@adhdev/daemon-standalone 0.9.82-rc.555 → 0.9.82-rc.558
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 +92 -28
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/public/assets/index-CfKeorNX.js +116 -0
- package/public/assets/{terminal-D_AgDYO_.js → terminal-DM8Grzs9.js} +1 -1
- package/public/assets/vendor-CECp-jXJ.js +2776 -0
- package/public/index.html +2 -2
- package/vendor/mcp-server/index.js +9 -1
- package/vendor/mcp-server/index.js.map +1 -1
- package/public/assets/index-Ct_5xMxw.js +0 -116
- package/public/assets/vendor-MlvUnxKA.js +0 -2768
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-DM8Grzs9.js","assets/vendor-CECp-jXJ.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
var gh=Object.defineProperty;var yh=(e,t,r)=>t in e?gh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var st=(e,t,r)=>yh(e,typeof t!="symbol"?t+"":t,r);import{r as l,j as s,M as wi,a as vh,b as wh,c as jh,t as kh,d as Sh,u as Pt,i as yt,e as Nh,f as hr,R as Lt,g as mn,h as Fo,k as Oo,D as Ch,E as Ih,l as Ah,C as Mh,m as Th,B as _h,n as Lh,o as Rh,p as Ph,H as vn,P as Ns,q as Dh,s as $h,v as Eh,w as Bh,x as Fh,y as Oh,z as ji,A as Hh,F as Wh,G as Kh,I as Uh,J as Cs,N as Ho,K as Gh}from"./vendor-CECp-jXJ.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 zh(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 fr=zh();function kl(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 Vh(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Sl(e){return Array.isArray(e)?[...e]:[]}function Ld(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?Sl(e.messages):i?[]:t.messages,activeModal:n?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...r?{messages:Sl(e.messages)}:{},...n?{activeModal:e.activeModal??null}:{}}}function Gr(e,t){const r=Vh(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:Ld(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),muted:e.muted??(t==null?void 0:t.muted),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 Rd(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?Gr(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 Nl(e){return!!e&&typeof e=="object"&&"text"in e}function ki(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:Nl(o)?String(o.text||""):"").join(r):Nl(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function xr(e){return ki(e,{normalizeWhitespace:!0})}function qh(e){let t="";for(let r=0;r<e.length;r++){const n=e[r],a=e.charCodeAt(r);if(!(a<=31&&n!==`
|
|
3
|
+
`&&n!==" ")&&!(a>=127&&a<=159)&&!(a>=8203&&a<=8207||a>=8234&&a<=8238||a===8288||a===65279)&&a!==65533){if(a===65038||a===65039){const o=t.length>0?t[t.length-1]:"";if(!o||o===`
|
|
4
|
+
`||o===" "||o===" ")continue}t+=n}}return t}function Cl(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 Pd(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 Yh(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 Wa(e){if(!e||typeof e!="object")return"";const t=e,r=Yh(xr(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 Jh(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=Wa(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:Wa(e[0]),last:Wa(e[e.length-1])}}function Wo(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function Ko(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(Wo(e)&&Wo(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)Ko(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"&&Ko(n[i],a[i],r)}function Yr(e,t){return Array.isArray(e)?e.map(r=>Yr(r,t)):!e||typeof e!="object"?e:Wo(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?Jh(a,t):Yr(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,Yr(n,t)]))}function Xh(e,t){try{const r=new WeakSet;return Ko(e,t,r),JSON.stringify(Yr(e,r))===JSON.stringify(Yr(t,r))}catch{return!1}}function Uo(e,t,r){return Xh(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Dd(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function Qh(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function Il(e,t,r,n){var d;const a=(d=t.chats)!=null&&d.length?t.chats:e.chats,o=Rd(e.childSessions,t.childSessions,{preserveMissing:n}),i=Ld(t.activeChat,e.activeChat),c=t.workspace||e.workspace;return Pd(e,t,{...e,...t,chats:a,childSessions:o,activeChat:i,workspace:c,_lastUpdate:r})}function Zh(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=Rd(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((o=e.chats)!=null&&o.length)&&(n.chats=t.chats),t.workspace&&(n.workspace=t.workspace);for(const i of["title","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","activeInteractivePrompt","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","muted","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion","versionUpdateReason","versionUpdateRequired","updateCommand","updatePolicy","updateChannel","releaseChannel"])Qh(n,t,i);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function ef(e,t,r,n){const a=Zh(e,t,n),o=Object.keys(a).length>0?Pd(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return Uo(e,o,r)}function tf(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=Dd(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 sf(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 rf(e,t,r,n,a){return e.transport?r.has(t)&&!n.has(t)?!0:a.has(t):!1}function nf(e,t,r){var u,m;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(h=>({...h,_lastUpdate:n}));const o=new Map;for(const h of t)o.set(h.id,h);const{incomingIds:i,incomingDaemonIds:c,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:p}=tf(e);for(const h of e){const g=o.get(h.id);if(!g){o.set(h.id,{...h,_lastUpdate:n});continue}const k=Cl(h),f=Cl(g),v=Dd(h),w=!a.has(v);if(k>f){const C=Il(g,h,n,w);o.set(h.id,Uo(g,C,n));continue}if(k<f){o.set(h.id,ef(g,h,n,w));continue}const x=h.timestamp||n,j=g._lastUpdate||g.timestamp||0;if(x>=j){const C=Il(g,h,n,w);o.set(h.id,Uo(g,C,n));continue}(u=h.chats)!=null&&u.length&&!((m=g.chats)!=null&&m.length)&&o.set(h.id,{...g,chats:h.chats})}for(const[h,g]of o){const k=g.daemonId||h.split(":")[0];if(!c.has(k))continue;if(a.has(k)&&p.has(k)&&!i.has(h)){o.delete(h);continue}const f=n-(g._lastUpdate||g.timestamp||0);sf(g,k,f,i,a,d)&&o.delete(h)}for(const[h,g]of o){const k=g.daemonId||h.split(":")[0];if(rf(g,k,c,d,o))continue;n-(g._lastUpdate||g.timestamp||0)>3e5&&g.status!=="online"&&o.delete(h)}return Array.from(o.values())}function af(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}const $d=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}),Ed=l.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function of({children:e,connectionOverrides:t}){const[r,n]=l.useState([]),[a,o]=l.useState(!1),[i,c]=l.useState([]),[d,p]=l.useState(void 0),u=l.useRef(r);l.useEffect(()=>{u.current=r},[r]);const m=l.useCallback((w,x)=>{n(j=>{let C=!1;const y=j.map(b=>b.id!==w||b.chats===x?b:(C=!0,{...b,chats:x}));return C?y:j})},[]),h=l.useCallback((w,x)=>{n(j=>{const C=j.length===0?w:nf(w,j,x),y=!af(j,C);return y&&fr.record({kind:"dashboard.entries_applied",payload:{incoming:kl(w),next:kl(C)}}),y?C:j})},[]),g=l.useCallback(()=>o(!0),[]),k=l.useMemo(()=>({injectEntries:h,markLoaded:g,getIdes:()=>u.current}),[h,g]),f=t,v=l.useMemo(()=>({ides:r,updateRouteChats:m,initialLoaded:a,toasts:i,setToasts:c,wsStatus:(f==null?void 0:f.wsStatus)??"connected",isConnected:(f==null?void 0:f.isConnected)??!0,connectionStates:(f==null?void 0:f.connectionStates)??{},connectionTransports:(f==null?void 0:f.connectionTransports)??{},showReconnected:(f==null?void 0:f.showReconnected)??!1,retryConnection:f==null?void 0:f.retryConnection,retryServerConnection:f==null?void 0:f.retryServerConnection,connectionLoginUrl:f==null?void 0:f.connectionLoginUrl,isP2PActive:(f==null?void 0:f.isP2PActive)??!1,p2pStates:(f==null?void 0:f.p2pStates)??{},userRole:f==null?void 0:f.userRole,connectionRetryStatuses:f==null?void 0:f.connectionRetryStatuses,userName:d,setUserName:p}),[r,m,a,i,f==null?void 0:f.wsStatus,f==null?void 0:f.isConnected,f==null?void 0:f.connectionStates,f==null?void 0:f.connectionTransports,f==null?void 0:f.showReconnected,f==null?void 0:f.retryConnection,f==null?void 0:f.retryServerConnection,f==null?void 0:f.connectionLoginUrl,f==null?void 0:f.isP2PActive,f==null?void 0:f.p2pStates,f==null?void 0:f.userRole,f==null?void 0:f.connectionRetryStatuses,d]);return s.jsx(Ed.Provider,{value:k,children:s.jsx($d.Provider,{value:v,children:e})})}function gs(){return l.useContext($d)}function nn(){return l.useContext(Ed)}function Bd(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),u=c.startsWith("http")?new URL(p):new URL(p,typeof window<"u"?window.location.origin:"http://localhost");return d&&u.searchParams.set("token",d),!c.startsWith("http")&&!t?`${u.pathname}${u.search}${u.hash}`:u.toString()}async function i(c,d={}){const p={"Content-Type":"application/json",...d.headers||{}},u=r==null?void 0:r();u&&(p.Authorization=`Bearer ${u}`);const m=a(c),h=new AbortController,g=setTimeout(()=>h.abort(),15e3);try{const k=await fetch(m,{...d,headers:p,signal:h.signal});if(k.status===401)throw n==null||n(),new Error("Unauthorized");if(!k.ok){const f=await k.json().catch(()=>({error:k.statusText}));throw new Error(f.error||`API Error: ${k.status}`)}return k.json()}finally{clearTimeout(g)}}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 lf=Bd({baseUrl:"http://localhost:3847"}),cf=l.createContext(lf);function df({client:e,children:t}){return s.jsx(cf.Provider,{value:e,children:t})}const uf={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Fd=l.createContext(uf);function pf({value:e,children:t}){return s.jsx(Fd.Provider,{value:e,children:t})}function bt(){return l.useContext(Fd)}function Od(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function mf(e){const t=Od(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 hf(e){const[t,r]=l.useState(null),n=l.useCallback(async(i,c)=>{const d=m=>e(i,"launch_cli",{...c,...m}),p=await d({}),u=mf(p);return u?new Promise(m=>{r({providerType:u.providerType||String(c.cliType??"?"),sourceName:u.sourceName,description:u.description,retry:()=>d({confirmExternalUntrusted:!0}),resolve:h=>{h.cancelled?m({success:!1,error:"user_cancelled_untrusted_launch"}):m(h.response)}})}):p},[e]),a=l.useCallback(async()=>{const i=t;if(i){r(null);try{const c=await i.retry(),d=Od(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 ff({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 Hd=l.createContext(null);function xf({sendDaemonCommand:e,children:t}){const r=hf(e),n=l.useMemo(()=>({launchCli:r.launchCli}),[r.launchCli]);return s.jsxs(Hd.Provider,{value:n,children:[t,r.pending&&s.jsx(ff,{providerType:r.pending.providerType,sourceName:r.pending.sourceName,description:r.pending.description,onConfirm:r.confirm,onCancel:r.cancel})]})}function wa(){const e=l.useContext(Hd);return e||{launchCli:async()=>{throw new Error("useLaunchCli must be used inside <LaunchCliProvider>")}}}function Wd(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function bf(e,t,r){return Number(e.receivedAt||r[ta(e)]||0)||0}function Kd(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function gf(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function _r(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 Ka(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 yf(e){let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t^e.charCodeAt(r),t|=0;return(t>>>0).toString(36)}function ta(e,t){const r=e,n=ki(e.content,{joiner:`
|
|
5
|
+
`}),a=[e.id?`id:${e.id}`:"",r._localId?`local:${r._localId}`:"",r._turnKey?`turn:${r._turnKey}`:"",e.bubbleId?`bubble:${e.bubbleId}`:"",e.providerUnitKey?`unit:${e.providerUnitKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",typeof e.sequence=="number"?`seq:${e.sequence}`:""].filter(Boolean);if(a.length>0)return a.join("|");const o=e.receivedAt||e.timestamp||0;return[e.role?`role:${e.role}`:"role:",`chash:${yf(n)}`,o?`ts:${o}`:""].filter(Boolean).join("|")}function vf(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 wf(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Ud(e){return e?vf([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),wf(e.content)]):""}const Si=200,jf=80,Al=650,Lr=new Map;function sa(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function kf(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}:${Ud(n)}`}function Sf(e,t,r,n){return e||!t?!1:sa(r,n)}function Nf({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=jf,bottomThresholdPx:a=Si}){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 Cf(e){return Nf({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function zr(e,t=Si){return!!e&&e.fromBottom>=t}function If(e,t){return sa(e,t)?!zr(e):!0}function Af({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function Mf({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function Ua(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}const ze={size:18};function Gd({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function Ni({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polyline",{points:"15 18 9 12 15 6"})})}function Ts({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),s.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),s.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),s.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function zd({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"9",cy:"7",r:"4"}),s.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),s.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Tf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function _f({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function Vd({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),s.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),s.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),s.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function qd({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),s.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),s.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),s.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),s.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function Lf({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polyline",{points:"20 6 9 17 4 12"})})}function ja({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function Ci({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),s.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function Rf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("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 Pf({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Zs({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function ds({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Ii({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("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 br({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function ka({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function Ys({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),s.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),s.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function an({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M12 22v-5"}),s.jsx("path",{d:"M9 8V2"}),s.jsx("path",{d:"M15 8V2"}),s.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function Zt({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"5",r:"2"}),s.jsx("circle",{cx:"5",cy:"19",r:"2"}),s.jsx("circle",{cx:"19",cy:"19",r:"2"}),s.jsx("line",{x1:"12",y1:"7",x2:"5",y2:"17"}),s.jsx("line",{x1:"12",y1:"7",x2:"19",y2:"17"}),s.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"19"})]})}function Df({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("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 Yd({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Ai({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"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 Jd({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function $f({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),s.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),s.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function Mi({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"4 17 10 11 4 5"}),s.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function Ef({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Xd({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Ti({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function Nt({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Bf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("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 Ff({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("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 Of({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function Hf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("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 Nr({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),s.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function Qd({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M8.7 3A6 6 0 0 1 18 8c0 3 .6 5 1.4 6.5"}),s.jsx("path",{d:"M17 17H3s3-2 3-9a5.98 5.98 0 0 1 .6-2.6"}),s.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"}),s.jsx("line",{x1:"2",y1:"2",x2:"22",y2:"22"})]})}function Wf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"5"}),s.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),s.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),s.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),s.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),s.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),s.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),s.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),s.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function Kf({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function Uf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Zd({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),s.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function Gf({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function zf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),s.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]})}function Vf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("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 qf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),s.jsx("path",{d:"M13 2h9v9"}),s.jsx("path",{d:"M22 2L13 11"})]})}function Yf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"9 14 4 9 9 4"}),s.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function Jf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),s.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),s.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),s.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),s.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),s.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),s.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),s.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),s.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),s.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function Xf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"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 Qf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),s.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}function Zf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),s.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]})}const eu="adhdev_chat_activity_visible",Ml=new Set(["hidden","debug","internal"]),Tl=new Set(["visible","user","chat"]),ex=new Set(["debug","trace","internal"]),tx=new Set(["tool_call","terminal_command","runtime_activity"]),sx=new Set(["runtime_status","provider_chrome","control"]),rx=new Set(["thought","tool","terminal"]);function tu(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function nr(e){return typeof e=="string"?e.trim().toLowerCase():""}function Ga(e,t,r){return e[r]??(t==null?void 0:t[r])}function _l(e,t,r){const n=e;return r.some(a=>n[a]===!0||(t==null?void 0:t[a])===!0)}function nx(e,t){const r=nr(e.kind);return r||(t==="tool"?"tool":"standard")}function za(e,t,r){const n=tu(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 ax(e){const t=e.content;return Array.isArray(t)&&t.some(r=>!!r&&typeof r=="object"&&r.type!=="text")}function _i(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=tu(e),r=nr(e.role),n=nx(e,r),a=nr(Ga(e,t,"visibility")),o=nr(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??a),i=nr(Ga(e,t,"audience")),c=nr(Ga(e,t,"source")),d=Ml.has(a)||Ml.has(o)||ex.has(i)||_l(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),p=Tl.has(a)||Tl.has(o)||i==="chat"||_l(e,t,["userFacing"]),u=rx.has(n)||tx.has(c);if(d)return{surface:u?"activity":"internal",isUserFacing:!1,isActivityFacing:u,isInternal:!u,role:r,kind:n,label:za(e,n,c)};if(p)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:za(e,n,c)};if((r==="system"||n==="system")&&ax(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:"Chat"};if(sx.has(c)||r==="system"||n==="system")return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:r,kind:n,label:"Internal"};if(u)return{surface:"activity",isUserFacing:!1,isActivityFacing:!0,isInternal:!1,role:r,kind:n,label:za(e,n,c)};const m=(r==="user"||r==="human"||r==="assistant")&&(n==="standard"||n==="");return{surface:m?"chat":"internal",isUserFacing:m,isActivityFacing:!1,isInternal:!m,role:r,kind:n,label:m?"Chat":"Internal"}}function ox(e){return(Array.isArray(e)?e:[]).filter(t=>_i(t).isUserFacing)}function su(e){return(Array.isArray(e)?e:[]).filter(t=>_i(t).isActivityFacing)}function ru(e){const t=e.content;return typeof t=="string"?t:(()=>{try{return JSON.stringify(t??"")}catch{return String(t??"")}})()}function ix(e){return`${String(e.role||"")}::${ru(e)}`}function lx(e){if(e.length<2)return e;const t=[];let r="";for(const n of e){const a=ix(n);ru(n).trim().length>0&&a===r||(t.push(n),r=a)}return t}function cx(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 Ll(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(eu))==="1"}catch{return!1}}function dx({text:e}){const[t,r]=l.useState(!1),n=l.useCallback(()=>{navigator.clipboard.writeText(e).catch(()=>{}),r(!0),setTimeout(()=>r(!1),1500)},[e]);return s.jsx("button",{type:"button",onClick:n,"aria-label":"메시지 복사",className:"chat-copy-btn",children:t?s.jsx(Lf,{size:11}):s.jsx(qd,{size:11})})}const nu=[vh,{singleTilde:!1}],au=[nu,wh,jh],ux=[nu];function wn(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 Rl(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):Kd(e)?s.jsx(wi,{remarkPlugins:au,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}const px=l.memo(function({content:t,renderAsPreformatted:r,renderAsMarkdown:n}){return r?s.jsx("pre",{className:"chat-preformatted",children:t}):n?s.jsx(wi,{remarkPlugins:au,children:t}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:t})});function Rr({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:Rl(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=Ka(r),o=r.alt||r.description||_r(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:wn("Image",o,r.mimeType)},`image-fallback-${n}`)}if(r.type==="audio"){const a=Ka(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:wn("Audio",_r(r.uri,"audio"),r.transcript||r.mimeType)},`audio-fallback-${n}`)}if(r.type==="video"){const a=Ka(r),o=r.title||r.name||r.alt||_r(r.uri,"video"),i=[r.transcript,r.description,r.mimeType].filter(Boolean).join(`
|
|
6
|
+
`);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"}):wn("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||_r(r.uri,"resource"),o=[r.description,r.mimeType].filter(Boolean).join(`
|
|
7
|
+
`);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}):wn("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=_r(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}),Rl(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})})}const mx=l.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(wi,{remarkPlugins:ux,children:t.text}),s.jsx("span",{className:"action-time",children:Wd(t.timestamp)})]})},(e,t)=>e.log===t.log);function Pl(e){const t=e.meta;return[Ud(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 hx=l.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:o,isTextExpanded:i,onToggleTextExpanded:c}){var S,I,R;const d=(t.role||"").toLowerCase(),p=d==="user"||d==="human",u=t.kind||(d==="tool"?"tool":"standard"),m=_i(t),h=gf(t.content)?t.content:null,g=!!(h!=null&&h.some(L=>L.type!=="text")),k=ki(t.content,{joiner:`
|
|
8
|
+
`});if(m.isActivityFacing&&u!=="thought"&&u!=="tool"&&u!=="terminal"){const L=m.label||"Activity";return s.jsxs("div",{className:"self-start chat-msg-activity","data-chat-activity-row":"true",children:[s.jsxs("div",{className:"chat-msg-activity-meta","aria-label":"Activity message",children:[s.jsx("span",{className:"activity-dot"}),s.jsx("span",{children:L})]}),g&&h?s.jsx("div",{className:"chat-msg-activity-body",children:s.jsx(Rr,{parts:h,renderAsPreformatted:!1})}):s.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:k})]})}if(u==="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":m.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(Of,{size:13}),s.jsx("span",{children:L})]}),s.jsx("div",{className:"chat-msg-body",children:k})]})}if(u==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":m.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-tool-meta","aria-label":"Tool message",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),s.jsx("span",{className:"tool-label",children:"Tool"})]}),g&&h?s.jsx("div",{className:"tool-text w-full",children:s.jsx(Rr,{parts:h,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:k})]});if(u==="terminal"){const L=(I=t.meta)!=null&&I.isRunning?"⏳":"✅",M=typeof((R=t.meta)==null?void 0:R.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal","data-chat-activity-row":m.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:L}),s.jsx("span",{children:M})]}),g&&h?s.jsx("div",{className:"chat-msg-body",children:s.jsx(Rr,{parts:h,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:k})]})}if(u==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:g&&h?s.jsx(Rr,{parts:h,renderAsPreformatted:!1}):k.slice(0,100)});const f=t.meta,w=(typeof(f==null?void 0:f.renderMode)=="string"?f.renderMode.trim():"")==="preformatted",x=k,j=!1,C=x,y=w,b=!p&&!y&&Kd(C),N=["chat-message-row",p?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return s.jsx("div",{className:N,children:(x||g||p)&&s.jsxs("div",{className:`chat-bubble ${p?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${x||g?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:p?a||"You":t.senderName||n}),s.jsxs("span",{className:"chat-bubble-header-end",children:[(x||g)&&s.jsx(dx,{text:k}),r!=null&&s.jsx("span",{className:"chat-time",children:Wd(r)})]})]}),(x||g)&&s.jsx("div",{className:"chat-markdown",children:g&&h?s.jsx(Rr,{parts:h,renderAsPreformatted:y}):s.jsx(px,{content:C,renderAsPreformatted:y,renderAsMarkdown:b})}),j]})})},(e,t)=>(e.message===t.message||Pl(e.message)===Pl(t.message))&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),fx=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:u=!1,emptyState:m,onLoadMore:h,isLoadingMore:g,hasMoreHistory:k,hiddenLiveCount:f=0,loadError:v,scrollToBottomRequestNonce:w,isVisible:x=!0},j){const C=l.useRef(null),y=l.useRef(null),b=l.useRef(null),N=l.useRef(0),S=l.useRef(""),I=l.useRef(""),R=l.useRef(!1),L=l.useRef(null),M=l.useRef(!1),P=l.useRef(null),$=l.useRef(!1),[Y,_]=l.useState(new Set),[H,W]=l.useState({showTop:!1,showBottom:!1}),B=l.useRef(!1),T=l.useRef(!1),A=l.useRef(x),E=l.useRef(x),z=l.useRef(null);E.current=x;const G=()=>{const le=C.current;return le?le.scrollHeight-le.scrollTop-le.clientHeight<Si:!0},re=l.useCallback(()=>{const le=C.current,D=le?Cf(le):{showTop:!1,showBottom:!1};W(de=>de.showTop===D.showTop&&de.showBottom===D.showBottom?de:D)},[]),X=l.useCallback((le="auto")=>{var de;const D=C.current;D&&(D.scrollTo({top:D.scrollHeight,behavior:le}),(de=D.ownerDocument.defaultView)==null||de.requestAnimationFrame(()=>re()))},[re]),te=l.useCallback((le="auto")=>{var de;const D=C.current;D&&(D.scrollTo({top:0,behavior:le}),(de=D.ownerDocument.defaultView)==null||de.requestAnimationFrame(()=>re()))},[re]),J=l.useCallback(()=>{var ue;const le=C.current,D=(ue=window.getSelection)==null?void 0:ue.call(window);if(!le||!D||D.rangeCount===0||D.isCollapsed){$.current=!1;return}const de=D.anchorNode,Se=D.focusNode;$.current=!!(de&&Se&&le.contains(de)&&le.contains(Se))},[]),F=l.useMemo(()=>{const le=ox(t),D=su(t);return lx(cx(le,D,u))},[t,u]),K=F.length===t.length?p:void 0,fe=kf(F,K),be=l.useCallback(()=>{const le=C.current;if(!le||!c||!E.current)return;const D={top:le.scrollTop,fromBottom:Math.max(0,le.scrollHeight-le.scrollTop-le.clientHeight),messageFingerprint:fe};z.current={contextKey:c,snapshot:D},Lr.set(c,D)},[c,fe]),oe=l.useCallback((le="auto")=>{L.current!=null&&cancelAnimationFrame(L.current),L.current=requestAnimationFrame(()=>{L.current=null,X(le)})},[X]),je=l.useCallback(()=>{B.current=!1,M.current=!0,T.current=!0,P.current!=null&&window.clearTimeout(P.current),P.current=window.setTimeout(()=>{M.current=!1,P.current=null},Al)},[]);l.useEffect(()=>{const le=!R.current,D=I.current!==c;if(I.current=c,le||D){R.current=!0;const Se=c?Lr.get(c):null,ue=!!Se&&sa(Se,fe);B.current=ue?zr(Se):!1,M.current=If(Se,fe),$.current||(ue?requestAnimationFrame(()=>{const q=C.current;q&&(Ua(q,Se),B.current=zr(Se),re(),T.current=!0)}):oe("auto")),N.current=F.length,S.current=fe;return}F.length>N.current;const de=fe!==S.current;Af({hasSelection:$.current,userScrolledUp:B.current,hasChatContentChanged:de})&&oe("auto"),N.current=F.length,S.current=fe},[fe,c,F.length,oe,re]),l.useEffect(()=>{w&&(je(),$.current||oe("auto"))},[je,oe,w]),l.useEffect(()=>{const le=A.current;le&&!x&&be(),E.current=x,A.current=x;const D=c?Lr.get(c):null;if(Sf(le,x,D,fe)){if(!D)return;B.current=zr(D),M.current=!1,$.current||requestAnimationFrame(()=>{const de=C.current;de&&(Ua(de,D),re())});return}},[x,c,fe,je,be,oe,re]),l.useEffect(()=>()=>{const le=z.current;le&&Lr.set(le.contextKey,le.snapshot),L.current!=null&&cancelAnimationFrame(L.current),P.current!=null&&window.clearTimeout(P.current)},[]),l.useEffect(()=>{const le=y.current,D=C.current;if(!le||!D)return;const de=()=>{P.current!=null&&window.clearTimeout(P.current),P.current=window.setTimeout(()=>{M.current=!1,P.current=null},Al)},Se=new ResizeObserver(()=>{re();const ue=M.current;Mf({hasSelection:$.current,userScrolledUp:B.current,contextAutoScrollActive:ue})&&(oe("auto"),ue&&de())});return Se.observe(le),D!==le&&Se.observe(D),()=>{Se.disconnect(),P.current!=null&&(window.clearTimeout(P.current),P.current=null)}},[oe,c,re]),l.useImperativeHandle(j,()=>({scrollToBottom:(le="smooth")=>{X(le)}}),[X]),l.useEffect(()=>{const le=C.current;if(!le)return;let D;const de=()=>{be(),clearTimeout(D),D=setTimeout(()=>{B.current=!G(),re()},50)};return le.addEventListener("scroll",de,{passive:!0}),()=>{le.removeEventListener("scroll",de),clearTimeout(D)}},[be,re]),l.useEffect(()=>(document.addEventListener("selectionchange",J),()=>document.removeEventListener("selectionchange",J)),[J]);const ge=l.useRef(0),we=l.useRef(!1);l.useEffect(()=>{const le=C.current;if(!le||!we.current||ge.current===0)return;const D=le.scrollHeight-ge.current;D>0&&(le.scrollTop=D),re(),be(),ge.current=0,we.current=!1},[F.length,be,re]),l.useEffect(()=>{if(T.current||!c)return;const le=Lr.get(c),D=C.current;if(!(!le||!D)){if(!sa(le,fe)){X("auto"),T.current=!0;return}Ua(D,le),B.current=zr(le),re(),T.current=!0}},[c,fe,F.length,X,re]);const me=()=>{const le=C.current;le&&(ge.current=le.scrollHeight),we.current=!0,h==null||h()},U=()=>{B.current=!0,te("smooth"),be()},O=()=>{je(),X("smooth"),be()},Z=l.useMemo(()=>{const le=F.map((ue,q)=>({type:"message",data:ue,index:q,ts:bf(ue,q,d)}));if(!r||r.length===0)return le;const D=[...r].sort((ue,q)=>ue.timestamp-q.timestamp).map((ue,q)=>({type:"action",data:ue,index:q,ts:ue.timestamp})),de=[];let Se=0;for(const ue of le){for(;Se<D.length&&ue.ts>0&&D[Se].ts<ue.ts;)de.push(D[Se++]);de.push(ue)}for(;Se<D.length;)de.push(D[Se++]);return de},[F,r,d]),V=f>0||!!k,he=f>0?`↑ Show ${Math.min(f,80)} earlier messages${f>80?` (${f} hidden)`:""}`:v?`↻ ${v}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:C,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:y,className:"chat-container-content",children:[g&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),V&&!g&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:me,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${v&&f===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:he})}),Z.length===0&&!V&&(m||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),Z.map(le=>{if(le.type==="action"){const ve=le.data;return s.jsx(mx,{log:ve},`action-${le.index}`)}const D=le.data;le.index;const de=ta(D),Se=D.receivedAt||d[de],ue=`${c}-${de}`,q=Y.has(ue);return s.jsx(hx,{message:D,receivedAt:Se,agentName:n,userName:a,isCliMode:o,isTextExpanded:q,onToggleTextExpanded:()=>_(ve=>{const Ae=new Set(ve);return q?Ae.delete(ue):Ae.add(ue),Ae})},`msg-${de}`)}),i&&s.jsx("div",{className:"self-start chat-typing-wrapper",children:s.jsxs("div",{className:"typing-indicator",children:[s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),s.jsx("div",{className:"min-h-10",ref:b})]})}),(H.showTop||H.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[H.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"}),H.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:O,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),xx=l.memo(fx,(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),bx="modulepreload",gx=function(e){return"/"+e},Dl={},yx=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=gx(d),d in Dl)return;Dl[d]=!0;const p=d.endsWith(".css"),u=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const m=document.createElement("link");if(m.rel=p?"stylesheet":bx,p||(m.as="script"),m.crossOrigin="",m.href=d,c&&m.setAttribute("nonce",c),document.head.appendChild(m),p)return new Promise((h,g)=>{m.addEventListener("load",h),m.addEventListener("error",()=>g(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 $l=!1;const ou=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),u=l.useRef([]),m=l.useRef(!1),h=l.useRef(!1),g=l.useRef(!1),k=l.useRef(!1),f=()=>{const v=c.current;if(v){m.current&&(v.clear(),m.current=!1);for(const w of u.current)v.write(w.data,w.onProcessed);u.current=[],h.current&&(v.fit(),h.current=!1),g.current&&(v.bumpResize(),g.current=!1),k.current&&(v.scrollToTop(),k.current=!1)}};return l.useImperativeHandle(i,()=>({write:(v,w)=>{c.current?c.current.write(v,w):u.current.push({data:v,onProcessed:w})},clear:()=>{c.current?c.current.clear():(u.current=[],m.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(u.current=[],m.current=!0)},resize:(v,w)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(v,w)},fit:()=>{c.current?c.current.fit():h.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():g.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():k.current=!0},getSelection:()=>{var v,w;return((w=(v=c.current)==null?void 0:v.getSelection)==null?void 0:w.call(v))||""},getVisibleText:()=>{var v,w;return((w=(v=c.current)==null?void 0:v.getVisibleText)==null?void 0:w.call(v))||""}}),[]),l.useEffect(()=>{d&&f()},[d]),l.useEffect(()=>{let v=!1;return yx(()=>import("./terminal-DM8Grzs9.js"),__vite__mapDeps([0,1,2])).then(w=>{$l||($l=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),v||p(()=>w.GhosttyTerminalView)}).catch(w=>{console.error("[CliTerminal] failed to load terminal renderer",w)}),()=>{v=!0}},[]),d?s.jsx(d,{ref:c,onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n,readOnly:a,sizingMode:o,className:"w-full h-full rounded-lg overflow-hidden"}):s.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});ou.displayName="CliTerminal";function Ft(...e){return kh(Sh(e))}const vx={lg:"rounded-lg",xl:"rounded-xl","2xl":"rounded-2xl"},wx={none:"",sm:"p-3",md:"px-4 py-3.5",lg:"px-5 py-4"},Ss=l.forwardRef(function({radius:t="xl",padding:r="md",className:n,...a},o){return s.jsx("div",{ref:o,className:Ft("border border-border-subtle bg-bg-secondary",vx[t],wx[r],n),...a})});function jn({label:e,value:t,sub:r,icon:n}){return s.jsxs(Ss,{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 El({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 jx({cursorPos:e,viewportRef:t,imgRef:r}){var x;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),o=(x=t.current)==null?void 0:x.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 u,m,h,g;d>p?(u=a.width,m=a.width/d,h=0,g=(a.height-m)/2):(m=a.height,u=a.height*d,h=(a.width-u)/2,g=0);const k=a.left-o.left+h+u*e.nx,f=a.top-o.top+g+m*e.ny,v=Math.max(8,Math.min(o.width-8,k)),w=Math.max(8,Math.min(o.height-8,f));return s.jsxs("div",{style:{position:"absolute",left:v-8,top:w-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 kx({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:o,imeText:i,setImeText:c,handleImeSubmit:d,isConnActive:p,zoom:u,isMobile:m,mobileFillZoom:h,onZoomOut:g,onZoomReset:k,onZoomIn:f,transportType:v,screenshotUsage:w,lastActionStatus:x}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:j=>j.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(j=>!j),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:j=>j.stopPropagation(),onChange:j=>c(j.target.value),onKeyDown:j=>{d(j)},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(j=>!j),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"})]}),u>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(u*100),"%"]}),v==="direct"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:"Direct P2P connection",children:"Direct"}),v==="relay"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),w&&w.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:w.budgetExhausted?"#ef4444":"#c4b5fd",background:w.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:w.budgetExhausted?"TURN blocked":`TURN ${w.dailyUsedMinutes}/${w.dailyBudgetMinutes}m`}),x&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:x})]})]}),a&&s.jsxs("div",{onTouchStart:j=>j.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",u<=(m?h:1)+.01?m?"FILL":"FIT":`${Math.round(u*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:j=>{j.stopPropagation(),g()},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:j=>{j.stopPropagation(),k()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:m?"FILL":"FIT"}),s.jsx("button",{onClick:j=>{j.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 Sx({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 Nx(){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 Bl(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 hn(e,t){const r=l.useRef(null),n=l.useRef(0);l.useEffect(()=>{if(!Nx())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,Bl(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,Bl(t[i])]))}),r.current=t})}function Cx({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:o,zoomRef:i,panXRef:c,panYRef:d,setPanX:p,setPanY:u,setZoom:m,lastWheelTimeRef:h,onAction:g,setLastActionStatus:k,spawnRippleFromNormalized:f,clampPan:v,isMobile:w,mobileFillZoom:x}){const[j,C]=l.useState(null),y=l.useRef(null),b=l.useRef(null),N=l.useRef(null),S=l.useRef(!1),I=l.useRef(null),R=l.useRef(0),L=l.useRef(null),M=l.useRef(1),P=l.useRef({x:0,y:0}),$=l.useRef(!1),Y=l.useRef(n),_=l.useRef(g),H=30,W=550,B=18,T=60,A=400,E=12,z=()=>{if(y.current)return;const X={nx:.5,ny:.5};y.current=X,C(X)};return l.useEffect(()=>{Y.current=n,n==="mouse"&&z()},[n]),l.useEffect(()=>{_.current=g},[g]),l.useEffect(()=>{const X=e.current;if(!X)return;const te=oe=>{if(!r.current)return null;const je=r.current.getBoundingClientRect();return!je.width||!je.height?null:{nx:Math.max(0,Math.min(1,(oe.clientX-je.left)/je.width)),ny:Math.max(0,Math.min(1,(oe.clientY-je.top)/je.height))}},J=(oe,je)=>{if(!r.current)return{dnx:0,dny:0};const ge=r.current,we=ge.getBoundingClientRect(),me=ge.naturalWidth||we.width,U=ge.naturalHeight||we.height,O=me/U,Z=we.width/we.height;let V,he;return O>Z?(V=we.width,he=we.width/O):(he=we.height,V=we.height*O),{dnx:oe/V,dny:je/he}},F=(oe,je,ge)=>{if(ge<=1.05)return;const we=-(oe-.5)*100,me=-(je-.5)*100,U=v(we,me,ge);(Math.abs(U.x-c.current)>.1||Math.abs(U.y-d.current)>.1)&&(p(U.x),u(U.y),c.current=U.x,d.current=U.y)},K=oe=>{const je=t.current;if(je&&oe.target instanceof Node&&je.contains(oe.target))oe.preventDefault();else return;if(oe.touches.length===1){const ge=oe.touches[0];b.current={x:ge.clientX,y:ge.clientY,time:Date.now()},N.current={x:ge.clientX,y:ge.clientY},$.current||(S.current=!1),I.current=setTimeout(()=>{if(!S.current&&!$.current)if(S.current=!0,Y.current==="mouse"){const we=y.current||{nx:.5,ny:.5};k("Right Click"),f(we.nx,we.ny,"right"),_.current("input_click",{...we,button:"right"}).catch(()=>{})}else{const we=te(ge);we&&(k("Right Click"),f(we.nx,we.ny,"right"),_.current("input_click",{...we,button:"right"}).catch(()=>{}))}},500);return}if(oe.touches.length===2){I.current&&clearTimeout(I.current),S.current=!0,$.current=!0;const ge=oe.touches[1].clientX-oe.touches[0].clientX,we=oe.touches[1].clientY-oe.touches[0].clientY;L.current=Math.sqrt(ge*ge+we*we),M.current=i.current,P.current={x:(oe.touches[0].clientX+oe.touches[1].clientX)/2,y:(oe.touches[0].clientY+oe.touches[1].clientY)/2}}},fe=oe=>{const je=t.current;if(je&&oe.target instanceof Node&&je.contains(oe.target)&&oe.preventDefault(),oe.touches.length===1&&N.current){const ge=oe.touches[0],we=ge.clientX-N.current.x,me=ge.clientY-N.current.y;if(!S.current&&b.current){const U=ge.clientX-b.current.x,O=ge.clientY-b.current.y;Math.sqrt(U*U+O*O)>8&&(S.current=!0,I.current&&clearTimeout(I.current))}if(S.current)if(Y.current==="mouse"){const U=J(we,me),O=y.current||{nx:.5,ny:.5},Z=Math.max(0,Math.min(1,O.nx+U.dnx)),V=Math.max(0,Math.min(1,O.ny+U.dny));y.current={nx:Z,ny:V},C({nx:Z,ny:V}),k(`Cursor: ${Math.round(Z*100)}%, ${Math.round(V*100)}%`),F(Z,V,i.current);const he=Date.now();he-h.current>=30&&(h.current=he,_.current("input_mouseMoved",{nx:Z,ny:V}).catch(()=>{}))}else if(i.current>1){const U=t.current;if(U){const O=U.clientWidth,Z=U.clientHeight,V=c.current+we/O*100,he=d.current+me/Z*100,le=v(V,he,i.current);p(le.x),u(le.y),c.current=le.x,d.current=le.y}}else{const U=te(ge);if(U){const O=Date.now();O-h.current>=40&&(h.current=O,k("Scroll"),_.current("input_wheel",{nx:U.nx,ny:U.ny,deltaX:Math.round(-we*2.5),deltaY:Math.round(-me*2.5)}).catch(()=>{}))}}N.current={x:ge.clientX,y:ge.clientY};return}if(oe.touches.length===2&&L.current!==null){const ge=oe.touches[1].clientX-oe.touches[0].clientX,we=oe.touches[1].clientY-oe.touches[0].clientY,U=Math.sqrt(ge*ge+we*we)/L.current,O=(oe.touches[0].clientX+oe.touches[1].clientX)/2,Z=(oe.touches[0].clientY+oe.touches[1].clientY)/2,V=O-P.current.x,he=Z-P.current.y,le=Math.abs(U-1)>.03;if(Y.current==="mouse"){if(le){const D=Math.max(o,Math.min(5,M.current*U));m(D),i.current=D}else if(Math.abs(V)>2||Math.abs(he)>2){const D=y.current||{nx:.5,ny:.5},de=Date.now();de-h.current>=30&&(h.current=de,k("Scroll"),_.current("input_wheel",{nx:D.nx,ny:D.ny,deltaX:Math.round(-V*3),deltaY:Math.round(-he*3)}).catch(()=>{}))}}else{const D=Math.max(o,Math.min(5,M.current*U));m(D),i.current=D;const de=t.current;if(de&&D>1){const Se=de.clientWidth,ue=de.clientHeight,q=c.current+V/Se*100,ve=d.current+he/ue*100,Ae=v(q,ve,D);p(Ae.x),u(Ae.y),c.current=Ae.x,d.current=Ae.y}}P.current={x:O,y:Z}}},be=oe=>{var je;if(I.current&&clearTimeout(I.current),L.current=null,oe.touches.length===1&&$.current){const ge=oe.touches[0];b.current={x:ge.clientX,y:ge.clientY,time:Date.now()},N.current={x:ge.clientX,y:ge.clientY},S.current=!0;return}if(oe.touches.length===0){if($.current){$.current=!1,S.current=!1;return}if(oe.changedTouches.length===1){const ge=oe.changedTouches[0],we=Date.now(),me=we-(((je=b.current)==null?void 0:je.time)||0),U=b.current?ge.clientX-b.current.x:0,O=b.current?ge.clientY-b.current.y:0,Z=Math.sqrt(U*U+O*O);if(Y.current==="mouse"){if(me<H||me>W||Z>B){S.current=!1;return}const V=y.current||te(ge);V&&(k(`Click: ${Math.round(V.nx*100)}%, ${Math.round(V.ny*100)}%`),f(V.nx,V.ny,"left"),_.current("input_click",{...V}).catch(()=>{}))}else{if(S.current){S.current=!1;return}if(me<T||me>A||Z>E){S.current=!1;return}const V=te(ge);if(!V)return;we-R.current<300?(k("Double tap"),f(V.nx,V.ny,"double"),_.current("input_click",{...V,clickCount:2}).catch(()=>{}),R.current=0):(k(`Tap: ${Math.round(V.nx*100)}%, ${Math.round(V.ny*100)}%`),f(V.nx,V.ny,"left"),_.current("input_click",{...V}).catch(()=>{}),R.current=we)}}S.current=!1}};return X.addEventListener("touchstart",K,{passive:!1}),X.addEventListener("touchmove",fe,{passive:!1}),X.addEventListener("touchend",be,{passive:!1}),()=>{X.removeEventListener("touchstart",K),X.removeEventListener("touchmove",fe),X.removeEventListener("touchend",be),I.current&&clearTimeout(I.current)}},[e,t,r,o,i,c,d,p,u,m,h,k,f,v]),{cursorPos:j,cursorPosRef:y,handleToggleInputMode:()=>{a(X=>{const te=X==="touch"?"mouse":"touch";return te==="mouse"&&z(),te})},handleZoomReset:()=>{const X=w?x:1;m(X),i.current=X,p(0),u(0),c.current=0,d.current=0}}}function iu({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,u]=l.useState(null),[m,h]=l.useState(""),[,g]=l.useState(!1),[k,f]=l.useState([]),v=l.useRef(0),[w,x]=l.useState(!1),[j,C]=l.useState(!1),y=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[b,N]=l.useState(y?"mouse":"touch"),[S,I]=l.useState(1),R=l.useRef(!1),[L,M]=l.useState(1),[P,$]=l.useState(0),[Y,_]=l.useState(0);hn("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:b,zoom:L,panX:P,panY:Y,isMenuOpen:w,isImeOpen:j});const H=l.useRef(0),W=l.useRef(L),B=l.useRef(P),T=l.useRef(Y);l.useEffect(()=>{W.current=L},[L]),l.useEffect(()=>{B.current=P},[P]),l.useEffect(()=>{T.current=Y},[Y]),l.useEffect(()=>{var me;(me=i.current)==null||me.focus()},[]);const A=r==="connected",E=n,z=A?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",G=A?"The remote stream is warming up":"Waiting for the remote stream to catch up";l.useEffect(()=>{if(!y||R.current||!E)return;const me=d.current,U=c.current;if(!me||!U)return;const O=()=>{const Z=U.clientWidth,V=U.clientHeight,he=me.naturalWidth,le=me.naturalHeight;if(!he||!le||!Z||!V)return;const D=Math.min(Z/he,V/le),Se=Math.max(Z/he,V/le)/D;Se>1.01&&(I(Se),M(Se),W.current=Se),R.current=!0};me.complete&&me.naturalWidth?O():me.addEventListener("load",O,{once:!0})},[E,y]);const re=.5;l.useEffect(()=>{L<=re&&($(0),_(0))},[L,re]);const X=(me,U,O)=>{if(O<=re)return{x:0,y:0};const Z=(O-1)/(2*O)*100,V=(O-1)/(2*O)*100;return{x:Math.max(-Z,Math.min(Z,me)),y:Math.max(-V,Math.min(V,U))}},te=(me,U)=>{if(!d.current)return null;const O=d.current.getBoundingClientRect();return!O.width||!O.height?null:{nx:Math.max(0,Math.min(1,(me-O.left)/O.width)),ny:Math.max(0,Math.min(1,(U-O.top)/O.height))}},J=(me,U,O)=>{const Z=c.current;if(!Z)return;const V=Z.getBoundingClientRect(),he=++v.current;f(le=>[...le,{id:he,x:me-V.left,y:U-V.top,type:O}]),setTimeout(()=>f(le=>le.filter(D=>D.id!==he)),600)},F=(me,U,O)=>{const Z=d.current,V=c.current;if(!Z||!V)return;const he=Z.getBoundingClientRect(),le=V.getBoundingClientRect(),D=Z.naturalWidth||he.width,de=Z.naturalHeight||he.height,Se=D/de,ue=he.width/he.height;let q,ve,Ae,Ne;Se>ue?(q=he.width,ve=he.width/Se,Ae=0,Ne=(he.height-ve)/2):(ve=he.height,q=he.height*Se,Ae=(he.width-q)/2,Ne=0);const Ke=he.left-le.left+Ae+q*me,ie=he.top-le.top+Ne+ve*U,Fe=++v.current;f($e=>[...$e,{id:Fe,x:Ke,y:ie,type:O}]),setTimeout(()=>f($e=>$e.filter(tt=>tt.id!==Fe)),600)},K=async me=>{var O;const U=te(me.clientX,me.clientY);if(U){u(`Click: ${Math.round(U.nx*100)}%, ${Math.round(U.ny*100)}%`),J(me.clientX,me.clientY,"left"),(O=i.current)==null||O.focus();try{const Z=await e("input_click",{nx:U.nx,ny:U.ny});Z!=null&&Z.success||t(`❌ Click failed: ${Z==null?void 0:Z.error}`)}catch(Z){t(`❌ Click error: ${Z.message||Z}`)}}},fe=async(me,U,O,Z=0)=>{try{await e("input_key",{type:O?"char":"keyDown",key:me,code:U,text:O?me:void 0,unmodifiedText:O?me:void 0,modifiers:Z})}catch(V){t(`❌ Key error: ${V.message||V}`)}},be=async me=>{if(me.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(me.key)&&me.preventDefault();let O=0;me.altKey&&(O|=1),me.ctrlKey&&(O|=2),me.metaKey&&(O|=4),me.shiftKey&&(O|=8),u(`Key: ${me.key}`),await fe(me.key,me.code,me.key.length===1,O)},oe=async me=>{if(me.key==="Enter"){if(me.nativeEvent.isComposing)return;if(m){const U=m;h(""),u(`IME Sent: ${U}`);try{const O=await e("input_type",{text:U});O!=null&&O.success||t(`❌ IME error: ${O==null?void 0:O.error}`)}catch(O){t(`❌ IME error: ${O.message}`)}}else u("Key: Enter"),await fe("Enter","Enter",!1)}};l.useEffect(()=>{const me=i.current;if(!me)return;const U=O=>{var Z;if((Z=d.current)!=null&&Z.contains(O.target)){O.preventDefault();const V=Date.now();if(V-H.current<40)return;H.current=V;const he=te(O.clientX,O.clientY);if(!he)return;u(`Scroll: ${Math.round(O.deltaY)}`),e("input_wheel",{nx:he.nx,ny:he.ny,deltaX:Math.round(O.deltaX),deltaY:Math.round(O.deltaY)}).catch(()=>{})}};return me.addEventListener("wheel",U,{passive:!1}),()=>me.removeEventListener("wheel",U)},[e]);const{cursorPos:je,handleToggleInputMode:ge,handleZoomReset:we}=Cx({containerRef:i,viewportRef:c,imgRef:d,inputMode:b,setInputMode:N,minZoom:re,zoomRef:W,panXRef:B,panYRef:T,setPanX:$,setPanY:_,setZoom:M,lastWheelTimeRef:H,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:F,clampPan:X,isMobile:y,mobileFillZoom:S});return s.jsxs("div",{ref:i,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:be,onContextMenu:me=>me.preventDefault(),onFocus:()=>g(!0),onBlur:()=>g(!1),tabIndex:0,children:[s.jsxs("div",{ref:c,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[E?s.jsx("img",{ref:d,src:E,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${L}) translate(${P}%, ${Y}%)`,transformOrigin:"center center",cursor:b==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:K,onContextMenu:me=>me.preventDefault(),onDragStart:me=>me.preventDefault()}):s.jsx(Sx,{waitingLabel:z,waitingHint:G,transportType:o}),b==="mouse"&&E&&s.jsx(jx,{cursorPos:je,viewportRef:c,imgRef:d}),k.map(me=>{const O={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[me.type];return s.jsxs("div",{style:{position:"absolute",left:me.x,top:me.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${O}, 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(${O}, 0.9)`,boxShadow:`0 0 12px rgba(${O}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},me.id)})]}),s.jsx(kx,{inputMode:b,onToggleInputMode:ge,isImeOpen:j,setIsImeOpen:C,isMenuOpen:w,setIsMenuOpen:x,imeText:m,setImeText:h,handleImeSubmit:oe,isConnActive:A,zoom:L,isMobile:y,mobileFillZoom:S,onZoomOut:()=>M(me=>Math.max(.5,me-.25)),onZoomReset:we,onZoomIn:()=>M(me=>Math.min(5,me+.25)),transportType:o,screenshotUsage:a,lastActionStatus:p}),s.jsx("style",{children:`
|
|
9
|
+
@keyframes slideUp {
|
|
10
|
+
from { opacity: 0; transform: translateY(6px); }
|
|
11
|
+
to { opacity: 1; transform: translateY(0); }
|
|
12
|
+
}
|
|
13
|
+
@keyframes slideUpSidebar {
|
|
14
|
+
from { opacity: 0; transform: translateY(6px); }
|
|
15
|
+
to { opacity: 1; transform: translateY(0); }
|
|
16
|
+
}
|
|
17
|
+
@keyframes click-ripple-ring {
|
|
18
|
+
0% { transform: scale(0.3); opacity: 1; }
|
|
19
|
+
100% { transform: scale(2.2); opacity: 0; }
|
|
20
|
+
}
|
|
21
|
+
@keyframes click-ripple-dot {
|
|
22
|
+
0% { transform: scale(1); opacity: 0.9; }
|
|
23
|
+
50% { transform: scale(1.8); opacity: 0.6; }
|
|
24
|
+
100% { transform: scale(0.5); opacity: 0; }
|
|
25
|
+
}
|
|
26
|
+
@keyframes remote-float {
|
|
27
|
+
0% { transform: translateY(0px); }
|
|
28
|
+
50% { transform: translateY(-7px); }
|
|
29
|
+
100% { transform: translateY(0px); }
|
|
30
|
+
}
|
|
31
|
+
`})]})}function Fl(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 Ix(e){var t;return Fl(e.activeInteractivePrompt)||Fl((t=e.activeChat)==null?void 0:t.activeInteractivePrompt)}function Ax(e){return e.sessionId||e.instanceId||e.id}function Mx(e,t){const r=typeof t=="string"?t.trim():"";for(const n of e){const a=Ix(n);if(!a)continue;const o=Ax(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 lu(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}}const Tx=200;function Ol(e){const t={};for(const r of(e==null?void 0:e.prompt.questions)||[])t[r.questionId]={selectedLabels:[],freeformText:""};return t}function Hl(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 _x({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-default bg-surface-secondary text-text-secondary hover:bg-surface-secondary 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-subtle"}`,children:r?s.jsx(Zd,{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 line-clamp-3 block text-xs leading-5 text-text-muted",children:t})]})]})})}function cu({promptSession:e,isSubmitting:t=!1,error:r,onSubmit:n,onCancel:a}){var R;const[o,i]=l.useState(()=>Ol(e)),[c,d]=l.useState(0),[p,u]=l.useState(!1),m=l.useRef(!1);l.useEffect(()=>{if(i(Ol(e)),d(0),u(!1),m.current=!1,!(e==null?void 0:e.prompt.promptId))return;const M=setTimeout(()=>{m.current=!0,u(!0)},Tx);return()=>clearTimeout(M)},[e==null?void 0:e.prompt.promptId]);const h=(e==null?void 0:e.prompt.questions)||[],g=h.length,k=c===g-1,f=g===1,v=h[c],w=v?o[v.questionId]:void 0,x=v?Hl(v,w):!1,j=l.useMemo(()=>e?e.prompt.questions.every(L=>Hl(L,o[L.questionId])):!1,[e,o]);if(!e)return null;const C=(L,M)=>{i(P=>{const $=P[L.questionId]||{selectedLabels:[]},Y=$.selectedLabels||[],_=L.multiSelect?Y.includes(M)?Y.filter(H=>H!==M):[...Y,M]:[M];return{...P,[L.questionId]:{...$,selectedLabels:_}}})},y=(L,M)=>{i(P=>({...P,[L]:{...P[L]||{selectedLabels:[]},freeformText:M}}))},b=()=>{c<g-1&&d(L=>L+1)},N=()=>{c>0&&d(L=>L-1)},S=()=>{!j||t||!m.current||n(o)},I=lu(e.prompt,o);return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50 px-4 pt-[calc(24px+env(safe-area-inset-top,0px))] pb-[calc(24px+env(safe-area-inset-bottom,0px))]",children:s.jsxs("div",{className:"flex max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-48px)] w-full max-w-2xl flex-col overflow-hidden rounded-lg border border-border-default bg-surface-primary shadow-2xl",children:[s.jsxs("div",{className:"flex shrink-0 items-start justify-between gap-4 border-b border-border-default 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(Ys,{size:15})," Action Required"]}),s.jsx("h2",{className:"mt-1 text-lg font-bold text-text-primary",children:e.title||e.providerType})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[!f&&s.jsxs("span",{className:"text-xs text-text-muted",children:[c+1," / ",g]}),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(Nt,{size:16})})]})]}),!f&&s.jsx("div",{className:"flex shrink-0 gap-1.5 px-5 pt-3",children:h.map((L,M)=>s.jsx("div",{className:`h-1.5 flex-1 rounded-full transition-colors ${M<c?"bg-accent-primary":M===c?"bg-accent-primary/60":"bg-border-default"}`},L.questionId))}),s.jsxs("div",{className:"min-h-0 flex-1 space-y-4 overflow-y-auto px-5 py-4",children:[v&&s.jsxs("section",{className:"space-y-3",children:[s.jsxs("div",{children:[v.header&&s.jsx("div",{className:"mb-1 text-xs font-semibold uppercase tracking-normal text-text-muted",children:v.header}),s.jsxs("div",{className:"text-sm font-semibold text-text-primary",children:[f?"":`${c+1}. `,v.question]}),v.multiSelect&&v.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:v.multiSelect?"group":"radiogroup","aria-label":v.question,children:v.options.map(L=>{var M;return s.jsx(_x,{label:L.label,description:L.description||L.preview,selected:(((M=I.answers[v.questionId])==null?void 0:M.selectedLabels)||[]).includes(L.label),multiSelect:v.multiSelect,disabled:t,onClick:()=>C(v,L.label)},L.label)})}),v.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:((R=o[v.questionId])==null?void 0:R.freeformText)||"",disabled:t,onChange:L=>y(v.questionId,L.currentTarget.value),className:"w-full min-h-20 rounded-md border border-border-default 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 shrink-0 items-center justify-between gap-2 border-t border-border-default px-5 pt-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))]",children:[s.jsx("div",{children:!f&&c>0&&s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:N,disabled:t,children:"Back"})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:a,disabled:t,children:"Cancel"}),f||k?s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:S,disabled:!j||t||!p,children:t?"Submitting...":"Submit"}):s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:b,disabled:!x||t,children:"Next"})]})]})]})})}function Sa(e,t={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=t,o=Date.now()-e,i=Math.floor(o/1e3);if(i<a)return n;const c=Math.floor(i/60);if(c<60)return`${c}m${r}`;const d=Math.floor(c/60);if(d<24)return`${d}h${r}`;const p=Math.floor(d/24);return p<7?`${p}d${r}`:new Date(e).toLocaleDateString()}const du=e=>Sa(e);function Lx(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden,muted:!!e.muted,completionMarker:typeof e.completionMarker=="string"?e.completionMarker:"",seenCompletionMarker:typeof e.seenCompletionMarker=="string"?e.seenCompletionMarker:""}}function Cr(e){const t=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating"||e.status==="no_progress"||e.status==="long_generating"||e.status==="streaming",a=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:r,isGenerating:n,isWaiting:a}}function uu(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...Lx(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 Ls(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,muted:!1,completionMarker:"",seenCompletionMarker:""}}function Na(e,t,r){const n=Ls(e,t),a=Cr(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,u=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:u,isReconnecting:o,isConnecting:i,isGenerating:c,isWaiting:d,inboxBucket:p?"needs_attention":u?"working":h?"task_complete":"idle"}}function Rx(e,t,r){return Na(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function pu({activeConv:e,onModalButton:t}){const{t:r}=Pt(),[n,a]=l.useState(null);if(l.useEffect(()=>{a(null)},[e.modalMessage,e.status,e.connectionState]),!Cr(e).isWaiting||!e.modalButtons)return null;const i=d=>{n||(a(d),t(d))},c=d=>d.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(Ys,{size:14})," ",r(n?"approval.processing":"approval.actionRequired")]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((d,p)=>{const u=c(d).toLowerCase(),m=/^(run|approve|accept|yes|allow|always)/.test(u),h=/^(reject|deny|delete|remove|abort)/.test(u),g=n===d,k=n!==null;return s.jsx("button",{onClick:()=>i(d),disabled:k,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${m?"font-extrabold":h?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${k&&!g?"opacity-40":"opacity-100"} ${k?"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)"}:h?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:g?"⏳ ...":c(d)},p)})})]})]})}const Li="adhdev_controls_bar_visible",Go="adhdev:controlsbarvisibilitychange";function Va(e){if(!e)return!1;try{return e.getItem(Li)==="1"}catch{return!1}}function Px(e,t){if(t)try{t.setItem(Li,e?"1":"0")}catch{}}function Dx(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Go,{detail:{visible:e}}))}function Ri(){const[e,t]=l.useState(()=>typeof window>"u"?!1:Va(window.localStorage)),r=l.useRef(e),n=l.useCallback((i,c=!0)=>{r.current=i,t(i),typeof window<"u"&&Px(i,window.localStorage),c&&Dx(i)},[]);l.useEffect(()=>{const i=d=>{const p=d.detail,u=typeof(p==null?void 0:p.visible)=="boolean"?p.visible:Va(window.localStorage);r.current=u,t(u)},c=d=>{if(d.key!==Li)return;const p=Va(window.localStorage);r.current=p,t(p)};return window.addEventListener(Go,i),window.addEventListener("storage",c),()=>{window.removeEventListener(Go,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}}const mu=["en","ko","ja","zh-CN","es"],Jr="en",qa=[{code:"en",label:"English"},{code:"ko",label:"한국어"},{code:"ja",label:"日本語"},{code:"zh-CN",label:"中文(简体)"},{code:"es",label:"Español"}];function dr(e){return typeof e=="string"&&mu.includes(e)}function $x(e){if(!e)return Jr;const t=e.trim().toLowerCase();if(!t)return Jr;if(t==="zh"||t.startsWith("zh-")||t.startsWith("zh_"))return"zh-CN";const r=t.split(/[-_]/)[0];return r==="en"?"en":r==="ko"?"ko":r==="ja"?"ja":r==="es"?"es":Jr}const Ex={label:"Language",select:"Select language"},Bx={cancel:"Cancel"},Fx={disconnected:"Disconnected",connected:"Connected",connectedToDashboard:"Connected to dashboard",connectingToMachine:"Connecting to machine...",networkOffline:"Network offline",reconnecting:"Reconnecting",sessionExpired:"Session expired.",logInAgain:"Log in again",connectionFailed:"Connection failed — refresh the page or try again shortly.",reconnectNow:"Reconnect now"},Ox={label:{success:"Done",warning:"Attention",info:"Update"},dismiss:"Dismiss"},Hx={actionNeeded:"Action needed",taskComplete:"Task complete",markRead:"Mark read",markUnread:"Mark unread",delete:"Delete"},Wx={taskCompleted:"{{label}} agent task completed",taskCompletedWithDuration:"{{label}} agent task completed ({{duration}}s)",approvalNeeded:"{{label}} approval needed",noProgress:"{{label}} agent shows no progress",noProgressWithDuration:"{{label}} agent shows no progress ({{minutes}}m)",noProgressTitle:"{{label}} — No Progress",noProgressBody:"Agent has shown no progress for over {{duration}}",viewRequest:"{{requester}} wants to view your session",viewRequestTitle:"View Request",viewRequestApproved:"View request approved",viewRequestDeclined:"{{target}} declined your view request",someoneRequester:"A team member",someoneTarget:"Team member"},Kx={header:{title:"Dashboard",guide:"Dashboard guide",guideOpen:"Open dashboard guide",guideShort:"Guide",openGitStatus:"Open git status",openMeshGraph:"Open live repo mesh graph",meshGraph:"Mesh graph",stopAcpSession:"Stop ACP session",stopCliProcess:"Stop CLI process",chatHistory:"Chat History",remoteControl:"Remote Control",generating:"generating",activityInbox:"Activity inbox"},hidden:{title:"Hidden tabs",dragHint:"Drag a tab here to hide it.",resetPanels:"Reset panels",restoreAll:"Restore all",hideCurrentTab:"Hide current tab",empty:"No hidden tabs."},inbox:{unread:"Unread",read:"Read",empty:"No pending activity."}},Ux={title:"Stop {{agent}}?",gracefulDescription:"Stop asks the provider to exit cleanly when supported. Force Stop ends the runtime immediately.",forceOnlyDescription:"This provider does not support graceful stop. Force Stop will end the runtime immediately.",stop:"Stop",forceStop:"Force Stop"},Gx={processing:"PROCESSING...",actionRequired:"ACTION REQUIRED"},zx={title:"Start session",close:"Close new session dialog",category:"Category",detectedLocally:"Detected locally",availableToOpen:"Available to open",machine:"Machine",selectMachine:"Select machine {{name}}",workspace:"Workspace",browse:"Browse…",launchTargetType:"Launch target type",modeWorkspace:"Workspace",modeWorkspaceDesc:"Normal session",modeMesh:"Mesh",modeMeshDesc:"Coordinator session",homeDirectory:"Home directory",customFolder:"Custom folder…",launchWithoutWorkspace:"Launch without a workspace.",selectWorkspaceFolder:"Select a workspace folder.",selectFolder:"Select folder",saving:"Saving…",saveWorkspace:"Save workspace",loadingMeshes:"Loading meshes…",noMeshes:"No repo meshes are configured on this machine. Create or sync a mesh first, then reopen this picker.",mesh:"Mesh",repoMesh:"Repo mesh",nodeCount_one:"{{count}} node",nodeCount_other:"{{count}} nodes",coordinatorWorkspace:"Coordinator workspace: {{path}}",chooseIde:"Choose IDE",chooseCliProvider:"Choose CLI provider",chooseAcpProvider:"Choose ACP provider",noProviders:"Nothing usable for this category on the selected machine. Set a custom executable path in Providers if the binary lives outside the default location.",startupArguments:"Startup arguments",optionalFlags:"Optional flags...",modelAndThinking:"Model & thinking (optional)",model:"Model",providerDefault:"(provider default)",custom:"Custom…",typeModelName:"Type a model name",backToModelList:"← Back to model list",thinkingLevel:"Thinking level",selectWorkspaceTitle:"Select workspace",selectWorkspaceDescription:"Pick the folder that should be used for this new session.",start:"Start",starting:"Starting…",startMeshCoordinator:"Start mesh coordinator",startingCoordinator:"Starting coordinator…",startIde:"Start IDE",startingIde:"Starting IDE…",startAcpSession:"Start ACP session",startingAcpSession:"Starting ACP session…",startFresh:"Start fresh",startingFresh:"Starting fresh…",resumeSavedHistory:"Resume saved history",resumingSavedHistory:"Resuming saved history…",errorLoadMeshes:"Could not load meshes",errorLoadFolder:"Could not load folder",errorLoadSavedSessions:"Could not load saved sessions",errorSaveWorkspace:"Could not save workspace",workspaceSaved:"Workspace saved. It will appear in the list once the machine state refreshes.",errorManualMcpSetup:"Manual MCP setup required before this provider can act as mesh coordinator.",errorStartMeshCoordinator:"Could not start mesh coordinator",errorStartSession:"Could not start session",errorResumeSession:"Could not resume session"},Vx={machines:"Machines",chats:"Chats",networkOffline:"Network offline",sessionExpired:"Session expired",reconnecting:"Reconnecting",waitingForNetwork:"Waiting for network…",pleaseLogInAgain:"Please log in again.",restoringConnection:"Restoring the server connection…",waitingForDaemon:"Waiting for your daemon",connectYourMachines:"Connect your machines",waitingForDaemonSubtitle:"Start the ADHDev daemon to connect this dashboard. Once it is online, you can launch sessions with any installed provider.",connectYourMachinesSubtitle:"Install ADHDev on a machine, sign in, and it will show up here.",newCount:"{{count}} new",chatCount_one:"{{count}} chat",chatCount_other:"{{count}} chats",idle:"Idle",unreadSuffix:" · {{count}} unread",noActiveChats:"No active chats",needsAttention:"Needs attention",taskComplete:"Task complete",workingNow:"Working now",earlier:"Earlier",connecting:"Connecting…",connectingSubtitle:"Waiting for server connection before loading conversations.",noMachinesConnected:"No machines connected",noMachinesSubtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents.",noConversations:"No conversations yet",allCaughtUp:"All caught up.",hiddenTabs:"Hidden tabs",collapsedCount_one:"{{count}} collapsed conversation",collapsedCount_other:"{{count}} collapsed conversations",restoreAll:"Restore all",hide:"Hide",hideTitle:"Hide {{title}}?",hideDescription:"This only collapses the chat locally. You can restore it from Hidden tabs.",reconnectingItem:"Reconnecting…",connectingItem:"Connecting…",actionNeeded:"Action needed",done:"Done",openMeshGraphFor:"Open mesh graph for {{title}}",openLiveMeshGraph:"Open live repo mesh graph",unmute:"Unmute {{title}}",mute:"Mute {{title}}",mutedTitle:"Muted — notifications silenced. Tap to unmute.",muteNotifications:"Mute notifications",hideConversationAria:"Hide {{title}}",hideConversationTitle:"Hide conversation",stopSessionAria:"Stop {{title}} session",stopSessionTitle:"Stop session (terminates the agent)"},qx={help:{toggleAria:"Mesh help",toggleTitle:"Mesh concept help",regionAria:"Mesh concept help",kicker:"Help",title:"Mesh concepts at a glance",close:"Close help",sections:{node:{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."]},p2p:{term:"P2P connection",summary:"How the selected coordinator reaches each remote node over WebRTC.",details:["direct — a direct host/STUN path; lowest latency.","relay — TURN-relayed; works through restrictive networks but is slower.","disconnected / failed — no live P2P link from the coordinator right now.","P2P connectivity is shown as transport and RTT chips on each node card (and in the node detail panel), not as a graph edge."]},session:{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)."]},task:{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."]},mission:{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."]},refinery:{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."]},completion:{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."]},magi:{term:"MAGI",summary:"Cross-verification: several independent AI agents answer the same question in parallel.",details:["Confidence comes from independence — different AIs on different machines fail in different ways.","When the agents disagree, the disagreement itself flags what to double-check.","Run via mesh_magi_review; the synthesis weighs agreement against source coupling."]},magiPanel:{term:"MAGI panel",summary:"A saved, reusable team of (machine × AI) members you invoke by name across investigations.",details:["Each member is one provider (AI) optionally pinned to a node (machine), with a replica count.","independent — spans ≥2 providers AND ≥2 machines, so agreement adds real confidence.","coupled — collapses to one AI or one machine; repeated members repeat the same mistakes.","Managed machine-locally from the Panels tab; defined in ~/.adhdev/meshes.json."]},convergence:{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."]}}},approvals:{title:"PENDING APPROVALS",empty:"No sessions are awaiting an approval decision.",sessionFallback:"session {{id}}",approve:"Approve",reject:"Reject"},chat:{loading:"Loading…",empty:"No messages."},coordinatorBadge:{daemon:"daemon: {{id}}",run:"run: {{id}}",session:"session: {{id}}"},difficulty:{intro:"Map each task difficulty to a brain. The coordinator classifies a task's difficulty; easy work then runs on a cheaper model at low effort, hard work on a stronger model at high effort. Leave a field blank to keep the routed default.",connectPrompt:"Connect to a coordinator daemon to edit brain presets.",errorLoad:"Failed to load brain presets",errorSave:"Failed to save brain presets",provider:"Provider",model:"Model",thinking:"Thinking",routedDefault:"(routed default)",defaultOption:"(default)",modelPlaceholder:"e.g. haiku, sonnet, opus",savePresets:"Save presets",saving:"Saving…",reset:"Reset",loading:"Loading…",easy:"Easy",easyHint:"trivial fixes, renames, docs — save tokens",medium:"Medium",mediumHint:"ordinary feature / bugfix work",difficult:"Difficult",difficultHint:"architecture, tricky debugging, hard reasoning",freeform:"Freeform",freeformHint:"no fixed shape"},magiKind:{intro:"Pick which agents review each task type. Add one row per agent.",refresh:"Refresh",loading:"Loading…",connectPrompt:"Connect to a coordinator daemon to manage kind → panel bindings.",errorLoad:"Failed to load kind panels",errorSave:"Failed to save kind binding",errorRemove:"Failed to remove kind binding",errorSlotProvider:"Slot {{slot}}: provider is required",errorSlotReplica:"Slot {{slot}}: replica count must be ≥ 1",errorNoSlot:"A kind binding needs at least one slot",removeConfirm:'Remove the MAGI panel binding for "{{kind}}"?',kindRca:"Root-cause analysis",kindDesign:"Design / approach review",kindClaimAudit:"Verify specific claims",kindFreeform:"Freeform review",agentCount_one:"{{count}} agent",agentCount_other:"{{count}} agents",off:"off",noAgents:"No agents yet — add one to enable this review type.",machine:"Machine",machineTitle:'Which machine runs this agent. Leave on "any" to let the coordinator route by tags.',anyMachine:"Any machine",offlineSuffix:"{{label}} (offline)",provider:"Provider",providerTitle:"The AI agent this slot runs.",selectProvider:"Select provider…",model:"Model",modelTitle:"Optional model override (best-effort). Blank uses the provider default.",modelDefault:"default",modelCustom:"Custom…",backToModelList:"← Back to model list",copies:"Copies",copiesTitle:"How many parallel copies of this agent to run. Blank = 1.",removeAgent:"Remove agent",addAgent:"+ Add agent",save:"Save",saving:"Saving…",removeBinding:"Remove binding",removeBindingTitle:"Clear this kind binding",removeBindingDisabledTitle:"Nothing to remove — this kind is unconfigured"},synthesis:{empty:"No MAGI cross-verification synthesis has been persisted for this mesh yet. Run a MAGI review (mesh_magi_review) and collect it (mesh_magi_collect); the synthesized summary then appears here, persisted to the mesh ledger.",synthesized:"synthesized",running:"running",answered:"{{answered}}/{{total}} answered",needsVerificationCount:"{{count}} needs verification",agreedCount:"{{count}} agreed",staleCount:"{{count}} stale",gitSkewLabel:"Git skew: ",gitSkewNote_one:"{{count}} branch ({{branches}}) — evidence compares different code.",gitSkewNote_other:"{{count}} branches ({{branches}}) — evidence compares different code.",needsVerification:"Needs verification",openQuestions:"Open questions",rawReplicaAnswers:"Raw replica answers",rawTitleLive:"Best-effort: raw replica text is not persisted — recoverable only from a live coordinator with the replica sessions still reachable.",rawTitleOffline:"A live coordinator daemon is required to fetch raw replica answers.",loading:"Loading…",reloadRaw:"Reload raw answers",loadRaw:"Load raw answers",rawNotice:"Raw per-replica text is not persisted (only this synthesis summary is). It is fetched live from the coordinator and is unavailable once the replica sessions age out or no live session exists.",errorLoadRaw:"Failed to load raw answers",rawEmpty:"No raw answers were returned — the replica transcripts are not retained (raw not persisted), aged out, or no live session is reachable for this group.",truncated:"truncated"}},Yx={page:{title:"Repo Mesh",subtitle:"Multi-workspace orchestration",waitingForDaemon:"Waiting for daemon connection...",observabilitySecondary:"Mesh observability"},list:{title:"Repo Meshes",count_one:"{{count}} mesh",count_other:"{{count}} meshes",createMesh:"+ Create Mesh",createTitle:"Create Repo Mesh",createOnMachine:"Create on machine",createOnMachineHint:"Mesh setup is stored by the selected daemon.",noConnectedDaemon:"No connected daemon",workspace:"Workspace",workspaceHint:"Choose from workspaces registered by the selected daemon.",selectMachineFirst:"Select a machine first",noRegisteredWorkspaces:"No registered workspaces",name:"Name",namePlaceholder:"my-project-mesh",remoteUrl:"Repo remote URL (optional)",remoteUrlHint:"Provide a remote URL OR a stable identity.",remoteUrlPlaceholder:"https://github.com/user/repo",repoIdentity:"Repo identity (optional)",repoIdentityPlaceholder:"github.com/user/repo",create:"Create",cancel:"Cancel",loading:"Loading meshes...",emptyTitle:"No Repo Meshes",emptyWithDaemons:"Create a mesh to get started.",emptyNoDaemons:"Connect an ADHDev daemon first.",createFirst:"Create First Mesh",noRepoIdentity:"No repo identity",repoMeshFallback:"Repo Mesh",nodesSuffix:"node(s)"},detail:{back:"← Back",probing:"Probing…",refresh:"Refresh",delete:"Delete",observabilityTitle:"Observability",observabilityDescription:"Open the live mesh graph, overview, and runtime status in the observability dialog.",observabilityOpenTitle:"Open the mesh graph / overview / status dialog",observabilityDisabledTitle:"A coordinator daemon must be selected first",observabilityOpen:"Open mesh graph & status",observabilityHint:"Topology graph, overview cards (missions, ledger, queue, nodes, sessions), and per-node runtime drift.",schedulingTitle:"Scheduling",schedulingDescription:"How untargeted queue work is distributed across eligible nodes.",distribution:"Distribution",recommended:"Recommended",saving:"Saving…",visibilityTitle:"Dashboard visibility",visibilityDescription:"Whether the worker sessions this coordinator spawns show up in your dashboard inbox and raise notifications.",visibilityLabel:"Coordinator-spawned worker sessions",visibilityHint:"Hidden = keep the inbox quiet and mute their notifications; you interact through the coordinator session. Visible = show every spawned worker as its own conversation.",visibilityHidden:"Hidden (no notifications, keep inbox quiet)",visibilityVisible:"Visible (show every worker in the dashboard)",magiTitle:"MAGI review panels",magiDescription:"MAGI (Multi-Agent Ground-truth Insight) runs a panel of AI agents that cross-check each other's work to surface the ground truth. Choose which agents handle each review type.",advanced:"advanced",coordinatorPromptTitle:"Coordinator prompt",coordinatorPromptDescription:"Customize the system prompt for coordinator sessions. Per-mesh overrides apply to this mesh only; user-level overrides apply to every mesh this daemon coordinates.",thisMesh:"This mesh",thisMeshHint:"Applies only to coordinator sessions for {{name}}. Leave empty to fall through to the user-level / daemon default.",overrideLabel:"Override (replaces default)",overrideHint:"When set, replaces the daemon's default base prompt. Leave empty to keep the default.",overridePlaceholder:"(empty — daemon default applies)",appendLabel:"Append (added after the base)",appendHint:"Always added after whichever base prompt wins.",appendPlaceholder:"(empty — nothing appended)",availablePlaceholders:"Available placeholders",saveCoordinatorPrompt:"Save coordinator prompt",clear:"Clear",clearTitle:"Clear both fields. Click Save to commit.",userLevel:"User-level (this daemon)",userLevelDescription:"Per-machine prompt files on the coordinator daemon. They apply to every mesh this daemon coordinates and are not synced across daemons. Per-mesh overrides above win over these.",safetyTitle:"Safety & Git",safetyDescription:"Checkpointing, approval gates, and git safety behavior for coordinator-driven tasks.",checkpointBefore:"Auto-commit a checkpoint before each task",checkpointAfter:"Auto-commit a checkpoint after each task",pushApproval:"Push approval",requireApprovalBeforePush:"Require approval before push",doNotRequireApproval:"Do not require approval",destructiveGitApproval:"Destructive git approval",requireApproval:"Require approval",uncommittedChanges:"When the workspace has uncommitted changes",warnAndContinue:"Warn and continue",blockTask:"Block task",checkpointThenContinue:"Checkpoint then continue",autoPublishSubmodule:"Auto-publish submodule commits (advanced)",requireExplicitApproval:"Require explicit approval",allowRefineryPublish:"Allow Refinery non-force publish",autoFastForward:"Auto fast-forward idle nodes",ffEnabled:"Enabled (catch up online, clean, behind nodes)",ffDisabled:"Disabled",includeRemoteNodes:"Include remote nodes",includeRemoteNodesHint:"Off = only the coordinator's local workspace is auto fast-forwarded.",remoteNo:"No (local workspace only)",remoteYes:"Yes (delegate to remote owning daemons)",detectionMode:"Detection mode",detectionModeHint:"Idle = on a node's idle edge. Continuous = also scan periodically (base nodes only).",idleEdgeOnly:"Idle edge only",continuousScan:"Continuous (periodic scan)",sessionCleanupLabel:"When removing a node, its sessions…",sessionCleanupHint:"Separate transcript cleanup from runtime/process cleanup.",mcpMode:"MCP Mode:",mcpDescription:"· The mesh MCP server can be used directly from your CLI agent."},nodeList:{title:"Nodes & Providers ({{count}})",descriptionCloud:"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.",descriptionStandalone:"Workspaces participating in this mesh and their preferred AI tools.",daemonCandidates:"Machine daemon candidates",daemonCandidatesHint:"Choose connected daemons to attach to the selected Mesh Host setup.",available:"{{count}} available",noDaemonsAvailable:"No connected machine daemons are currently available.",allDaemonsAttached:"All connected machine daemons are already attached.",selectedHost:"selected host",attachMachine:"Attach machine",addNode:"Add node",attachMachineTitle:"Attach Machine Daemon",addNodeTitle:"Add Node",machine:"Machine",selectMachine:"Select a machine...",workspacePath:"Workspace Path",enterCustomPath:"Or enter a custom path →",pathPlaceholder:"/Users/dev/projects/myapp",preferredTools:"Preferred AI tools (in order)",preferredToolsHint:"Order used when launching without an explicit provider.",add:"Add",cancel:"Cancel",setupInventoryWarning:"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.",emptyTitle:"No nodes",emptyDescription:"Add a workspace to this mesh.",setupInventory:"setup inventory",liveDetailGraphOwned:"Live branch/git/session detail is graph-owned; use the node popup in the live graph above.",slotsLabel:"Preferred AI tools (capability slots)",slotsHint:"Each slot = provider + model + thinking + the task difficulty/capability it handles + a per-slot parallel cap. Tasks are matched to the best-fit slot (order = preference). With no slots, this node uses its legacy provider order.",nodeInstruction:"Node instruction (optional)",nodeInstructionHint:"Surfaced in the coordinator system prompt as 📌 Node instruction.",nodeInstructionPlaceholder:"e.g. 'Run only smoke tests here', 'Use opus on this node'",saveInstruction:"Save instruction",saving:"Saving…",removeNode:"Remove node",details:"Details",nodeId:"Node ID:",launchReady:"Launch ready:",launchReadyYes:"yes",launchReadyNo:"no preferred tool configured",repoRoot:"Repo root:",activeSessionsLabel:"Active sessions:",added:"Added:",activeQueueAssignments:"Active queue assignments",noActiveAssignment:"No active assigned queue task for this node.",activeSessions:"Active sessions",launchBlocked:"No provider detected on this node — task launch is blocked until a provider is selected or installed. (Empty capability slots alone do not block launch; this means no provider was found.)"},host:{coordinatorProvider:"Coordinator CLI provider",coordinatorProviderHint:"Tool launched for the host coordinator session.",useNodePriority:"Use node provider priority",title:"Mesh Host daemon",descriptionSet:"The daemon that owns this mesh's coordinator and live truth (status, queue, graph, node detail). Fixed when the mesh is created — it cannot be reassigned here.",descriptionUnset:"This mesh has no host yet. Launching the coordinator on a connected daemon fixes that daemon as the mesh host (a 1:1 pin); it owns live truth thereafter.",hostLabel:"Host:",hostNode:"Host node:",unknown:"Unknown",hostOffline:"Host offline.",hostOfflineText:"The pinned host daemon is not connected. Live status/queue/graph will not load until it reconnects. You can temporarily route commands through another connected daemon below — this is a routing fallback, not a host reassignment.",reconnectToCommand:"Reconnect to command",reconnectToCommandHint:"Route commands through this connected daemon until the host is back. Does not change the mesh host.",waitForHost:"Wait for host to reconnect",noDaemonsToRoute:"No connected daemons available to route commands through. Bring the host (or another daemon) online.",launching:"Launching...",launchHost:"Launch Host Coordinator",setHostBanner:"Set the mesh host.",setHostBannerText:"The host is the daemon that owns this mesh's coordinator and live truth. Launch the host coordinator below to set it — the host is fixed once established.",hostDaemon:"Host daemon",hostDaemonHint:"Pick the daemon that will host this mesh. Launching the coordinator on it fixes it as the host.",resolvingHost:"Resolving host… (or pick a daemon to host)",launchHostSetsHost:"Launch Host Coordinator (sets host)",noDaemonsToHost:"No connected daemons. Bring a daemon online to host this mesh."},slotEditor:{empty:"No capability slots set — that's fine. This node still runs tasks using its provider priority order (below). Slots are optional fine-tuning: add one to route specific task difficulties or capabilities to a specific tool.",moveUp:"Move up",moveDown:"Move down",removeSlot:"Remove slot",provider:"Provider",select:"(select)",providerPlaceholder:"claude-cli",model:"Model",providerDefault:"(provider default)",custom:"Custom…",modelPlaceholder:"model",backToModelList:"← Back to model list",thinking:"Thinking",thinkingDefault:"(default)",difficulty:"Difficulty (blank = all)",capabilityTags:"Capability tags (comma-separated)",capabilityTagsPlaceholder:"worktree, os=darwin",maxParallel:"Max parallel (per slot)",maxParallelPlaceholder:"unlimited",addSlot:"Add slot",saving:"Saving…",saveSlots:"Save slots"},tagEditor:{noSpaces:"Tags cannot contain spaces.",reservedPrefix:"That prefix is auto-derived — pick a different tag.",alreadyAdded:"Already added.",routingTags:"Routing tags",autoDerivedTitle:"Auto-derived — can't be edited",customTagTitle:"Custom tag",remove:"Remove {{tag}}",addPlaceholder:"add a custom tag (e.g. test-runner)",add:"Add",saving:"Saving…",saveTags:"Save tags",empty:"No routing tags — tasks can run here without matching any specific capability. Tags are optional."},missions:{errorFetch:"Failed to fetch full mission goals",title:"Missions",description:"Active and historical missions reported by the coordinator. Expand a goal to fetch its full text on demand.",empty:"No {{status}} missions.",taskCount_one:"{{count}} task",taskCount_other:"{{count}} tasks",goalUnavailable:" … (full goal unavailable)",showLess:"Show less",loading:"Loading…",showFullGoal:"Show full goal",showMore:"Show {{count}} more"},queue:{title:"Queue",description:"Inspect active queue work separately from historical completed, failed, and cancelled task records.",statActive:"Active",statPending:"Pending",statAssigned:"Assigned",statStale:"Stale",statHistorical:"Historical",statCompleted:"Completed",statFailed:"Failed",loading:"Loading...",refresh:"Refresh Queue",refreshHint:"Refresh the queue to view host-owned task counts and recent assignments.",empty:"Queue is empty.",staleBadge:"stale",staleTitle:"Stale assignment",waitingOnTitle:"Waiting on: {{tasks}}",waitsOn_one:"waits on {{count}} task",waitsOn_other:"waits on {{count}} tasks",blocked:"blocked",durationTitle:"Dispatched → terminal wall clock",retry_one:" · {{count}} retry",retry_other:" · {{count}} retries",node:"node {{id}}",session:"session {{id}}"},promptPreview:{connectPrompt:"Connect a daemon to preview the default.",errorRender:"Failed to render the default prompt",hide:"Hide the default prompt",view:"View the default prompt",rendering:"Rendering…",retry:"Retry",info:"This is what a coordinator session gets when Override is empty."},hermesMcp:{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.",fallbackProvider:"Hermes CLI"}},Jx={language:Ex,common:Bx,connection:Fx,toast:Ox,notification:Hx,event:Wx,dashboard:Kx,cliStop:Ux,approval:Gx,newSession:zx,mobileInbox:Vx,meshGraph:qx,repoMesh:Yx},Xx={label:"언어",select:"언어 선택"},Qx={cancel:"취소"},Zx={disconnected:"연결 끊김",connected:"연결됨",connectedToDashboard:"대시보드에 연결됨",connectingToMachine:"머신에 연결 중...",networkOffline:"네트워크 오프라인",reconnecting:"재연결 중",sessionExpired:"세션이 만료되었습니다.",logInAgain:"다시 로그인",connectionFailed:"연결에 실패했습니다 — 페이지를 새로고침하거나 잠시 후 다시 시도하세요.",reconnectNow:"지금 재연결"},eb={label:{success:"완료",warning:"주의",info:"업데이트"},dismiss:"닫기"},tb={actionNeeded:"조치 필요",taskComplete:"작업 완료",markRead:"읽음 표시",markUnread:"읽지 않음 표시",delete:"삭제"},sb={taskCompleted:"{{label}} 에이전트 작업 완료",taskCompletedWithDuration:"{{label}} 에이전트 작업 완료 ({{duration}}초)",approvalNeeded:"{{label}} 승인 필요",noProgress:"{{label}} 에이전트 진행 없음",noProgressWithDuration:"{{label}} 에이전트 진행 없음 ({{minutes}}분)",noProgressTitle:"{{label}} — 진행 없음",noProgressBody:"에이전트가 {{duration}} 넘게 진행이 없습니다",viewRequest:"{{requester}}님이 세션 보기를 요청합니다",viewRequestTitle:"보기 요청",viewRequestApproved:"보기 요청이 승인되었습니다",viewRequestDeclined:"{{target}}님이 보기 요청을 거절했습니다",someoneRequester:"팀 멤버",someoneTarget:"팀 멤버"},rb={header:{title:"대시보드",guide:"대시보드 가이드",guideOpen:"대시보드 가이드 열기",guideShort:"가이드",openGitStatus:"Git 상태 열기",openMeshGraph:"실시간 리포 메시 그래프 열기",meshGraph:"메시 그래프",stopAcpSession:"ACP 세션 중지",stopCliProcess:"CLI 프로세스 중지",chatHistory:"채팅 기록",remoteControl:"원격 제어",generating:"생성 중",activityInbox:"활동 수신함"},hidden:{title:"숨긴 탭",dragHint:"탭을 여기로 끌어다 놓으면 숨겨집니다.",resetPanels:"패널 초기화",restoreAll:"모두 복원",hideCurrentTab:"현재 탭 숨기기",empty:"숨긴 탭이 없습니다."},inbox:{unread:"읽지 않음",read:"읽음",empty:"대기 중인 활동이 없습니다."}},nb={title:"{{agent}}을(를) 중지할까요?",gracefulDescription:"중지는 지원되는 경우 프로바이더에게 정상 종료를 요청합니다. 강제 중지는 런타임을 즉시 종료합니다.",forceOnlyDescription:"이 프로바이더는 정상 중지를 지원하지 않습니다. 강제 중지는 런타임을 즉시 종료합니다.",stop:"중지",forceStop:"강제 중지"},ab={processing:"처리 중...",actionRequired:"조치 필요"},ob={title:"세션 시작",close:"새 세션 대화상자 닫기",category:"카테고리",detectedLocally:"로컬에서 감지됨",availableToOpen:"열기 가능",machine:"머신",selectMachine:"머신 {{name}} 선택",workspace:"워크스페이스",browse:"찾아보기…",launchTargetType:"실행 대상 유형",modeWorkspace:"워크스페이스",modeWorkspaceDesc:"일반 세션",modeMesh:"메시",modeMeshDesc:"코디네이터 세션",homeDirectory:"홈 디렉터리",customFolder:"사용자 지정 폴더…",launchWithoutWorkspace:"워크스페이스 없이 실행합니다.",selectWorkspaceFolder:"워크스페이스 폴더를 선택하세요.",selectFolder:"폴더 선택",saving:"저장 중…",saveWorkspace:"워크스페이스 저장",loadingMeshes:"메시 불러오는 중…",noMeshes:"이 머신에 구성된 리포 메시가 없습니다. 먼저 메시를 생성하거나 동기화한 후 이 선택기를 다시 여세요.",mesh:"메시",repoMesh:"리포 메시",nodeCount_one:"노드 {{count}}개",nodeCount_other:"노드 {{count}}개",coordinatorWorkspace:"코디네이터 워크스페이스: {{path}}",chooseIde:"IDE 선택",chooseCliProvider:"CLI 프로바이더 선택",chooseAcpProvider:"ACP 프로바이더 선택",noProviders:"선택한 머신에서 이 카테고리로 사용할 수 있는 것이 없습니다. 바이너리가 기본 위치 밖에 있다면 프로바이더에서 사용자 지정 실행 경로를 설정하세요.",startupArguments:"시작 인자",optionalFlags:"선택적 플래그...",modelAndThinking:"모델 & 사고 수준 (선택)",model:"모델",providerDefault:"(프로바이더 기본값)",custom:"사용자 지정…",typeModelName:"모델 이름 입력",backToModelList:"← 모델 목록으로",thinkingLevel:"사고 수준",selectWorkspaceTitle:"워크스페이스 선택",selectWorkspaceDescription:"이 새 세션에 사용할 폴더를 선택하세요.",start:"시작",starting:"시작 중…",startMeshCoordinator:"메시 코디네이터 시작",startingCoordinator:"코디네이터 시작 중…",startIde:"IDE 시작",startingIde:"IDE 시작 중…",startAcpSession:"ACP 세션 시작",startingAcpSession:"ACP 세션 시작 중…",startFresh:"새로 시작",startingFresh:"새로 시작 중…",resumeSavedHistory:"저장된 기록 재개",resumingSavedHistory:"저장된 기록 재개 중…",errorLoadMeshes:"메시를 불러올 수 없습니다",errorLoadFolder:"폴더를 불러올 수 없습니다",errorLoadSavedSessions:"저장된 세션을 불러올 수 없습니다",errorSaveWorkspace:"워크스페이스를 저장할 수 없습니다",workspaceSaved:"워크스페이스가 저장되었습니다. 머신 상태가 새로고침되면 목록에 표시됩니다.",errorManualMcpSetup:"이 프로바이더가 메시 코디네이터로 작동하려면 수동 MCP 설정이 필요합니다.",errorStartMeshCoordinator:"메시 코디네이터를 시작할 수 없습니다",errorStartSession:"세션을 시작할 수 없습니다",errorResumeSession:"세션을 재개할 수 없습니다"},ib={machines:"머신",chats:"채팅",networkOffline:"네트워크 오프라인",sessionExpired:"세션 만료됨",reconnecting:"재연결 중",waitingForNetwork:"네트워크 대기 중…",pleaseLogInAgain:"다시 로그인해 주세요.",restoringConnection:"서버 연결을 복원하는 중…",waitingForDaemon:"데몬을 기다리는 중",connectYourMachines:"머신을 연결하세요",waitingForDaemonSubtitle:"ADHDev 데몬을 시작하여 이 대시보드에 연결하세요. 온라인이 되면 설치된 프로바이더로 세션을 실행할 수 있습니다.",connectYourMachinesSubtitle:"머신에 ADHDev를 설치하고 로그인하면 여기에 표시됩니다.",newCount:"새 항목 {{count}}개",chatCount_one:"채팅 {{count}}개",chatCount_other:"채팅 {{count}}개",idle:"유휴",unreadSuffix:" · 읽지 않음 {{count}}개",noActiveChats:"활성 채팅 없음",needsAttention:"조치 필요",taskComplete:"작업 완료",workingNow:"작업 중",earlier:"이전",connecting:"연결 중…",connectingSubtitle:"대화를 불러오기 전에 서버 연결을 기다리는 중입니다.",noMachinesConnected:"연결된 머신 없음",noMachinesSubtitle:"머신 탭으로 전환하여 첫 머신을 연결하고 AI 에이전트와 채팅을 시작하세요.",noConversations:"아직 대화가 없습니다",allCaughtUp:"모두 확인했습니다.",hiddenTabs:"숨긴 탭",collapsedCount_one:"접힌 대화 {{count}}개",collapsedCount_other:"접힌 대화 {{count}}개",restoreAll:"모두 복원",hide:"숨기기",hideTitle:"{{title}}을(를) 숨길까요?",hideDescription:"채팅이 로컬에서만 접힙니다. 숨긴 탭에서 다시 복원할 수 있습니다.",reconnectingItem:"재연결 중…",connectingItem:"연결 중…",actionNeeded:"조치 필요",done:"완료",openMeshGraphFor:"{{title}} 메시 그래프 열기",openLiveMeshGraph:"실시간 리포 메시 그래프 열기",unmute:"{{title}} 음소거 해제",mute:"{{title}} 음소거",mutedTitle:"음소거됨 — 알림이 차단되었습니다. 탭하여 해제하세요.",muteNotifications:"알림 음소거",hideConversationAria:"{{title}} 숨기기",hideConversationTitle:"대화 숨기기",stopSessionAria:"{{title}} 세션 중지",stopSessionTitle:"세션 중지 (에이전트를 종료합니다)"},lb={help:{toggleAria:"메시 도움말",toggleTitle:"메시 개념 도움말",regionAria:"메시 개념 도움말",kicker:"도움말",title:"메시 개념 한눈에 보기",close:"도움말 닫기",sections:{node:{term:"노드",summary:"메시에 참여하는 워크스페이스 — 리포 체크아웃 또는 격리된 git 워크트리.",details:["베이스 노드 vs 워크트리 클론 노드 — 클론은 충돌 없이 병렬 작업을 격리합니다.","상태(온라인/오프라인)를 git 상태(브랜치 · ahead/behind · dirty)와 함께 표시합니다.","여러 노드가 같은 데몬을 공유할 수 있습니다."]},p2p:{term:"P2P 연결",summary:"선택한 코디네이터가 WebRTC로 각 원격 노드에 도달하는 방식.",details:["direct — 직접 host/STUN 경로; 가장 낮은 지연.","relay — TURN 릴레이; 제한적 네트워크에서도 작동하지만 느립니다.","disconnected / failed — 현재 코디네이터로부터 활성 P2P 링크가 없음.","P2P 연결성은 그래프 엣지가 아니라 각 노드 카드(및 노드 상세 패널)의 transport·RTT 칩으로 표시됩니다."]},session:{term:"세션",summary:"노드에서 실행 중인 에이전트 CLI 세션.",details:["status = idle / generating / waiting_approval.","작업을 디스패치·수집하는 코디네이터 세션과 실제 작업을 수행하는 위임 워커 세션을 구분합니다."]},task:{term:"태스크",summary:"큐 기반 풀 모델로 처리되는 단일 작업 단위.",details:["상태: pending → assigned → completed / failed / cancelled.","유휴 노드는 큐에서 자동으로 클레임하며, 직접 디스패치는 특정 세션을 대상으로 합니다."]},mission:{term:"미션",summary:"하나의 목표를 향한 다중 태스크 배치이자 그 노력의 영속 기록.",details:["상태: active / paused / completed / abandoned.","진행률은 소속 태스크들의 상태에서 파생됩니다."]},refinery:{term:"리파이너리 (refine)",summary:"워크트리 브랜치를 베이스로 안전하게 수렴·머지하는 과정.",details:["구성 기반(.adhdev/refine.*) — 패치 동등성 프리플라이트와 no-op 가드로 보호됩니다.","원칙적으로 ff-only; 강제 푸시 없음.","서브모듈 커밋이 origin에서 도달 불가하면 게시되어야 하며 → blocked_review로 분류됩니다."]},completion:{term:"완료 모델",summary:"위임된 작업의 완료는 큐(pending-events)에 영속됩니다.",details:["코디네이터는 주기적 폴링 또는 이벤트로 완료를 인지합니다.","큐에 영속되므로 완료 신호는 결코 유실되지 않습니다."]},magi:{term:"MAGI",summary:"교차 검증: 여러 독립 AI 에이전트가 같은 질문에 병렬로 답합니다.",details:["신뢰는 독립성에서 나옵니다 — 서로 다른 머신의 서로 다른 AI는 서로 다르게 실패합니다.","에이전트들이 의견이 갈리면 그 불일치 자체가 재확인할 지점을 표시합니다.","mesh_magi_review로 실행하며, 합성은 합의를 소스 결합도와 견주어 평가합니다."]},magiPanel:{term:"MAGI 패널",summary:"이름으로 호출하는, 저장·재사용 가능한 (머신 × AI) 멤버 팀.",details:["각 멤버는 하나의 프로바이더(AI)이며, 선택적으로 노드(머신)에 고정되고 복제 수를 가집니다.","independent — 프로바이더 ≥2 AND 머신 ≥2에 걸쳐 합의가 실질적 신뢰를 더합니다.","coupled — 하나의 AI 또는 머신으로 수렴; 반복 멤버는 같은 실수를 반복합니다.","패널 탭에서 머신 로컬로 관리; ~/.adhdev/meshes.json에 정의됩니다."]},convergence:{term:"브랜치 수렴 상태",summary:"워크트리 작업 후 각 브랜치는 정확히 하나의 최종 상태로 분류됩니다.",details:["merged_to_main — 베이스에 머지됨.","pushed_feature_branch_needs_merge — 푸시됨, 머지 대기.","blocked_review — 리뷰/도달성 문제로 보류됨.","cleanup_candidate — 정리 준비 완료.","not_mergeable — 머지 불가."]}}},approvals:{title:"대기 중인 승인",empty:"승인 결정을 기다리는 세션이 없습니다.",sessionFallback:"세션 {{id}}",approve:"승인",reject:"거절"},chat:{loading:"불러오는 중…",empty:"메시지가 없습니다."},coordinatorBadge:{daemon:"데몬: {{id}}",run:"실행: {{id}}",session:"세션: {{id}}"},difficulty:{intro:"각 태스크 난이도를 브레인에 매핑하세요. 코디네이터가 태스크의 난이도를 분류하며, 쉬운 작업은 저노력의 저렴한 모델에서, 어려운 작업은 고노력의 강력한 모델에서 실행됩니다. 필드를 비워 두면 라우팅된 기본값을 유지합니다.",connectPrompt:"브레인 프리셋을 편집하려면 코디네이터 데몬에 연결하세요.",errorLoad:"브레인 프리셋을 불러오지 못했습니다",errorSave:"브레인 프리셋을 저장하지 못했습니다",provider:"프로바이더",model:"모델",thinking:"사고",routedDefault:"(라우팅 기본값)",defaultOption:"(기본값)",modelPlaceholder:"예: haiku, sonnet, opus",savePresets:"프리셋 저장",saving:"저장 중…",reset:"초기화",loading:"불러오는 중…",easy:"쉬움",easyHint:"사소한 수정, 이름 변경, 문서 — 토큰 절약",medium:"보통",mediumHint:"일반적인 기능 / 버그 수정 작업",difficult:"어려움",difficultHint:"아키텍처, 까다로운 디버깅, 어려운 추론",freeform:"자유형",freeformHint:"고정된 형태 없음"},magiKind:{intro:"각 태스크 유형을 검토할 에이전트를 선택하세요. 에이전트당 한 행씩 추가합니다.",refresh:"새로고침",loading:"불러오는 중…",connectPrompt:"kind → 패널 바인딩을 관리하려면 코디네이터 데몬에 연결하세요.",errorLoad:"kind 패널을 불러오지 못했습니다",errorSave:"kind 바인딩을 저장하지 못했습니다",errorRemove:"kind 바인딩을 제거하지 못했습니다",errorSlotProvider:"슬롯 {{slot}}: 프로바이더가 필요합니다",errorSlotReplica:"슬롯 {{slot}}: 복제 수는 1 이상이어야 합니다",errorNoSlot:"kind 바인딩에는 최소 하나의 슬롯이 필요합니다",removeConfirm:'"{{kind}}"의 MAGI 패널 바인딩을 제거할까요?',kindRca:"근본 원인 분석",kindDesign:"설계 / 접근 검토",kindClaimAudit:"특정 주장 검증",kindFreeform:"자유형 검토",agentCount_one:"에이전트 {{count}}개",agentCount_other:"에이전트 {{count}}개",off:"꺼짐",noAgents:"아직 에이전트가 없습니다 — 하나 추가하여 이 검토 유형을 활성화하세요.",machine:"머신",machineTitle:'이 에이전트를 실행할 머신. "any"로 두면 코디네이터가 태그로 라우팅합니다.',anyMachine:"아무 머신",offlineSuffix:"{{label}} (오프라인)",provider:"프로바이더",providerTitle:"이 슬롯이 실행하는 AI 에이전트.",selectProvider:"프로바이더 선택…",model:"모델",modelTitle:"선택적 모델 재정의(최선). 비워 두면 프로바이더 기본값을 사용합니다.",modelDefault:"기본값",modelCustom:"사용자 지정…",backToModelList:"← 모델 목록으로",copies:"복제 수",copiesTitle:"이 에이전트를 병렬로 몇 개 실행할지. 비우면 = 1.",removeAgent:"에이전트 제거",addAgent:"+ 에이전트 추가",save:"저장",saving:"저장 중…",removeBinding:"바인딩 제거",removeBindingTitle:"이 kind 바인딩 지우기",removeBindingDisabledTitle:"제거할 것이 없습니다 — 이 kind는 구성되지 않았습니다"},synthesis:{empty:"이 메시에 아직 영속된 MAGI 교차 검증 합성이 없습니다. MAGI 리뷰(mesh_magi_review)를 실행하고 수집(mesh_magi_collect)하세요. 합성된 요약이 메시 원장에 영속되어 여기에 표시됩니다.",synthesized:"합성됨",running:"실행 중",answered:"{{answered}}/{{total}} 응답",needsVerificationCount:"{{count}}건 검증 필요",agreedCount:"{{count}}건 합의",staleCount:"{{count}}건 오래됨",gitSkewLabel:"Git 편차: ",gitSkewNote_one:"브랜치 {{count}}개 ({{branches}}) — 증거가 서로 다른 코드를 비교합니다.",gitSkewNote_other:"브랜치 {{count}}개 ({{branches}}) — 증거가 서로 다른 코드를 비교합니다.",needsVerification:"검증 필요",openQuestions:"미해결 질문",rawReplicaAnswers:"원본 복제 답변",rawTitleLive:"최선: 원본 복제 텍스트는 영속되지 않으며, 복제 세션이 아직 도달 가능한 라이브 코디네이터에서만 복구할 수 있습니다.",rawTitleOffline:"원본 복제 답변을 가져오려면 라이브 코디네이터 데몬이 필요합니다.",loading:"불러오는 중…",reloadRaw:"원본 답변 다시 불러오기",loadRaw:"원본 답변 불러오기",rawNotice:"원본 복제별 텍스트는 영속되지 않습니다(이 합성 요약만 영속됨). 코디네이터에서 라이브로 가져오며, 복제 세션이 만료되거나 라이브 세션이 없으면 사용할 수 없습니다.",errorLoadRaw:"원본 답변을 불러오지 못했습니다",rawEmpty:"반환된 원본 답변이 없습니다 — 복제 트랜스크립트가 보존되지 않았거나(원본 미영속), 만료되었거나, 이 그룹에 도달 가능한 라이브 세션이 없습니다.",truncated:"잘림"}},cb={page:{title:"리포 메시",subtitle:"다중 워크스페이스 오케스트레이션",waitingForDaemon:"데몬 연결 대기 중...",observabilitySecondary:"메시 관측성"},list:{title:"리포 메시",count_one:"메시 {{count}}개",count_other:"메시 {{count}}개",createMesh:"+ 메시 생성",createTitle:"리포 메시 생성",createOnMachine:"생성할 머신",createOnMachineHint:"메시 설정은 선택한 데몬에 저장됩니다.",noConnectedDaemon:"연결된 데몬 없음",workspace:"워크스페이스",workspaceHint:"선택한 데몬에 등록된 워크스페이스에서 선택하세요.",selectMachineFirst:"머신을 먼저 선택하세요",noRegisteredWorkspaces:"등록된 워크스페이스 없음",name:"이름",namePlaceholder:"my-project-mesh",remoteUrl:"리포 리모트 URL (선택)",remoteUrlHint:"리모트 URL 또는 안정적인 식별자 중 하나를 제공하세요.",remoteUrlPlaceholder:"https://github.com/user/repo",repoIdentity:"리포 식별자 (선택)",repoIdentityPlaceholder:"github.com/user/repo",create:"생성",cancel:"취소",loading:"메시 불러오는 중...",emptyTitle:"리포 메시 없음",emptyWithDaemons:"메시를 생성하여 시작하세요.",emptyNoDaemons:"먼저 ADHDev 데몬을 연결하세요.",createFirst:"첫 메시 생성",noRepoIdentity:"리포 식별자 없음",repoMeshFallback:"리포 메시",nodesSuffix:"노드"},detail:{back:"← 뒤로",probing:"탐색 중…",refresh:"새로고침",delete:"삭제",observabilityTitle:"관측성",observabilityDescription:"관측성 대화상자에서 라이브 메시 그래프, 개요, 런타임 상태를 엽니다.",observabilityOpenTitle:"메시 그래프 / 개요 / 상태 대화상자 열기",observabilityDisabledTitle:"코디네이터 데몬을 먼저 선택해야 합니다",observabilityOpen:"메시 그래프 & 상태 열기",observabilityHint:"토폴로지 그래프, 개요 카드(미션, 원장, 큐, 노드, 세션), 노드별 런타임 편차.",schedulingTitle:"스케줄링",schedulingDescription:"대상 미지정 큐 작업이 적격 노드에 분배되는 방식.",distribution:"분배",recommended:"권장",saving:"저장 중…",visibilityTitle:"대시보드 노출",visibilityDescription:"이 코디네이터가 스폰하는 워커 세션이 대시보드 수신함에 표시되고 알림을 발생시킬지 여부.",visibilityLabel:"코디네이터가 스폰한 워커 세션",visibilityHint:"숨김 = 수신함을 조용히 유지하고 알림을 음소거; 코디네이터 세션을 통해 상호작용합니다. 표시 = 스폰된 모든 워커를 각각의 대화로 표시합니다.",visibilityHidden:"숨김 (알림 없음, 수신함 조용히 유지)",visibilityVisible:"표시 (모든 워커를 대시보드에 표시)",magiTitle:"MAGI 검토 패널",magiDescription:"MAGI(Multi-Agent Ground-truth Insight)는 서로의 작업을 교차 검증하여 실측을 드러내는 AI 에이전트 패널을 실행합니다. 각 검토 유형을 처리할 에이전트를 선택하세요.",advanced:"고급",coordinatorPromptTitle:"코디네이터 프롬프트",coordinatorPromptDescription:"코디네이터 세션의 시스템 프롬프트를 사용자 지정합니다. 메시별 재정의는 이 메시에만 적용되고, 사용자 수준 재정의는 이 데몬이 코디네이트하는 모든 메시에 적용됩니다.",thisMesh:"이 메시",thisMeshHint:"{{name}}의 코디네이터 세션에만 적용됩니다. 비워 두면 사용자 수준 / 데몬 기본값으로 넘어갑니다.",overrideLabel:"재정의 (기본값 대체)",overrideHint:"설정하면 데몬의 기본 베이스 프롬프트를 대체합니다. 비워 두면 기본값을 유지합니다.",overridePlaceholder:"(비어 있음 — 데몬 기본값 적용)",appendLabel:"추가 (베이스 뒤에 추가)",appendHint:"어떤 베이스 프롬프트가 선택되든 항상 그 뒤에 추가됩니다.",appendPlaceholder:"(비어 있음 — 추가 없음)",availablePlaceholders:"사용 가능한 플레이스홀더",saveCoordinatorPrompt:"코디네이터 프롬프트 저장",clear:"지우기",clearTitle:"두 필드를 모두 지웁니다. 저장을 클릭하여 커밋하세요.",userLevel:"사용자 수준 (이 데몬)",userLevelDescription:"코디네이터 데몬의 머신별 프롬프트 파일. 이 데몬이 코디네이트하는 모든 메시에 적용되며 데몬 간 동기화되지 않습니다. 위의 메시별 재정의가 이보다 우선합니다.",safetyTitle:"안전 & Git",safetyDescription:"코디네이터 주도 작업의 체크포인트, 승인 게이트, git 안전 동작.",checkpointBefore:"각 작업 전에 체크포인트 자동 커밋",checkpointAfter:"각 작업 후에 체크포인트 자동 커밋",pushApproval:"푸시 승인",requireApprovalBeforePush:"푸시 전 승인 필요",doNotRequireApproval:"승인 불필요",destructiveGitApproval:"파괴적 git 승인",requireApproval:"승인 필요",uncommittedChanges:"워크스페이스에 커밋되지 않은 변경이 있을 때",warnAndContinue:"경고 후 계속",blockTask:"작업 차단",checkpointThenContinue:"체크포인트 후 계속",autoPublishSubmodule:"서브모듈 커밋 자동 게시 (고급)",requireExplicitApproval:"명시적 승인 필요",allowRefineryPublish:"리파이너리 비강제 게시 허용",autoFastForward:"유휴 노드 자동 fast-forward",ffEnabled:"활성화 (온라인·클린·뒤처진 노드 따라잡기)",ffDisabled:"비활성화",includeRemoteNodes:"원격 노드 포함",includeRemoteNodesHint:"끄면 = 코디네이터의 로컬 워크스페이스만 자동 fast-forward됩니다.",remoteNo:"아니요 (로컬 워크스페이스만)",remoteYes:"예 (원격 소유 데몬에 위임)",detectionMode:"감지 모드",detectionModeHint:"Idle = 노드의 유휴 에지에서. Continuous = 주기적으로도 스캔(베이스 노드만).",idleEdgeOnly:"유휴 에지만",continuousScan:"연속 (주기적 스캔)",sessionCleanupLabel:"노드 제거 시 해당 세션은…",sessionCleanupHint:"트랜스크립트 정리를 런타임/프로세스 정리와 분리합니다.",mcpMode:"MCP 모드:",mcpDescription:"· 메시 MCP 서버는 CLI 에이전트에서 직접 사용할 수 있습니다."},nodeList:{title:"노드 & 프로바이더 ({{count}})",descriptionCloud:"이 메시의 워크스페이스와 선호 AI 도구. 설정 인벤토리 전용 — 라이브 그래프/git/세션 실측은 위의 메시 호스트 상태가 소유합니다.",descriptionStandalone:"이 메시에 참여하는 워크스페이스와 선호 AI 도구.",daemonCandidates:"머신 데몬 후보",daemonCandidatesHint:"선택한 메시 호스트 설정에 연결할 연결된 데몬을 선택하세요.",available:"{{count}}개 사용 가능",noDaemonsAvailable:"현재 사용 가능한 연결된 머신 데몬이 없습니다.",allDaemonsAttached:"연결된 모든 머신 데몬이 이미 연결되어 있습니다.",selectedHost:"선택된 호스트",attachMachine:"머신 연결",addNode:"노드 추가",attachMachineTitle:"머신 데몬 연결",addNodeTitle:"노드 추가",machine:"머신",selectMachine:"머신을 선택하세요...",workspacePath:"워크스페이스 경로",enterCustomPath:"또는 사용자 지정 경로 입력 →",pathPlaceholder:"/Users/dev/projects/myapp",preferredTools:"선호 AI 도구 (순서대로)",preferredToolsHint:"명시적 프로바이더 없이 실행할 때 사용되는 순서.",add:"추가",cancel:"취소",setupInventoryWarning:"설정 인벤토리 전용 — 라이브 git/세션/브랜치 세부 정보는 메시 호스트에서 직접 집계된 mesh_status 실측이 확보된 후 그래프 팝업에 표시됩니다.",emptyTitle:"노드 없음",emptyDescription:"이 메시에 워크스페이스를 추가하세요.",setupInventory:"설정 인벤토리",liveDetailGraphOwned:"라이브 브랜치/git/세션 세부 정보는 그래프가 소유합니다. 위 라이브 그래프의 노드 팝업을 사용하세요.",slotsLabel:"선호 AI 도구 (역량 슬롯)",slotsHint:"각 슬롯 = 프로바이더 + 모델 + 사고 + 처리할 작업 난이도/역량 + 슬롯별 병렬 상한. 작업은 최적 슬롯에 매칭됩니다(순서 = 선호도). 슬롯이 없으면 이 노드는 레거시 프로바이더 순서를 사용합니다.",nodeInstruction:"노드 지시 (선택)",nodeInstructionHint:"코디네이터 시스템 프롬프트에 📌 Node instruction으로 표시됩니다.",nodeInstructionPlaceholder:"예: '여기서는 스모크 테스트만 실행', '이 노드에서는 opus 사용'",saveInstruction:"지시 저장",saving:"저장 중…",removeNode:"노드 제거",details:"세부 정보",nodeId:"노드 ID:",launchReady:"실행 준비:",launchReadyYes:"예",launchReadyNo:"선호 도구가 구성되지 않음",repoRoot:"리포 루트:",activeSessionsLabel:"활성 세션:",added:"추가됨:",activeQueueAssignments:"활성 큐 배정",noActiveAssignment:"이 노드에 활성 배정된 큐 작업이 없습니다.",activeSessions:"활성 세션",launchBlocked:"이 노드에서 감지된 프로바이더가 없습니다 — 프로바이더가 선택되거나 설치될 때까지 작업 실행이 차단됩니다. (빈 역량 슬롯만으로는 실행이 차단되지 않습니다. 이것은 프로바이더를 찾지 못했다는 의미입니다.)"},host:{coordinatorProvider:"코디네이터 CLI 프로바이더",coordinatorProviderHint:"호스트 코디네이터 세션에 실행되는 도구.",useNodePriority:"노드 프로바이더 우선순위 사용",title:"메시 호스트 데몬",descriptionSet:"이 메시의 코디네이터와 라이브 실측(상태, 큐, 그래프, 노드 세부)을 소유하는 데몬. 메시 생성 시 고정되며 여기서 재할당할 수 없습니다.",descriptionUnset:"이 메시에는 아직 호스트가 없습니다. 연결된 데몬에서 코디네이터를 실행하면 그 데몬이 메시 호스트로 고정됩니다(1:1 핀). 이후 라이브 실측을 소유합니다.",hostLabel:"호스트:",hostNode:"호스트 노드:",unknown:"알 수 없음",hostOffline:"호스트 오프라인.",hostOfflineText:"고정된 호스트 데몬이 연결되지 않았습니다. 재연결될 때까지 라이브 상태/큐/그래프가 로드되지 않습니다. 아래에서 다른 연결된 데몬을 통해 일시적으로 명령을 라우팅할 수 있습니다 — 이는 라우팅 폴백이며 호스트 재할당이 아닙니다.",reconnectToCommand:"명령 재연결",reconnectToCommandHint:"호스트가 복귀할 때까지 이 연결된 데몬을 통해 명령을 라우팅합니다. 메시 호스트를 변경하지 않습니다.",waitForHost:"호스트 재연결 대기",noDaemonsToRoute:"명령을 라우팅할 연결된 데몬이 없습니다. 호스트(또는 다른 데몬)를 온라인으로 만드세요.",launching:"실행 중...",launchHost:"호스트 코디네이터 실행",setHostBanner:"메시 호스트를 설정하세요.",setHostBannerText:"호스트는 이 메시의 코디네이터와 라이브 실측을 소유하는 데몬입니다. 아래에서 호스트 코디네이터를 실행하여 설정하세요 — 호스트는 한 번 확립되면 고정됩니다.",hostDaemon:"호스트 데몬",hostDaemonHint:"이 메시를 호스팅할 데몬을 선택하세요. 그 위에서 코디네이터를 실행하면 호스트로 고정됩니다.",resolvingHost:"호스트 확인 중… (또는 호스팅할 데몬 선택)",launchHostSetsHost:"호스트 코디네이터 실행 (호스트 설정)",noDaemonsToHost:"연결된 데몬이 없습니다. 이 메시를 호스팅할 데몬을 온라인으로 만드세요."},slotEditor:{empty:"설정된 역량 슬롯이 없습니다 — 괜찮습니다. 이 노드는 여전히 프로바이더 우선순위(아래)로 작업을 실행합니다. 슬롯은 선택적 미세 조정입니다: 특정 작업 난이도나 역량을 특정 도구로 라우팅하려면 하나 추가하세요.",moveUp:"위로 이동",moveDown:"아래로 이동",removeSlot:"슬롯 제거",provider:"프로바이더",select:"(선택)",providerPlaceholder:"claude-cli",model:"모델",providerDefault:"(프로바이더 기본값)",custom:"사용자 지정…",modelPlaceholder:"모델",backToModelList:"← 모델 목록으로",thinking:"사고",thinkingDefault:"(기본값)",difficulty:"난이도 (비우면 = 전체)",capabilityTags:"역량 태그 (쉼표 구분)",capabilityTagsPlaceholder:"worktree, os=darwin",maxParallel:"최대 병렬 (슬롯당)",maxParallelPlaceholder:"무제한",addSlot:"슬롯 추가",saving:"저장 중…",saveSlots:"슬롯 저장"},tagEditor:{noSpaces:"태그에는 공백을 포함할 수 없습니다.",reservedPrefix:"그 접두사는 자동 파생됩니다 — 다른 태그를 선택하세요.",alreadyAdded:"이미 추가됨.",routingTags:"라우팅 태그",autoDerivedTitle:"자동 파생 — 편집할 수 없음",customTagTitle:"사용자 지정 태그",remove:"{{tag}} 제거",addPlaceholder:"사용자 지정 태그 추가 (예: test-runner)",add:"추가",saving:"저장 중…",saveTags:"태그 저장",empty:"라우팅 태그 없음 — 특정 역량과 매칭 없이 여기서 작업을 실행할 수 있습니다. 태그는 선택 사항입니다."},missions:{errorFetch:"전체 미션 목표를 가져오지 못했습니다",title:"미션",description:"코디네이터가 보고한 활성 및 과거 미션. 목표를 펼치면 전체 텍스트를 온디맨드로 가져옵니다.",empty:"{{status}} 미션이 없습니다.",taskCount_one:"태스크 {{count}}개",taskCount_other:"태스크 {{count}}개",goalUnavailable:" … (전체 목표 사용 불가)",showLess:"간략히 보기",loading:"불러오는 중…",showFullGoal:"전체 목표 보기",showMore:"{{count}}개 더 보기"},queue:{title:"큐",description:"활성 큐 작업을 과거의 완료·실패·취소된 작업 기록과 분리하여 검사합니다.",statActive:"활성",statPending:"대기",statAssigned:"배정됨",statStale:"오래됨",statHistorical:"과거",statCompleted:"완료",statFailed:"실패",loading:"불러오는 중...",refresh:"큐 새로고침",refreshHint:"호스트 소유 작업 수와 최근 배정을 보려면 큐를 새로고침하세요.",empty:"큐가 비어 있습니다.",staleBadge:"오래됨",staleTitle:"오래된 배정",waitingOnTitle:"대기 대상: {{tasks}}",waitsOn_one:"태스크 {{count}}개 대기",waitsOn_other:"태스크 {{count}}개 대기",blocked:"차단됨",durationTitle:"디스패치 → 종료 실시간",retry_one:" · 재시도 {{count}}회",retry_other:" · 재시도 {{count}}회",node:"노드 {{id}}",session:"세션 {{id}}"},promptPreview:{connectPrompt:"기본값을 미리 보려면 데몬을 연결하세요.",errorRender:"기본 프롬프트를 렌더링하지 못했습니다",hide:"기본 프롬프트 숨기기",view:"기본 프롬프트 보기",rendering:"렌더링 중…",retry:"다시 시도",info:"재정의가 비어 있을 때 코디네이터 세션이 받는 내용입니다."},hermesMcp:{title:"Hermes MCP 구성",description:"Hermes는 리포 로컬 .mcp.json을 자동 가져오지 않습니다. Hermes 구성의 mcp_servers 아래에 이 YAML을 추가한 뒤 새 Hermes 세션을 시작하세요.",fallbackProvider:"Hermes CLI"}},db={language:Xx,common:Qx,connection:Zx,toast:eb,notification:tb,event:sb,dashboard:rb,cliStop:nb,approval:ab,newSession:ob,mobileInbox:ib,meshGraph:lb,repoMesh:cb},ub={},pb={},mb={},zo="lang",Wl="common",hb={en:{common:Jx},ko:{common:db},ja:{common:ub},"zh-CN":{common:pb},es:{common:mb}};function fb(){try{const e=localStorage.getItem(zo);if(dr(e))return e}catch{}return null}function hu(){const e=fb();return e||(typeof navigator<"u"?$x(navigator.language):Jr)}function Vo(e){typeof document>"u"||document.documentElement.setAttribute("lang",e)}let Kl=!1;function xb(){if(Kl)return yt;Kl=!0;const e=hu();return yt.use(Nh).init({resources:hb,lng:e,fallbackLng:Jr,supportedLngs:mu,ns:[Wl],defaultNS:Wl,interpolation:{escapeValue:!1},returnEmptyString:!1}),Vo(e),yt}var bb=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function gb(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function Qt(e,t){if(gb(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":bb.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 qo(e){return Qt(e)==="generating"}function Ul(e,t){return Qt(e,t)==="waiting_approval"}function mt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Te(...e){for(const t of e){if(typeof t!="string")continue;const r=t.trim();if(r)return r}}function Gt(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function Dt(...e){for(const t of e)if(typeof t=="boolean")return t}function Ya(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function yb(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 Pi(e){switch(e){case"fresh":return 30;case"no_upstream":return 4;case"unchecked":case void 0:return 0;case"stale":return-10;case"unavailable":return-15;default:return 0}}function vb(e,t){if(!Array.isArray(e))return;const r=e.map(n=>{const a=mt(n),o=Te(a.path),i=Te(a.commit),c=Te(a.repoPath,a.repo_root)??yb(t,o);if(!o||!i)return null;const d={path:o,commit:i,dirty:Dt(a.dirty)??!1,outOfSync:Dt(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:Gt(a.lastCheckedAt,a.last_checked_at)??Date.now()};c&&(d.repoPath=c);const p=Te(a.error);return p&&(d.error=p),d}).filter(n=>n!==null);return r.length>0?r:void 0}function wb(e){return Dt(e.isGitRepo)!==void 0||!!Te(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||!!Te(e.repoRoot,e.repo_root,e.workspace)||Gt(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 Wn(e,t,r){const n=Dt(e.isGitRepo);if(!Object.keys(e).length||!wb(e))return;const a=n??!0,o=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(j=>typeof j=="string"):[],i=Gt(e.conflicts)??o.length,c=Dt(e.hasConflicts)??i>0,d=Te(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,p=vb(e.submodules,d),u=Te(e.upstreamStatus,e.upstream_status),m=Gt(e.upstreamFetchedAt,e.upstream_fetched_at),h=Te(e.upstreamFetchError,e.upstream_fetch_error),g=Te(e.error),k=Gt(e.staged)??0,f=Gt(e.modified)??0,v=Gt(e.untracked)??0,w=Gt(e.deleted)??0,x=Gt(e.renamed)??0;return{workspace:Te(e.workspace,t.workspace)||"",repoRoot:d??null,isGitRepo:a,branch:Te(e.branch)??null,headCommit:Te(e.headCommit)??null,headMessage:Te(e.headMessage)??null,upstream:Te(e.upstream)??null,upstreamStatus:u??"unchecked",...m!==void 0?{upstreamFetchedAt:m}:{},...h?{upstreamFetchError:h}:{},ahead:Gt(e.ahead)??0,behind:Gt(e.behind)??0,staged:k,modified:f,untracked:v,deleted:w,renamed:x,dirty:Dt(e.dirty,e.isDirty,e.is_dirty)??(k+f+v+w+x>0||c),hasConflicts:c,conflictFiles:o,stashCount:Gt(e.stashCount,e.stash_count)??0,lastCheckedAt:(r==null?void 0:r.lastCheckedAt)??Gt(e.lastCheckedAt,e.last_checked_at)??Date.now(),...p?{submodules:p}:{},...g?{error:g}:{}}}function jb(e){if(!e)return Number.NEGATIVE_INFINITY;let t=0;return e.isGitRepo===!0&&(t+=50),e.isGitRepo===!1&&(t-=10),e.branch&&(t+=20),e.headCommit&&(t+=20),e.upstream&&(t+=10),t+=Pi(e.upstreamStatus),typeof e.ahead=="number"&&(t+=2),typeof e.behind=="number"&&(t+=2),Array.isArray(e.submodules)&&e.submodules.length>0&&(t+=4+e.submodules.length),e.error&&(t-=20),t}function kb(e,t){const r=mt(e.lastGit??e.last_git),n=mt(r.result),a=mt(r.status),o=mt(n.status),i=mt(e.lastProbe??e.last_probe),c=mt(i.git),d=mt(c.result),p=mt(c.status),u=mt(d.status),m=t==null?void 0:t.lastCheckedAt;let h=null;for(const g of[a,o,p,u]){const k=Wn(g,e,{lastCheckedAt:m??Date.now()});if(!k)continue;const f=jb(k);(!h||f>h.score)&&(h={git:k,score:f})}return h==null?void 0:h.git}function Sb(e){const t=[Te(e.workspace),Te(e.providerType,e.provider),Te(e.role),Te(e.state,e.status),Te(e.title),Te(e.createdAt,e.created_at),Te(e.startedAt,e.started_at)].filter(r=>!!r);if(t.length!==0)return`synthetic:${t.join("|")}`}function Yo(e){const t=mt(e),r=Te(t.sessionId,t.session_id,t.id)??Sb(t);return r?{sessionId:r,...Te(t.providerType,t.provider)?{providerType:Te(t.providerType,t.provider)}:{},...Te(t.state,t.status)?{state:Te(t.state,t.status)}:{},...Te(t.chatStatus,t.chat_status)?{chatStatus:Te(t.chatStatus,t.chat_status)}:{},...Te(t.lifecycle)?{lifecycle:Te(t.lifecycle)}:{},...Te(t.surfaceKind,t.surface_kind)?{surfaceKind:Te(t.surfaceKind,t.surface_kind)}:{},...Te(t.recoveryState,t.recovery_state)?{recoveryState:Te(t.recoveryState,t.recovery_state)}:{},...Te(t.workspace)?{workspace:Te(t.workspace)}:{},...Te(t.title)?{title:Te(t.title)}:{},...Te(t.role)?{role:Te(t.role)}:{},...Dt(t.isSelfCoordinator,t.is_self_coordinator)!==void 0?{isSelfCoordinator:Dt(t.isSelfCoordinator,t.is_self_coordinator)}:{},...Te(t.statusNote,t.status_note)?{statusNote:Te(t.statusNote,t.status_note)}:{},...Te(t.createdAt,t.created_at)?{createdAt:Te(t.createdAt,t.created_at)}:{},...Te(t.startedAt,t.started_at)?{startedAt:Te(t.startedAt,t.started_at)}:{},...Te(t.lastActivityAt,t.last_activity_at)?{lastActivityAt:Te(t.lastActivityAt,t.last_activity_at)}:{},...Dt(t.isCached,t.is_cached)!==void 0?{isCached:Dt(t.isCached,t.is_cached)}:{}}:null}function Nb(e){const t=e&&typeof e=="object"?e:{};return Te(t.id,t.nodeId,t.node_id)}function Cb(e,t){if(!t)return!1;const r=t.trim();return r?Nb(e)===r:!1}var Ib=["daemon_","standalone_"];function Gl(e){const t=Te(e);if(t){for(const r of Ib)if(t.startsWith(r))return t.slice(r.length).trim()||void 0;return t}}function Hs(e,t){const r=Gl(e),n=Gl(t);return!r||!n?!1:r===n}var Ab=["easy","medium","difficult","freeform"];function Rt(e){return(typeof e=="string"?e.trim():"")||void 0}function js(e,t){const r=Rt(t);return r?`${e}:${r}`:void 0}function As(e,t,r){const n=js(t,r),a=Rt(r);n&&e.push(n),a&&e.push(a)}function ur(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function fu(e){return Rt(e.providerSessionId)||Rt(e.sessionId)||Rt(e.tabKey)||Rt(e.routeId)}function Ca(e){return ur([Rt(e.historySessionId),Rt(e.providerSessionId),Rt(e.sessionId)])}function Xr(e){const t=[];return As(t,"provider",e.providerSessionId),As(t,"session",e.sessionId),As(t,"tab",e.tabKey),As(t,"route",e.routeId),ur(t)}function Mb(e){const t=[];return Rt(e.providerSessionId)?(As(t,"provider",e.providerSessionId),ur(t)):Rt(e.sessionId)?(As(t,"session",e.sessionId),ur(t)):Rt(e.tabKey)?(As(t,"tab",e.tabKey),ur(t)):Rt(e.routeId)?(As(t,"route",e.routeId),ur(t)):[]}function xu(e){return js("provider",e.providerSessionId)||js("session",e.sessionId)||js("tab",e.tabKey)||js("route",e.routeId)||"unknown:"}function Ia(e){return Ca(e)[0]}function Aa(e){const t=Rt(e.sessionId),r=Ia(e);if(r&&!(t&&r===t))return r}function Tb(e){const t=Rt(e.providerSessionId),r=Rt(e.sessionId),n=Rt(e.tabKey),a=Rt(e.routeId),o=[js("provider",t),js("session",r),js("tab",n),js("route",a)].filter(d=>typeof d=="string"),i=Xr({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),c=xu({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:c,targetKey:c,targetValue:fu({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:Ia({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:i}}function Jo(e,t){const r=Tb(e);return Mb(t).some(n=>r.lookupKeys.includes(n))}function bu(e){const t=String(e.daemonId||"").trim(),r=String(e.id||"").trim();return t&&r.startsWith(`${t}:`)?r.slice(t.length+1):r}function Xo(e){if(String(e.ownerDaemonId||"").trim())return!0;const t=e.settings;return t?!!t.meshNodeFor||!!t.meshNodeId||t.launchedByCoordinator===!0||t._remoteOwnedSession===!0:!1}function _b(e,t){const r=String(e.daemonId||"").trim(),n=String(e.id||"").trim(),a=bu(e);if(a&&t.has(a))return`mesh:${a}`;const o=String(e.ownerDaemonId||"").trim()||r;return o?a?`${o}:${a}`:o:n}function Ja(e,t){return t||e||"unknown"}function Lb(e,t){return e.ownerDaemonId&&(t==null?void 0:t[e.ownerDaemonId])||e.ownerMachineName||void 0||e.daemonId&&(t==null?void 0:t[e.daemonId])||void 0}function $t(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function Rb(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 Xa(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function gu(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 Pb(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 Db(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function $b(e){return Pb(e.trim().replace(/\.local$/i,""))}function Eb(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function yu(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&&!Db(i));if(r&&r!=="Unknown")return $b(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function es(e,t={}){return Eb(e)||yu(e,t)}function vu(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 wu(e,t,r={}){const n=String(t).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(o=>String((o==null?void 0:o.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function Js(e,t){return vu(e).join(" · ")}function on(e){return e.transport==="pty"}function pr(e){return e.transport==="acp"}function Bb(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:$t(e)}function zl(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),i=$t(r||"").trim().toLowerCase();return n===a||n===o||n===i}function Fb(e,t=[],r=[]){var d,p,u,m;const n=Qt(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=>Ul(h.status,{activeModal:h.activeModal})||qo(h.status));if(a)return Qt(a.status,{activeModal:a.activeModal});const o=r.find(h=>Ul(h.status,{activeModal:h.activeModal})||qo(h.status));if(o)return Qt(o.status,{activeModal:o.activeModal});if(n&&n!=="idle")return n;const i=Qt((d=t[0])==null?void 0:d.status,{activeModal:(p=t[0])==null?void 0:p.activeModal});if(i!=="idle")return i;const c=Qt((u=r[0])==null?void 0:u.status,{activeModal:(m=r[0])==null?void 0:m.activeModal});return c!=="idle"?c:"idle"}function Ob(e){return Qt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Hb(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=Qt(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 Wb(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 Kb(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&&Wb(t.receivedAt)||0}function Ub(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Qo(e){return Math.max(Ub(e),Kb(e.activeChat))}function Gb(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 Di(e,t){return Gb(Qo(e),Qo(t),es(e,{fallbackId:e.id}),es(t,{fallbackId:t.id}),e.id,t.id)}const ju="adhdev_notification_prefs",Vl={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function zb(){try{const e=localStorage.getItem(ju);if(e){const t=JSON.parse(e);return{...Vl,...t}}}catch{}return{...Vl}}function Vb(e){try{localStorage.setItem(ju,JSON.stringify(e))}catch{}}let ws=zb(),Kn=[];function qb(){Kn.forEach(e=>e())}function Yb(e){ws={...ws,...e},Vb(ws),qb()}function Jb(){const[,e]=l.useState(0);l.useEffect(()=>{const r=()=>e(n=>n+1);return Kn.push(r),()=>{Kn=Kn.filter(n=>n!==r)}},[]);const t=l.useCallback(r=>{Yb(r)},[]);return[{...ws},t]}function Qr(e){if(!ws.globalEnabled)return!1;switch(e){case"disconnect":return ws.disconnectAlert;case"completion":return ws.completionAlert;case"approval":return ws.approvalAlert;case"browser":return ws.browserNotifications;default:return!0}}const Xb={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function ku(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Su(){return"Notification"in window&&Notification.permission==="granted"}let $s=null;function Qb(e){return e!==!1}async function Zb(){if($s!==null)return $s;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return $s=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?($s=!!await e.pushManager.getSubscription(),$s):($s=!1,!1)}catch{return $s=!1,!1}}function Zo(e,t,r){if(Su())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 eg(e,t={}){const r={...Xb,...t},n=l.useRef(new Map),a=l.useRef(0),[o,i]=l.useState(null);l.useEffect(()=>{let d=!1;return Zb().then(p=>{d||i(p)}),()=>{d=!0}},[]);const c=l.useCallback((d,p,u)=>{const m=Date.now();m-a.current<r.throttleMs||(a.current=m,Zo(d,p,u))},[r.throttleMs]);l.useEffect(()=>{var d;if(!(!r.enabled||!Su())&&Qr("browser")&&!Qb(o)){if(document.hasFocus()){for(const p of e)n.current.set(p.id,Qt(p.status,{activeModal:p.activeModal}));return}for(const p of e){const u=n.current.get(p.id),m=Qt(p.status,{activeModal:p.activeModal}),h=p.name||p.id;if(p.muted){n.current.set(p.id,m);continue}if(r.onApproval&&Qr("approval")&&m==="waiting_approval"&&u!=="waiting_approval"){const g=((d=p.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${h} — Approval needed`,g.slice(0,120),`approval-${p.id}`)}r.onComplete&&Qr("completion")&&qo(u)&&m==="idle"&&c(`✅ ${h} — Task complete`,"Agent has finished generating",`complete-${p.id}`),r.onError&&m==="error"&&u!=="error"&&c(`⚠️ ${h} — Error`,"Agent encountered an error",`error-${p.id}`),n.current.set(p.id,m)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,c])}const tg=/^(run|approve|accept|yes|allow|always)/,sg=/^(run|approve|accept|yes|allow|always|proceed|save)/,rg=/^(reject|deny|delete|remove|abort|cancel|no)/;function $i(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function ng(e){const t=$i(e).toLowerCase();return tg.test(t)?"primary":rg.test(t)?"danger":"default"}function ag(e){return sg.test($i(e).toLowerCase())?"approve":"reject"}function og(e){return e.map((t,r)=>({label:$i(t),variant:ng(t),action:ag(t),button:t,buttonIndex:r}))}function ig(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function lg(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 cg{constructor(){st(this,"dedupMap",new Map);st(this,"DEDUP_WINDOW_MS",5e3);st(this,"DEDUP_MAX_SIZE",50);st(this,"DEDUP_CLEANUP_AGE_MS",1e4);st(this,"toastCallbacks",[]);st(this,"statusEventCallbacks",[]);st(this,"resolveActionFn",null);st(this,"viewRequestRespondFn",null);st(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(r=>r!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const r of this.toastCallbacks)r(t)}showToast(t,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:t,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(t){const r=Date.now(),n=this.dedupMap.get(t)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,o]of this.dedupMap)r-o>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(t){if(t.daemonId){const a=this.ides.find(o=>o.id===t.daemonId&&o.type==="adhdev-daemon");if(a)return a}const r=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const o=this.ides.find(i=>i.id===a&&i.type==="adhdev-daemon");if(o)return o}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(t){for(const r of this.ides)if(r.id===t||r.sessionId===t||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===t))return r;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const r=this.findOwningSession(t.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}isConversationEventMuted(t){const r=t.targetSessionId;if(!r)return!1;for(const n of this.ides){if(n.id===r||n.sessionId===r)return!!n.muted;const o=(Array.isArray(n.childSessions)?n.childSessions:[]).find(i=>(i==null?void 0:i.id)===r);if(o)return!!o.muted}return!1}handleRawEvent(t,r){var f;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),o=n||t.daemonId||"",i=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),c=`${o}:${t.event}:${i}`;if(this.isDuplicate(c))return;for(const v of this.statusEventCallbacks)v(t);const d=this.isConversationEventMuted(t),p=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,u=(p==null?void 0:p.type)||"";let m=$t(u);const h=this.resolveOwningDaemon(t);if(h){const v=es(h,{fallbackId:h.id});v&&(m=!u||u==="adhdev-daemon"?v:`${v}/${m}`)}let g="",k="info";if(t.event==="agent:generating_completed"){if(g=t.duration?`✅ ${yt.t("event.taskCompletedWithDuration",{label:m,duration:t.duration})}`:`✅ ${yt.t("event.taskCompleted",{label:m})}`,k="success",!d)try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(t.event!=="agent:generating_started"){if(t.event==="agent:waiting_approval"){if(g=`⚡ ${yt.t("event.approvalNeeded",{label:m})}`,k="warning",d)g="";else if((f=t.modalButtons)!=null&&f.length&&this.resolveActionFn){const v=this.resolveActionRouteTarget(t);if(!v)return;const w=this.resolveActionFn,x=og(t.modalButtons).map(y=>({label:y.label,variant:y.variant,onClick:()=>{w(v,"resolve_action",{action:y.action,button:y.button,buttonIndex:y.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),j=ig(m,t.modalMessage,g),C=Date.now();this.emitToast({id:C,message:j,type:k,timestamp:C,targetKey:n||v,actions:x,duration:15e3}),g=""}}else if(t.event==="monitor:no_progress"||t.event==="monitor:long_generating"){const v=t.elapsedSec?Math.round(t.elapsedSec/60):0;g=v?`⚠️ ${yt.t("event.noProgressWithDuration",{label:m,minutes:v})}`:`⚠️ ${yt.t("event.noProgress",{label:m})}`,k="warning",!d&&Qr("browser")&&!document.hasFocus()&&Zo(`⚠️ ${yt.t("event.noProgressTitle",{label:m})}`,yt.t("event.noProgressBody",{duration:v?`${v}m`:""}),`no-progress-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const v=t.requesterName||yt.t("event.someoneRequester"),w=t.requestId,x=t.orgId;if(g=`👁️ ${yt.t("event.viewRequest",{requester:v})}`,k="warning",w&&x&&this.viewRequestRespondFn){const j=Date.now(),C=lg(x,w,this.viewRequestRespondFn,(y,b)=>console.error(`[EventManager] ${y} view request failed:`,b));this.emitToast({id:j,message:g,type:k,timestamp:j,actions:C,duration:3e4}),g=""}Qr("browser")&&!document.hasFocus()&&Zo(`👁️ ${yt.t("event.viewRequestTitle")}`,yt.t("event.viewRequest",{requester:v}),`view-request-${w}`)}else if(t.event==="team:view_request_approved")g=`✅ ${yt.t("event.viewRequestApproved")}`,k="success";else if(t.event==="team:view_request_rejected"){const v=t.targetName||yt.t("event.someoneTarget");g=`❌ ${yt.t("event.viewRequestDeclined",{target:v})}`,k="warning"}}if(g&&!d){const v=Date.now();this.emitToast({id:v,message:g,type:k,timestamp:v,targetKey:n||t.daemonId,duration:5e3})}}}const ut=new cg,ql=new Map;function ra(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function mr(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Ma(e){return ra(e)?ra(e.result)?e.result:e:null}function dg(e){const t=Ma(e);return!t||!ra(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function kn(e){const t=Ma(e);return!t||!ra(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function Pr(e){const t=Ma(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function Sn(e){const t=Ma(e);return!!t&&t.success===!1}function ug(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";ut.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";ut.showToast(n.notification.body,a)}}}function pg(e,t){return e&&mr(e.currentValue)?e.currentValue:t}function mg(e,t){const r=Object.keys(e).filter(a=>t[a]!==void 0);if(r.length===0)return e;const n={...e};for(const a of r)delete n[a];return n}function hg(e,t){return mr(t)?mr(e)?typeof e=="string"&&e.trim()==="":!0:!1}function fg(e,t){var o,i;if((t.now??Date.now())<t.localOverrideUntil){const c=t.localValues[e];if(mr(c))return c}const n=(o=t.controlValues)==null?void 0:o[e];if(mr(n))return n;const a=(i=t.defaultValues)==null?void 0:i[e];return mr(a)?a:void 0}function Un(e,t){return e.options||t[e.id]||[]}const xg={antigravity:new Set(["new_session"]),"claude-cli":new Set(["compact","new_session","stop"]),"claude-code-vscode":new Set(["new_session"]),codex:new Set(["new_session"])};function bg(e,t,r){var n;return((n=xg[t])==null?void 0:n.has(r.id))===!0}function gg(e){if(e)switch(e){case"idle":return["idle"];case"generating":case"streaming":case"working":case"starting":case"no_progress":case"long_generating":return["busy","generating","starting"];case"waiting_approval":case"approval":return["approval"];case"waiting_choice":return["picker"];default:return}}function yg(e,t){const r=e.visibleWhenState;if(!r||r.length===0)return!0;const n=gg(t);return n?n.some(a=>r.includes(a)):!0}function Ei(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!bg(t.hostIdeType,t.providerType,r)&&yg(r,t.currentStatus)).sort((r,n)=>(r.order??50)-(n.order??50))}function Qa(e,t){return{value:t}}function vg(e,t,r){var a;return r?((a=Un(e,t).find(o=>o.value===r))==null?void 0:a.label)||r:""}const wg={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function jg({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:i,currentStatus:c,coordinatorHint:d}){const{sendCommand:p}=bt(),u=`${e}:${t||n}`,m=wg[n]||"#94a3b8",[h,g]=l.useState({}),k=l.useRef({}),f=l.useRef(i);k.current=h,f.current=i;const v=l.useRef(0),w={};for(const B of o||[])B.defaultValue!==void 0&&(w[B.id]=B.defaultValue);const x={...w,...i||{},...Date.now()<v.current?h:{}};l.useEffect(()=>{i&&Date.now()>v.current&&g(B=>mg(B,i))},[i]);const[j,C]=l.useState(ql.get(u)||{}),[y,b]=l.useState(null),[N,S]=l.useState(null),I=l.useCallback(async(B,T={})=>{const A={...T,...t&&{targetSessionId:t},...d??{}};return await p(e,B,A)},[e,t,p,d]),R=l.useCallback(async(B,T={})=>{const A=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await I("invoke_provider_script",{...A,scriptName:B,...T})},[I,n,r,t]),L=l.useCallback((B,T,A)=>{const E=pg(A,T);g(z=>({...z,[B.id]:E})),ug(A==null?void 0:A.effects)},[]),M=l.useCallback((B,T)=>{g(A=>{const E={...A};return T===void 0?delete E[B.id]:E[B.id]=T,E}),v.current=0},[]);if(!o||o.length===0)return null;const P=Ei(o,{hostIdeType:r,providerType:n,currentStatus:c});if(P.length===0)return null;const $=async B=>{if(y===B.id){b(null);return}if(Un(B,j).length>0){b(B.id);return}if(B.dynamic&&B.listScript){S(B.id);try{const A=await R(B.listScript,{}),E=dg(A);if(!E){const re=Pr(A);re&&ut.showToast(re,"warning");return}const z=E.options;C(re=>{const X={...re,[B.id]:z};return ql.set(u,X),X});const G=fg(B.id,{localOverrideUntil:v.current,localValues:k.current,controlValues:f.current,defaultValues:w});if(hg(G,E.currentValue)){const re=E.currentValue;g(X=>({...X,[B.id]:re}))}b(B.id)}catch(A){const E=A instanceof Error?A.message:`Could not load ${B.label}`;ut.showToast(E,"warning")}finally{S(null)}}},Y=async(B,T)=>{b(null);const A=(i==null?void 0:i[B.id])??w[B.id];g(E=>({...E,[B.id]:T})),v.current=Date.now()+5e3;try{if(!B.setScript)return;const E=await R(B.setScript,Qa(B,T)),z=kn(E);if(z&&!z.ok||Sn(E))throw new Error((z==null?void 0:z.error)||Pr(E)||`Could not update ${B.label}`);L(B,T,z)}catch(E){M(B,A);const z=E instanceof Error?E.message:`Could not update ${B.label}`;ut.showToast(z,"warning")}},_=async B=>{const T=Un(B,j).map(X=>X.value);if(T.length===0)return;const A=String(x[B.id]||""),z=(T.indexOf(A)+1)%T.length,G=T[z];if(typeof G!="string")return;const re=(i==null?void 0:i[B.id])??w[B.id];g(X=>({...X,[B.id]:G})),v.current=Date.now()+5e3;try{if(!B.setScript)return;const X=await R(B.setScript,Qa(B,G)),te=kn(X);if(te&&!te.ok||Sn(X))throw new Error((te==null?void 0:te.error)||Pr(X)||`Could not update ${B.label}`);L(B,G,te)}catch(X){M(B,re);const te=X instanceof Error?X.message:`Could not update ${B.label}`;ut.showToast(te,"warning")}},H=async B=>{const A=!x[B.id],E=(i==null?void 0:i[B.id])??w[B.id];g(z=>({...z,[B.id]:A})),v.current=Date.now()+5e3;try{if(!B.setScript)return;const z=await R(B.setScript,Qa(B,A)),G=kn(z);if(G&&!G.ok||Sn(z))throw new Error((G==null?void 0:G.error)||Pr(z)||`Could not update ${B.label}`);L(B,A,G)}catch(z){M(B,E);const G=z instanceof Error?z.message:`Could not update ${B.label}`;ut.showToast(G,"warning")}},W=async B=>{if(!B.invokeScript)return;if(B.confirmMessage){const A=[B.confirmTitle,B.confirmMessage,B.confirmLabel].filter(z=>typeof z=="string"&&z.trim().length>0);if(!window.confirm(A.join(`
|
|
32
|
+
|
|
33
|
+
`)))return}const T=(i==null?void 0:i[B.id])??w[B.id];try{const A=await R(B.invokeScript),E=kn(A);if(E&&!E.ok||Sn(A))throw new Error((E==null?void 0:E.error)||Pr(A)||`Could not run ${B.label}`);E&&L(B,T??!0,E)}catch(A){M(B,T);const E=A instanceof Error?A.message:`Could not run ${B.label}`;ut.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:`${m}33`,background:`${m}12`,color:m},children:a}),P.map(B=>{const T=String(x[B.id]||""),A=vg(B,j,T),E=y===B.id,z=N===B.id,G=Un(B,j),re="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(B.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${re} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:E?`${m}55`:"var(--border-default)",background:E?`${m}10`:"var(--surface-tertiary)",color:T?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void $(B),title:B.label,children:[B.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:B.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:z?"Loading…":A||B.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),E&&G.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[var(--z-dropdown)]",onClick:()=>b(null)}),s.jsxs("div",{className:"absolute bottom-full left-0 z-[var(--z-dropdown)] 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:B.label}),G.map(X=>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:X.value===T?`${m}14`:"transparent",color:X.value===T?"var(--text-primary)":"var(--text-secondary)",borderLeft:X.value===T?`2px solid ${m}`:"2px solid transparent"},title:X.description||X.label,onMouseEnter:te=>{te.currentTarget.style.background=`${m}10`},onMouseLeave:te=>{te.currentTarget.style.background=X.value===T?`${m}14`:"transparent"},onClick:()=>void Y(B,X.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:X.label}),X.value===T&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},X.value))]})]})]},B.id);case"cycle":return s.jsxs("button",{type:"button",className:`${re} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:T?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void _(B),title:`Click to cycle: ${G.map(X=>X.label).join(" → ")}`,children:[B.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:B.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:A||B.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},B.id);case"toggle":return s.jsxs("button",{type:"button",className:`${re} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:T?`${m}44`:"var(--border-default)",background:T?`${m}14`:"var(--surface-tertiary)",color:T?m:"var(--text-muted)"},onClick:()=>void H(B),"aria-pressed":!!T,children:[B.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:B.icon}),B.label]},B.id);case"action":return s.jsxs("button",{type:"button",className:`${re} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void W(B),children:[B.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:B.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:B.resultDisplay==="inline"&&T?`${B.label}: ${T}`:B.label})]},B.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:T?"var(--text-primary)":"var(--text-muted)"},children:[B.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:B.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:T?`${B.label}: ${T}`:B.label})]},B.id);default:return null}})]})})}function kg({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:i,controls:c,controlValues:d,currentStatus:p,coordinatorHint:u}){const{isVisible:m}=Ri(),h=Ei(c,{hostIdeType:a,providerType:o,currentStatus:p});return!e||t||h.length===0||!m?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(jg,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:i,controls:h,controlValues:d,currentStatus:p,coordinatorHint:u})})}const Dr=5,Nu=10*1024*1024;function Sg({hasDraft:e,isBusy:t=!1}){return!e||t}function Ng(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 Cg(e){if(e.size>Nu)return null;const t=await Ng(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 Ig(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const Cu=l.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:o=null,inlineStatusMessage:i=null,onSend:c,onForceSend:d,canForceSend:p=!1,isActive:u=!0,showControlsToggle:m=!1,animateVisibility:h=!0,onControlsToggle:g,messageInput:k}){const f=l.useRef(null),v=l.useRef(null),[w,x]=l.useState(""),[j,C]=l.useState([]),[y,b]=l.useState(null),[N,S]=l.useState(!1),I=l.useRef(!1),{isVisible:R,toggleVisibility:L}=Ri(),M=Ig(k),P=!!w.trim()||j.length>0;l.useEffect(()=>{x(""),C([]),b(null)},[t]),l.useEffect(()=>{var A;u&&((A=f.current)==null||A.focus({preventScroll:!0}))},[t,u]),l.useEffect(()=>{const A=f.current;A&&(A.style.height="auto",A.style.height=`${Math.min(A.scrollHeight,160)}px`)},[w]);const $=l.useCallback(async A=>{b(null);const E=Array.from(A).filter(J=>J.type.startsWith("image/"));if(E.length===0)return;const z=Dr-j.length;if(z<=0){b(`Max ${Dr} images`);return}const G=E.slice(0,z);if(G.filter(J=>J.size>Nu).length>0){b("Image too large (max 10 MB)");return}const te=(await Promise.all(G.map(Cg))).filter(J=>J!==null);C(J=>[...J,...te])},[j.length]),Y=l.useCallback(A=>{C(E=>E.filter((z,G)=>G!==A))},[]),_=l.useCallback(async()=>{const A=w.trim();if(!A&&j.length===0||a||I.current)return;I.current=!0;const E=j.length>0?[...j]:void 0;try{await c(A,E)!==!1&&(x(""),C([]),b(null))}finally{I.current=!1}},[w,j,a,c]),H=l.useCallback(async()=>{if(!p||!d)return;const A=w.trim();if(!A&&j.length===0||I.current)return;I.current=!0;const E=j.length>0?[...j]:void 0;try{await d(A,E)!==!1&&(x(""),C([]),b(null))}finally{I.current=!1}},[j,p,w,d]),W=l.useCallback(A=>{M&&(A.preventDefault(),S(!0))},[M]),B=l.useCallback(()=>S(!1),[]),T=l.useCallback(A=>{M&&(A.preventDefault(),S(!1),A.dataTransfer.files.length>0&&$(A.dataTransfer.files))},[M,$]);return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",h?"transition-all duration-200 ease-out":"",N?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:u?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:u?200:0,opacity:u?1:0,transform:u?"translateY(0)":"translateY(10px)",padding:u?"10px 12px":"0 12px",pointerEvents:u?"auto":"none"},"aria-hidden":!u,onDragOver:W,onDragLeave:B,onDrop:T,children:[j.length>0&&s.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:j.map((A,E)=>s.jsxs("div",{className:"relative group w-14 h-14 rounded-lg overflow-hidden border border-border-subtle shrink-0",style:{background:"var(--surface-secondary)"},children:[s.jsx("img",{src:A.previewUrl,alt:A.name,className:"w-full h-full object-cover"}),s.jsx("button",{type:"button",onClick:()=>Y(E),className:"absolute top-0.5 right-0.5 w-4 h-4 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity text-[10px] leading-none","aria-label":`Remove ${A.name}`,children:"✕"})]},E))}),s.jsxs("div",{className:"flex gap-2 items-center",title:u?`Send message to ${r}`:void 0,children:[m&&s.jsx("button",{type:"button",onClick:()=>{L(),g==null||g()},"aria-label":R?"Hide controls":"Show controls","aria-pressed":R,title:R?"Hide controls":"Show controls",className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:s.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[s.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),M&&s.jsxs(s.Fragment,{children:[s.jsx("input",{ref:v,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:A=>{A.target.files&&$(A.target.files),A.target.value=""}}),s.jsx("button",{type:"button",onClick:()=>{var A;return(A=v.current)==null?void 0:A.click()},disabled:j.length>=Dr,title:j.length>=Dr?`Max ${Dr} images`:"Attach image",className:"h-10 w-8 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center disabled:opacity-40","aria-label":"Attach image",children:s.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"})})})]}),s.jsx("div",{className:"flex-1 relative",children:s.jsx("textarea",{ref:f,rows:1,placeholder:o||(M&&j.length>0?"Add a message (optional)...":`Send message to ${r}... (Shift+Enter for newline)`),value:w,onChange:A=>x(A.target.value),onPaste:A=>{if(M&&A.clipboardData.files.length>0&&Array.from(A.clipboardData.files).some(K=>K.type.startsWith("image/"))){A.preventDefault(),$(A.clipboardData.files);return}const E=A.clipboardData.getData("text/plain"),z=qh(E);if(z===E)return;A.preventDefault();const G=f.current,re=(G==null?void 0:G.selectionStart)??w.length,X=(G==null?void 0:G.selectionEnd)??w.length,te=w.slice(0,re)+z+w.slice(X);x(te);const J=re+z.length;requestAnimationFrame(()=>{G==null||G.setSelectionRange(J,J)})},onKeyDown:A=>{A.key==="Enter"&&(A.nativeEvent.isComposing||A.shiftKey||(A.preventDefault(),_()))},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:()=>{_()},disabled:Sg({hasDraft:P,isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${P&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:P&&!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:P?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})}),p&&s.jsx("button",{type:"button",onClick:()=>{H()},disabled:!P,className:`h-10 px-3 rounded-full text-[11px] font-medium border border-border-subtle shrink-0 transition-colors ${P?"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"})]}),(y||M&&N)&&s.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${y?"text-red-400":"text-[var(--accent-primary)]"}`,children:y||"Drop image here"}),i&&!y&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),Ag=l.createContext(null);function Bi(){return l.useContext(Ag)}function Mg(e){return kb(e,{lastCheckedAt:Date.now()})}function Tg(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 _g(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 na(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=Tg(e);return t.outOfSync?"degraded":t.dirty||_g(e)?"dirty":"online"}function Lg(e,t){const r=t?na(t):void 0;return!e||e==="unknown"?r:e}function Rg(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(Yo).filter(i=>i!==null);if(o.length>0)return o}const r=mt(e.activeSession??e.active_session),n={...r,sessionId:Te(r.sessionId,r.id,r.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id)},a=Yo(n);return a?[a]:void 0}function Pg(e){const t=mt(e.connection);return Object.keys(t).length>0?t:void 0}function Dg(e){const t=e==null?void 0:e.source,r=e==null?void 0:e.transport;return{...e,perspective:(e==null?void 0:e.perspective)??"selected_coordinator",source:t&&t!=="not_reported"?t:"mesh_peer_status",state:"connected",transport:r&&r!=="unknown"?r:"direct",reported:!0,reason:"Live peer git snapshot reported by the selected coordinator."}}function Fi(e){var r;const t=e.git;return!!(t&&(t.isGitRepo===!0||t.isGitRepo===!1||t.branch||t.upstream||t.headCommit||typeof t.lastCheckedAt=="number"||(((r=t.submodules)==null?void 0:r.length)??0)>0))}function Yl(e){var n,a,o,i,c,d;let t=0;const r=e.git;return Fi(e)&&(t+=80,(r==null?void 0:r.isGitRepo)===!0&&(t+=20),(r==null?void 0:r.isGitRepo)===!1&&(t+=5),r!=null&&r.branch&&(t+=20),r!=null&&r.upstream&&(t+=12),r!=null&&r.headCommit&&(t+=12),t+=Pi(r==null?void 0:r.upstreamStatus),typeof(r==null?void 0:r.lastCheckedAt)=="number"&&(t+=6),t+=(((n=r==null?void 0:r.submodules)==null?void 0:n.length)??0)*6),(a=e.branchConvergence)!=null&&a.status&&(t+=12),(((o=e.connection)==null?void 0:o.state)==="connected"||((i=e.connection)==null?void 0:i.state)==="self")&&(t+=8),((c=e.connection)==null?void 0:c.transport)==="direct"&&(t+=4),((d=e.connection)==null?void 0:d.source)==="mesh_peer_status"&&(t+=4),e.health==="online"&&(t+=4),e.health==="dirty"&&(t+=3),e.health==="degraded"&&(t+=2),e.launchReady&&(t+=2),e.gitProbePending&&(t-=40),e.error&&(t-=10),t}function $g(e,t){var k,f,v,w;const r=Yl(e),a=Yl(t)>r?t:e,o=a===t?e:t,i=a.git??o.git,c=(((k=a.providers)==null?void 0:k.length)??0)>0?a.providers:o.providers,d=(((f=a.activeSessions)==null?void 0:f.length)??0)>0?a.activeSessions:o.activeSessions,p=(((v=a.activeSessionDetails)==null?void 0:v.length)??0)>0?a.activeSessionDetails:o.activeSessionDetails,u=(((w=a.providerPriority)==null?void 0:w.length)??0)>0?a.providerPriority:o.providerPriority,m=a.connection??o.connection,h={...o,...a,machineLabel:a.machineLabel||o.machineLabel,workspace:a.workspace||o.workspace,...a.repoRoot||o.repoRoot?{repoRoot:a.repoRoot||o.repoRoot}:{},...a.daemonId||o.daemonId?{daemonId:a.daemonId||o.daemonId}:{},...a.machineId||o.machineId?{machineId:a.machineId||o.machineId}:{},...a.machineStatus||o.machineStatus?{machineStatus:a.machineStatus||o.machineStatus}:{},health:i&&(!a.health||a.health==="unknown")?na(i):a.health,providers:c??[],activeSessions:d??[],...p&&p.length>0?{activeSessionDetails:p}:{},...u&&u.length>0?{providerPriority:u}:{},...m?{connection:m}:{},...i?{git:i}:{}},g=mt(a.branchConvergence);return Object.keys(g).length>0?Object.assign(h,{branchConvergence:g}):delete h.branchConvergence,i&&(delete h.gitProbePending,delete h.error),h}function Iu(e){const t=mt(e),r=Te(t.nodeId,t.id);if(!r)return null;const n=mt(t.cachedStatus),a=Mg(t),o=a?void 0:Wn(mt(t.git),t)??Wn(t,t),i=a??o,c=i?void 0:Wn(mt(n.git),t),d=i??c,p=Te(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),u=Te(t.health),m=a?na(d):Lg(u,i)||(d?na(d):void 0)||Te(n.health)||p||Te(t.status)||"unknown",g=(a?void 0:Te(t.error))??(i?void 0:Te(n.error)),k=Rg(t),f=Ya(t.activeSessions),v=(k==null?void 0:k.map(S=>S.sessionId))??[],w=Ya(t.providerPriority),x=Dt(t.gitProbePending,t.git_probe_pending),j=i?void 0:x,C=Pg(t),y=mt(t.branchConvergence??t.branch_convergence),b=C==null?void 0:C.state,N=a&&(!(C!=null&&C.reported)||b==="unknown")?Dg(C):C;return{nodeId:r,machineLabel:Te(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,r)||r,workspace:Te(t.workspace,d==null?void 0:d.workspace)||"",...Te(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:Te(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)}:{},...Te(t.daemonId,t.daemon_id)?{daemonId:Te(t.daemonId,t.daemon_id)}:{},...Te(t.machineId,t.machine_id)?{machineId:Te(t.machineId,t.machine_id)}:{},...p?{machineStatus:p}:{},...Dt(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:Dt(t.isLocalWorktree,t.is_local_worktree)}:{},...Te(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:Te(t.worktreeBranch,t.worktree_branch)}:{},...Te(t.clonedFromNodeId,t.cloned_from_node_id)?{clonedFromNodeId:Te(t.clonedFromNodeId,t.cloned_from_node_id)}:{},health:m,...d?{git:d}:{},...j!==void 0?{gitProbePending:j}:{},providers:Ya(t.providers),activeSessions:f.length>0?f:v,...k&&k.length>0?{activeSessionDetails:k}:{},...w.length>0?{providerPriority:w}:{},...Dt(t.launchReady)!==void 0?{launchReady:Dt(t.launchReady)}:a?{launchReady:!0}:{},...Te(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)?{lastSeenAt:Te(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)}:{},...Te(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)?{updatedAt:Te(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)}:{},...N?{connection:N}:{},...Object.keys(y).length>0?{branchConvergence:y}:{},...t.scheduling&&typeof t.scheduling=="object"?{scheduling:t.scheduling}:{},...Dt(t.autoFastForwardEligible,t.auto_fast_forward_eligible)===!0?{autoFastForwardEligible:!0}:{},...t.worktreeBootstrap&&typeof t.worktreeBootstrap=="object"?{worktreeBootstrap:t.worktreeBootstrap}:{},...t.staleDaemonBuild&&typeof t.staleDaemonBuild=="object"?{staleDaemonBuild:t.staleDaemonBuild}:{},...t.providerVersions&&typeof t.providerVersions=="object"&&!Array.isArray(t.providerVersions)?{providerVersions:t.providerVersions}:{},...Te(t.daemonBuildVersion,t.daemon_build_version)?{daemonBuildVersion:Te(t.daemonBuildVersion,t.daemon_build_version)}:{},...g?{error:g}:{}}}function Jl(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 Au(e,t){const r=Array.isArray(e.coordinatorSessions)?e.coordinatorSessions:Array.isArray(e.coordinator_sessions)?e.coordinator_sessions:[],n=r.map(Yo).filter(a=>a!==null);return n.length===0?t:t.map(a=>{const o=n.filter(c=>{const d=mt(r.find(h=>{const g=mt(h);return Te(g.sessionId,g.session_id,g.id)===c.sessionId})),p=Te(d.nodeId,d.node_id),u=Te(d.daemonId,d.daemon_id),m=Te(d.workspace);return p&&p===a.nodeId?!0:Hs(u,a.daemonId)?!m||!a.workspace||m===a.workspace:!!(m&&a.workspace&&m===a.workspace)});if(o.length===0)return a;const i=Jl([...a.activeSessionDetails??[],...o]);return{...a,activeSessionDetails:i,activeSessions:Jl([...a.activeSessionDetails??[],...o,...(a.activeSessions??[]).map(c=>({sessionId:c}))]).map(c=>c.sessionId)}})}function Eg(e){const t=mt(e);return Array.isArray(t.sessions)||Array.isArray(t.active_session_details)||Te(t.daemon_id,t.machine_id,t.repo_root,t.worktree_branch,t.cloned_from_node_id)!==void 0||Dt(t.is_local_worktree)!==void 0}function Mu(e){const t=new Map,r=[];for(const n of e){const a=Eg(n)?Iu(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=$g(o,a);t.set(a.nodeId,i);const c=r.findIndex(d=>d.nodeId===a.nodeId);c>=0&&(r[c]=i)}return r}function Tu(e){const t=e??{},r=Mu(t.nodes??[]);return{...t,nodes:Au(t,r)}}function Bg(e){var r;const t=e==null?void 0:e.git;return{nodeId:(e==null?void 0:e.nodeId)??null,chosenSource:t?"live_git":e!=null&&e.gitProbePending?"pending_git":"no_git",hasLiveGit:Fi(e??{git:void 0}),branch:(t==null?void 0:t.branch)??null,upstream:(t==null?void 0:t.upstream)??null,headCommit:(t==null?void 0:t.headCommit)??null,submoduleCount:((r=t==null?void 0:t.submodules)==null?void 0:r.length)??0,pendingGit:(e==null?void 0:e.gitProbePending)===!0,connection:e!=null&&e.connection?{state:e.connection.state,transport:e.connection.transport,source:e.connection.source}:null}}function Fg(e){const t=Te(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(d=>Iu(d)).filter(d=>d!==null):null;if(!t||!n)return null;const a=Au(e,Mu(n)),o=Te(e.meshName,e.mesh_name,e.name),i=Te(e.repoIdentity,e.repo_identity),c=Te(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 Og(e){var o;let t=0;const r=mt(e.sourceOfTruth),n=mt(r.directPeerTruth);Te(r.currentStatus)==="live_git_and_session_probes"&&(t+=100),r.coordinatorOwnsLiveTruth===!0&&(t+=25),n.satisfied===!0&&(t+=15);for(const i of e.nodes){const c=i.git;if(!c){i.gitProbePending&&(t-=8);continue}t+=10,c.isGitRepo===!0&&(t+=5),c.isGitRepo===!1&&(t+=1),c.branch&&(t+=4),c.upstream&&(t+=3),c.headCommit&&(t+=3),t+=Pi(c.upstreamStatus),typeof c.ahead=="number"&&(t+=1),typeof c.behind=="number"&&(t+=1),typeof c.lastCheckedAt=="number"&&(t+=2),t+=(((o=c.submodules)==null?void 0:o.length)??0)*2}return t}function Hg(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 Wg=20;function Xl(e){let t=null;for(const r of e){const n=Fg(mt(r));if(!n)continue;const a=Og(n),o=Hg(n);if(!t){t={status:n,score:a,refreshedAt:o};continue}(Math.abs(a-t.score)<=Wg?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 Oi(e){const r=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,n=Xl([r==null?void 0:r.status,r]);return n||Xl([e==null?void 0:e.status,e])}function Kg(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 Ug(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 Gg(e,t){var a;if(!t)return null;const r=Oi(e),n=(a=r==null?void 0:r.nodes)==null?void 0:a.find(o=>Cb(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}const zg={sm:"max-w-md",md:"max-w-lg",lg:"max-w-3xl"};function _u({open:e,onClose:t,size:r="md",title:n,footer:a,children:o,showClose:i=!0,closeOnBackdrop:c=!0,closeOnEsc:d=!0,ariaLabel:p,className:u,contentClassName:m}){l.useEffect(()=>{if(!e||!d)return;const f=v=>{v.key==="Escape"&&t()};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[e,d,t]);const h=l.useCallback(f=>{c&&f.target===f.currentTarget&&t()},[c,t]);if(!e)return null;const g=n!=null||i,k=s.jsx("div",{className:Ft("fixed inset-0 flex items-center justify-center bg-black/60 p-4",u),style:{zIndex:"var(--z-modal-backdrop)"},onClick:h,children:s.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":n==null?p:void 0,className:Ft("relative flex max-h-[calc(100dvh-2rem)] w-full flex-col overflow-hidden","rounded-xl border border-border-default bg-surface-primary shadow-2xl",zg[r],m),style:{zIndex:"var(--z-modal)"},onClick:f=>f.stopPropagation(),children:[g&&s.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-4 border-b border-border-default px-5 py-4",children:[s.jsx("div",{className:"min-w-0",children:typeof n=="string"||typeof n=="number"?s.jsx("h2",{className:"truncate text-lg font-bold text-text-primary",children:n}):n}),i&&s.jsx("button",{type:"button",onClick:t,className:"btn btn-ghost btn-sm h-8 w-8 shrink-0 p-0","aria-label":"Close dialog",children:s.jsx(Nt,{size:16})})]}),s.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-5 py-4",children:o}),a!=null&&s.jsx("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border-default px-5 py-4",children:a})]})});return typeof document>"u"?k:hr.createPortal(k,document.body)}function Ql(e){if(!e||!Number.isFinite(e))return"—";try{return`${new Date(e).toLocaleString()} (${e})`}catch{return String(e)}}function Zl(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 Vg({sessionId:e,daemonId:t,conv:r,onClose:n}){var y,b;const{sendCommand:a}=bt(),o=Bi(),[i,c]=l.useState(!0),[d,p]=l.useState(null),[u,m]=l.useState(null),[h,g]=l.useState(null),[k,f]=l.useState(null),v=l.useMemo(()=>Kg(r),[r]),w=l.useMemo(()=>Ug(r),[r]),x=l.useCallback(async()=>{c(!0),m(null);try{const N=await a(t,"get_session_info",{targetSessionId:e}),S=N&&typeof N=="object"?N:{},I=S.result&&typeof S.result=="object"?S.result:S;I!=null&&I.success?p(I):(m((I==null?void 0:I.error)||"Failed to load session info"),p(null))}catch(N){m((N==null?void 0:N.message)||String(N)),p(null)}finally{c(!1)}},[a,t,e]);l.useEffect(()=>{x()},[x]);const j=l.useCallback(async()=>{if(g(null),f(null),!(!v||!w||!(o!=null&&o.loadMeshStatus)))try{const N=await o.loadMeshStatus(t,v,{refresh:!1}),S=Gg(N,w);if(!S){f("This session is stamped to a mesh node that the coordinator no longer reports.");return}g(S)}catch(N){f((N==null?void 0:N.message)||"Failed to load mesh node info")}},[o,t,v,w]);l.useEffect(()=>{j()},[j]);const C=s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",onClick:()=>void x(),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"})]});return s.jsx(_u,{open:!0,onClose:n,title:"Session info",size:"lg",footer:C,children:s.jsxs("div",{className:"text-sm space-y-4",children:[i&&s.jsx("div",{className:"text-text-secondary",children:"Loading…"}),u&&s.jsx("div",{className:"text-red-500",children:u}),(d==null?void 0:d.session)&&s.jsxs(ar,{title:"Session",children:[s.jsx(rt,{k:"Session ID",v:s.jsx(At,{children:d.session.sessionId})}),s.jsx(rt,{k:"Provider",v:`${d.session.providerName||d.session.providerType} (${d.session.providerType})`}),d.session.transport&&s.jsx(rt,{k:"Transport",v:d.session.transport}),d.session.workspace&&s.jsx(rt,{k:"Workspace",v:s.jsx(At,{children:d.session.workspace})}),s.jsx(rt,{k:"Spawned at",v:s.jsxs(s.Fragment,{children:[Ql(d.session.spawnedAtMs),d.session.spawnedAtMs?s.jsx("span",{className:"text-text-secondary ml-2",children:Zl(d.session.spawnedAtMs)}):null]})}),d.session.providerSessionId&&s.jsx(rt,{k:"Provider session ID",v:s.jsx(At,{children:d.session.providerSessionId})}),!d.session.workspace&&(r==null?void 0:r.workspacePath)&&s.jsx(rt,{k:"Workspace",v:s.jsx(At,{children:r.workspacePath})}),(r==null?void 0:r.machineName)&&s.jsx(rt,{k:"Machine",v:r.machineName}),(r==null?void 0:r.connectionState)&&s.jsx(rt,{k:"Connection",v:r.connectionState}),(r==null?void 0:r.git)&&s.jsx(rt,{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"]})})]}),((y=d==null?void 0:d.session)==null?void 0:y.launch)&&s.jsxs(ar,{title:"Launch",children:[d.session.launch.command&&s.jsx(rt,{k:"Command",v:s.jsx(At,{children:d.session.launch.command})}),d.session.launch.cwd&&s.jsx(rt,{k:"Working directory",v:s.jsx(At,{children:d.session.launch.cwd})}),Array.isArray(d.session.launch.args)&&d.session.launch.args.length>0&&s.jsx(rt,{k:"Args",v:s.jsx(At,{children:d.session.launch.args.join(" ")})}),Array.isArray(d.session.launch.extraArgs)&&d.session.launch.extraArgs.length>0&&s.jsx(rt,{k:"Extra args",v:s.jsx(At,{children:d.session.launch.extraArgs.join(" ")})}),Array.isArray(d.session.launch.extraEnvKeys)&&d.session.launch.extraEnvKeys.length>0&&s.jsx(rt,{k:"Extra env",v:s.jsx(At,{children:d.session.launch.extraEnvKeys.join(", ")})})]}),h&&s.jsxs(ar,{title:"Mesh node",children:[h.nodeId&&s.jsx(rt,{k:"Node ID",v:s.jsx(At,{children:h.nodeId})}),h.workspace&&s.jsx(rt,{k:"Workspace",v:s.jsx(At,{children:h.workspace})}),h.repoRoot&&h.repoRoot!==h.workspace&&s.jsx(rt,{k:"Repo root",v:s.jsx(At,{children:h.repoRoot})}),h.daemonId&&s.jsx(rt,{k:"Daemon ID",v:s.jsx(At,{children:h.daemonId})}),h.role&&s.jsx(rt,{k:"Role",v:h.role}),h.machineStatus&&s.jsx(rt,{k:"Machine status",v:h.machineStatus}),h.health&&s.jsx(rt,{k:"Health",v:h.health}),h.isLocalWorktree&&s.jsx(rt,{k:"Worktree",v:h.worktreeBranch?s.jsx(At,{children:h.worktreeBranch}):"yes"}),typeof h.launchReady=="boolean"&&s.jsx(rt,{k:"Launch ready",v:h.launchReady?"yes":"no"}),h.git&&s.jsx(rt,{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(rt,{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(rt,{k:"Providers",v:s.jsx(At,{children:h.providers.join(", ")})}),Array.isArray(h.providerPriority)&&h.providerPriority.length>0&&s.jsx(rt,{k:"Provider priority",v:s.jsx(At,{children:h.providerPriority.join(" › ")})})]}),!h&&k&&(v||w)&&s.jsx(ar,{title:"Mesh node",children:s.jsx("div",{className:"text-text-secondary italic",children:k})}),(d==null?void 0:d.coordinator)&&s.jsxs(ar,{title:"Mesh coordinator",children:[s.jsx(rt,{k:"Mesh ID",v:s.jsx(At,{children:d.coordinator.meshId})}),d.coordinator.cliType&&s.jsx(rt,{k:"Coordinator CLI",v:d.coordinator.cliType}),s.jsx(rt,{k:"Started at",v:s.jsxs(s.Fragment,{children:[Ql(d.coordinator.startedAt),d.coordinator.startedAt?s.jsx("span",{className:"text-text-secondary ml-2",children:Zl(d.coordinator.startedAt)}):null]})}),d.coordinator.injection&&s.jsx(rt,{k:"Prompt injection",v:`${d.coordinator.injection.mode}${d.coordinator.injection.target?` → ${d.coordinator.injection.target}`:""}`}),d.coordinator.mcpConfigPath&&s.jsx(rt,{k:"MCP config",v:s.jsx(At,{children:d.coordinator.mcpConfigPath})}),d.coordinator.extraSystemPrompt&&s.jsx(ei,{title:"Per-launch extra prompt",body:d.coordinator.extraSystemPrompt,defaultOpen:!0}),d.coordinator.systemPrompt&&s.jsx(ei,{title:"Final system prompt (click to expand)",body:d.coordinator.systemPrompt})]}),((b=d==null?void 0:d.session)==null?void 0:b.runtimeMetadata)!=null&&s.jsx(qg,{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."})]})})}function ar({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 rt({k:e,v:t}){return s.jsxs("div",{className:"flex flex-col sm:flex-row gap-1 sm:gap-3",children:[s.jsx("div",{className:"w-full sm:w-36 sm:shrink-0 text-text-secondary font-medium sm:font-normal",children:e}),s.jsx("div",{className:"min-w-0 break-all",children:t})]})}function At({children:e}){return s.jsx("code",{className:"font-mono text-xs",children:e})}function qg({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(ar,{title:"Runtime",children:[n&&s.jsx(rt,{k:"Runtime ID",v:s.jsx(At,{children:n})}),a&&s.jsx(rt,{k:"Lifecycle",v:a}),o&&s.jsx(rt,{k:"Surface",v:o}),i&&s.jsx(rt,{k:"Recovery state",v:i}),typeof t.restoredFromStorage=="boolean"&&s.jsx(rt,{k:"Restored from storage",v:t.restoredFromStorage?"yes":"no"}),c!=null&&s.jsx(rt,{k:"Attached clients",v:String(c)}),s.jsx(ei,{title:"Raw runtime metadata (click to expand)",body:Yg(e)})]})}function Yg(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function ei({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 Jg({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(Vg,{sessionId:e,daemonId:t,conv:r,onClose:()=>a(!1)})]})}const Xg=8e3;function Qg({sessionId:e,daemonId:t,muted:r,sendDaemonCommand:n}){const[a,o]=l.useState(null),i=l.useRef(null);if(l.useEffect(()=>{a!==null&&r===a&&o(null)},[r,a]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]),!e||!t)return null;const c=a!==null?a:r,d=()=>{const p=!c;o(p),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>o(null),Xg),n(t,"set_conversation_prefs",{sessionId:e,muted:p}).catch(u=>{console.warn("[conversation-prefs] toggle mute failed",u),o(null)})};return s.jsx("button",{type:"button",onClick:d,"aria-label":c?"Unmute this chat":"Mute this chat","aria-pressed":c,title:c?"Muted — notifications silenced. Click to unmute.":"Mute notifications for this chat",className:`inline-flex items-center justify-center w-6 h-6 rounded-full leading-none transition-colors ${c?"bg-amber-500 text-white hover:bg-amber-600":"text-text-secondary hover:text-text-primary hover:bg-surface-secondary"}`,style:{pointerEvents:"auto"},children:c?s.jsx(Qd,{size:13}):s.jsx(Nr,{size:13})})}function Lu(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}function Ru(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function Zg(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 Za(e){return Zg(e)?String(e.role||"").toLowerCase():""}const ey=4;function ty(e,t){if(e.length===0)return[];for(let o=t.length-1;o>=0;o-=1)if(Za(t[o])==="assistant")return[];const r=t.some(o=>Za(o)==="user"),n=[];let a=!1;for(let o=e.length-1;o>=0&&n.length<ey;o-=1){const i=e[o],c=Za(i);if(c){if(!a&&c==="assistant"){n.unshift(i),a=!0;continue}if(a&&c==="user"){r||n.unshift(i);break}}}return n}function sy(e){return e.map((t,r)=>({message:t,index:r,ts:Lu(t)})).sort((t,r)=>t.ts-r.ts||t.index-r.index).map(t=>t.message)}function ry(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=ty(o,i),d=c.length>0?[...c,...i]:i,p=t.length===0?d:[...t,...d];return sy(p)}const dt=e=>e.transport==="pty",Ir=(e,t)=>dt(e)&&e.mode||"chat",Pu=(e,t)=>dt(e)&&Ir(e)==="terminal",lt=e=>e.transport==="acp",ny=180;function _s(e){return e.streamSource!=="agent-stream"}function Rs(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function Ta(e){var r;const t=typeof((r=e.settings)==null?void 0:r.meshCoordinatorDaemonId)=="string"?e.settings.meshCoordinatorDaemonId:void 0;return t?{meshCoordinatorDaemonId:t}:{}}function Du(e){return e.machineName||""}function er(e){return Rs(e)}function bs(e){return e.agentType||""}function aa(e){return e.hostIdeType||""}function Hi(e){return e.displayPrimary||e.agentName||"Agent"}function $u(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function ay(e,t){const r=Ru(e,t);return[...r].reverse().find(n=>!(n!=null&&n._localId))||r[r.length-1]}function Eu(e,t){const r=ay(e,t),n=xr(r==null?void 0:r.content),a=xr(e.lastMessagePreview);return a&&e.lastMessageRole==="assistant"&&(r==null?void 0:r.role)==="user"?a:n||a||""}function oy(e,t=ny){const r=xr(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 iy(e){return oy(Eu(e)||e.displaySecondary||"")}function Bu(e){return[e.displaySecondary,Du(e)].filter(Boolean)}function gr(e){return e.agentName||$t(bs(e))}function ly(e){var t,r;if(!_s(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return $t(aa(e)||bs(e))}function Fu(e){return _s(e)?e.sessionId:e.nativeSessionId}function ec(e){return _s(e)?"native":e.tabKey}function cy(e){return e.sessionId}function dy(e,t){if(t)return _s(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function uy(e,t){const r=bs(e),n=_s(e),a=dt(e)||lt(e),o=n?a?gr(e)||(t==null?void 0:t.cliName)||$t(aa(e)||r):t!=null&&t.type?$t(t.type):$t(aa(e)||r):gr(e);return{isNativeConversation:n,isCli:dt(e),isAcp:lt(e),isCliTerminal:Pu(e),providerType:r,displayLabel:o,targetEntry:dy(e,t)}}function Ws(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:dt(e)||lt(e)?{agentType:bs(e)}:e.streamSource==="agent-stream"?{agentType:bs(e)}:t}function Ks(e){return e?er(e):""}function or(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 tc(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 py(){return"open_panel"}function my({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function sc(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function Nn(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Zr(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Ki(e){return e instanceof Error?e.message:String(e||"")}function rc(e){const t=Ki(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function nc(e,t){const r=Ki(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function ac(e,t,r,n={}){const a=Ws(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 _a({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,o]=l.useState(!1),[i,c]=l.useState(!1),[d,p]=l.useState(null),u=l.useRef(!1),m=l.useRef(null);l.useEffect(()=>{p(null)},[t==null?void 0:t.tabKey]);const h=l.useCallback(async(w,x)=>{if(!t||u.current)return!1;const j=w.trim(),C=Wi(t);if(my({hasMessage:!!j,blockedMessage:C,sendInFlight:u.current}))return C&&p(C),!1;const y=Date.now(),b={tabKey:t.tabKey,message:j,timestamp:y};if(sc(m.current,b))return p(null),!0;u.current=!0,c(!0),p(null),m.current=b;try{const N=Ks(t);if(!N)return m.current=Nn(m.current,b),p("Unable to send message right now."),!1;const S=await e(N,"send_chat",ac(j,x,t)),I=Zr(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(N){const S=Ki(N);return S.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",S):console.warn("Send blocked/failed",N),m.current=Nn(m.current,b),p(tc(N)),!1}finally{u.current=!1,c(!1)}},[t,e]),g=l.useCallback(async(w,x)=>{if(!t||u.current)return!1;const j=w.trim();if(!j&&(!x||x.length===0))return!1;const C=Date.now(),y={tabKey:t.tabKey,message:`force:${j}`,timestamp:C};if(sc(m.current,y))return p(null),!0;u.current=!0,c(!0),p(null),m.current=y;try{const b=Ks(t);if(!b)return m.current=Nn(m.current,y),p("Unable to send message right now."),!1;const N=await e(b,"send_chat",ac(j,x,t,{force:!0})),S=Zr(N);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(b){return console.warn("Force send blocked/failed",b),m.current=Nn(m.current,y),p(tc(b)),!1}finally{u.current=!1,c(!1)}},[t,e]),k=l.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(w){console.error("Relaunch failed",w)}},[t,e]),f=l.useCallback(async w=>{if(t)try{const j=(t.modalButtons||[]).indexOf(w),C=w.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),y=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(C),b=Ks(t);if(!b)return;const N=await e(b,"resolve_action",{button:w,action:y?"approve":"reject",...j>=0&&{buttonIndex:j},...Ws(t),...Ta(t)}),S=Zr(N);S.success||r(I=>[...I,{routeId:t.tabKey,text:nc(w,S==null?void 0:S.error),timestamp:Date.now()}])}catch(x){rc(x)||console.error("[ModalButton] Error:",x),r(j=>[...j,{routeId:t.tabKey,text:rc(x)?nc(w,x):`❌ **${w}** error`,timestamp:Date.now()}])}},[t,e,r]),v=l.useCallback(async()=>{if(!(!t||a)){o(!0);try{await e(t.routeId,py(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(w){console.error("Focus agent failed",w)}finally{o(!1)}}},[t,a,e]);return{isSendingChat:i,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:h,handleForceSendChat:g,handleRelaunch:k,handleModalButton:f,handleFocusAgent:v}}const hy=10,fy=8e3,xy=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function by(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 ti(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(xy.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=by(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=>ti(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,ti(a,n,r+1)]))}function $r(e,t){return Array.isArray(e)?e.slice(-t):[]}function gy(e,t=Date.now()){const r=e&&t-e.firstAt<=fy,n=r?e.count+1:1;return n>=hy?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function Hu(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:$r(e.chatTailState.liveMessages??t.messages,10),activeConversationMessagesTail:$r(t.messages,10),visibleMessagesTail:$r(e.visibleMessages,5),historyMessagesTail:$r(e.chatTailState.historyMessages,5),actionLogsTail:$r(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 ti(r)}function Wu(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 Ku(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 Uu(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(`
|
|
34
|
+
`)}return typeof t.text=="string"?t.text:t.bundle&&typeof t.bundle=="object"?`# ADHDev Chat Debug Bundle
|
|
35
|
+
|
|
36
|
+
\`\`\`json
|
|
37
|
+
${JSON.stringify(t.bundle,null,2)}
|
|
38
|
+
\`\`\``:`# ADHDev Chat Debug Bundle
|
|
39
|
+
|
|
40
|
+
\`\`\`json
|
|
41
|
+
${JSON.stringify(t,null,2)}
|
|
42
|
+
\`\`\``}function eo(e,t){return`${e}:${t}`}function yy(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function vy(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function sr(e,t){vy()&&console.debug(`[subscription-manager] ${e}`,t)}class wy{constructor(){st(this,"active",new Map);st(this,"retryTimers",new Map)}subscribe(t,r,n,a,o){var u,m;const i=eo(n.topic,n.key),c=this.active.get(i);let d=!0;if(c)c.handlers.add(a),(!yy(c.request,n)||c.daemonId!==r)&&(c.daemonId=r,c.request=n,d=((u=t.sendData)==null?void 0:u.call(t,r,n))??!1,!d&&(o!=null&&o.retryIntervalMs)?this.scheduleRetry(i,t,o.retryIntervalMs):d&&this.clearRetry(i),sr("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),sr("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((m=t.sendData)==null?void 0:m.call(t,r,n))??!1,!d&&(o!=null&&o.retryIntervalMs)&&this.scheduleRetry(i,t,o.retryIntervalMs)}const p=()=>{var k;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 g={type:"unsubscribe",topic:n.topic,key:n.key};sr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(k=t.sendData)==null||k.call(t,r,g)};return p.initialSendAccepted=d,p}publish(t){const r=eo(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,fr.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),fr.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=eo(t,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(t){var r;sr("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(n=>({daemonId:n.daemonId,topic:n.request.topic,key:n.request.key}))});for(const n of this.active.values())(r=t.sendData)==null||r.call(t,n.daemonId,n.request)}resubscribeForDaemon(t,r){var a;const n=Array.from(this.active.values()).filter(o=>o.daemonId===t);sr("resubscribe_daemon",{daemonId:t,count:n.length,subscriptions:n.map(o=>({topic:o.request.topic,key:o.request.key}))});for(const o of n)(a=r.sendData)==null||a.call(r,o.daemonId,o.request)}scheduleRetry(t,r,n){if(this.retryTimers.has(t))return;const a=setTimeout(()=>{var c;this.retryTimers.delete(t);const o=this.active.get(t);if(!o)return;const i=((c=r.sendData)==null?void 0:c.call(r,o.daemonId,o.request))??!1;sr("subscribe_retry",{id:t,accepted:i,topic:o.request.topic,key:o.request.key}),i||this.scheduleRetry(t,r,n)},n);this.retryTimers.set(t,a)}clearRetry(t){const r=this.retryTimers.get(t);r!==void 0&&(clearTimeout(r),this.retryTimers.delete(t))}}const is=new wy;function jy(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 ky(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 to(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function Sy(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function Ny(e){Sy()&&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 oa(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:u}=ky(d),m=jy(o,n),h=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,g=p.filter(v=>v.kind==="workspace"&&v.transport==="cdp-page"),k=p.filter(v=>v.kind==="agent"&&v.transport==="pty"),f=p.filter(v=>v.kind==="agent"&&v.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:c,...e.version&&{version:e.version},...h&&{machine:h,platform:h.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},_sessionListAuthoritative:Array.isArray(e.sessions),cdpConnected:g.some(v=>!!v.cdpConnected)});for(const v of g){const w=m.get(v.id),x=Gr(v,w),j=(u.get(v.id)||[]).map(C=>Gr(C,m.get(C.id)));r.push({id:`${n}:ide:${v.id}`,sessionId:v.id,providerSessionId:v.providerSessionId??(w==null?void 0:w.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,status:x.cdpConnected?"online":"detected",daemonId:n,instanceId:to(n,v.id),workspace:x.workspace,terminals:0,childSessions:j,agents:j.map(C=>({id:C.id,name:C.providerName||C.providerType,type:C.providerType,status:C.status})),activeChat:x.activeChat,...x.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:x.activeInteractivePrompt},chats:[],cdpConnected:x.cdpConnected,...x.lastMessagePreview!==void 0&&{lastMessagePreview:x.lastMessagePreview},...x.lastMessageRole!==void 0&&{lastMessageRole:x.lastMessageRole},...x.lastMessageAt!==void 0&&{lastMessageAt:x.lastMessageAt},...x.lastMessageHash!==void 0&&{lastMessageHash:x.lastMessageHash},lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,seenCompletionMarker:x.seenCompletionMarker,surfaceHidden:x.surfaceHidden,muted:x.muted,...x.controlValues!==void 0&&{controlValues:x.controlValues},...x.providerControls!==void 0&&{providerControls:x.providerControls},...x.summaryMetadata!==void 0&&{summaryMetadata:x.summaryMetadata},...x.settings!==void 0&&{settings:x.settings},...x.messageInput!==void 0&&{messageInput:x.messageInput},timestamp:c})}for(const v of k){const w=m.get(v.id),x=Gr(v,w);r.push({id:`${n}:cli:${v.id}`,sessionId:v.id,providerSessionId:v.providerSessionId??(w==null?void 0:w.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,agentType:x.providerType,status:x.status||"running",daemonId:n,instanceId:to(n,v.id),cliName:x.providerName||x.providerType,mode:x.mode||(w==null?void 0:w.mode)||"terminal",workspace:x.workspace||"",...v.ownerDaemonId&&{ownerDaemonId:v.ownerDaemonId},...v.ownerMachineName&&{ownerMachineName:v.ownerMachineName},activeChat:x.activeChat,...x.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:x.activeInteractivePrompt},...x.resume!==void 0&&{resume:x.resume},...x.runtimeKey!==void 0&&{runtimeKey:x.runtimeKey},...x.runtimeDisplayName!==void 0&&{runtimeDisplayName:x.runtimeDisplayName},...x.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:x.runtimeWorkspaceLabel},...x.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:x.runtimeWriteOwner},...x.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:x.runtimeAttachedClients},...x.lastMessagePreview!==void 0&&{lastMessagePreview:x.lastMessagePreview},...x.lastMessageRole!==void 0&&{lastMessageRole:x.lastMessageRole},...x.lastMessageAt!==void 0&&{lastMessageAt:x.lastMessageAt},...x.lastMessageHash!==void 0&&{lastMessageHash:x.lastMessageHash},lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,seenCompletionMarker:x.seenCompletionMarker,surfaceHidden:x.surfaceHidden,muted:x.muted,...x.controlValues!==void 0&&{controlValues:x.controlValues},...x.providerControls!==void 0&&{providerControls:x.providerControls},...x.summaryMetadata!==void 0&&{summaryMetadata:x.summaryMetadata},...x.settings!==void 0&&{settings:x.settings},...x.messageInput!==void 0&&{messageInput:x.messageInput},timestamp:c,_isCli:!0})}for(const v of f){const w=m.get(v.id),x=Gr(v,w);r.push({id:`${n}:acp:${v.id}`,sessionId:v.id,providerSessionId:v.providerSessionId??(w==null?void 0:w.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,agentType:x.providerType,status:x.status||"running",daemonId:n,instanceId:to(n,v.id),cliName:x.providerName||x.providerType,mode:"chat",workspace:x.workspace||"",...v.ownerDaemonId&&{ownerDaemonId:v.ownerDaemonId},...v.ownerMachineName&&{ownerMachineName:v.ownerMachineName},activeChat:x.activeChat,...x.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:x.activeInteractivePrompt},...x.runtimeKey!==void 0&&{runtimeKey:x.runtimeKey},...x.runtimeDisplayName!==void 0&&{runtimeDisplayName:x.runtimeDisplayName},...x.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:x.runtimeWorkspaceLabel},...x.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:x.runtimeWriteOwner},...x.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:x.runtimeAttachedClients},...x.lastMessagePreview!==void 0&&{lastMessagePreview:x.lastMessagePreview},...x.lastMessageRole!==void 0&&{lastMessageRole:x.lastMessageRole},...x.lastMessageAt!==void 0&&{lastMessageAt:x.lastMessageAt},...x.lastMessageHash!==void 0&&{lastMessageHash:x.lastMessageHash},lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,seenCompletionMarker:x.seenCompletionMarker,surfaceHidden:x.surfaceHidden,muted:x.muted,...x.controlValues!==void 0&&{controlValues:x.controlValues},...x.providerControls!==void 0&&{providerControls:x.providerControls},...x.summaryMetadata!==void 0&&{summaryMetadata:x.summaryMetadata},...x.settings!==void 0&&{settings:x.settings},...x.messageInput!==void 0&&{messageInput:x.messageInput},timestamp:c,_isAcp:!0})}return Ny(r),r}const Cy=15e3,Iy=15e3,Ay=6e4,oc=12,My=8e3,Ty=4e3;function _y(e){const{force:t,hasSubscription:r,loadedAt:n,now:a,minFreshMs:o}=e;return t||n<=0?!0:r?!1:a-n>=o}const so=new Map,ro=new Map,Cn=new Set;function Ly(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 Ar(){const{sendCommand:e,sendData:t}=bt(),{injectEntries:r,getIdes:n}=nn();return l.useCallback(async(a,o)=>{if(!a)return;const i=(o==null?void 0:o.minFreshMs)??Ay;if(!_y({force:o==null?void 0:o.force,hasSubscription:Cn.has(a),loadedAt:ro.get(a)||0,now:Date.now(),minFreshMs:i}))return;const c=so.get(a);if(c)return c;const d=(async()=>{t&&!Cn.has(a)&&(is.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},f=>{const v=n(),w=v.find(j=>j.id===a),x=oa(f.status,{daemonId:a,existingDaemon:w,existingEntries:v,timestamp:f.timestamp});x.length>0&&r(x),ro.set(a,Date.now())}).initialSendAccepted?Cn.add(a):Cn.delete(a));const p=await e(a,"get_status_metadata"),u=Ly(p);if(!u)return;const m=n(),h=m.find(k=>k.id===a),g=oa(u,{daemonId:a,existingDaemon:h,existingEntries:m,timestamp:u.timestamp||Date.now()});g.length>0&&r(g,{authoritativeDaemonIds:[a]}),ro.set(a,Date.now())})().finally(()=>{so.delete(a)});return so.set(a,d),d},[n,r,e,t])}const Ry=60,Py=50;function Gu(e={}){return e.isCliLike?Py:Ry}function Dy(e={}){return Gu(e)}const fn=60,$y=1e3,Ey=750,ic=500,La=12e4,zu=new Set(["generating","waiting_approval","starting","streaming","working"]),ln=new Map;let Vu=0;const si=new Set;function By(){Vu+=1;for(const e of si)e()}function Fy(e){return si.add(e),()=>{si.delete(e)}}function lc(){return Vu}function xn(e,t,r){return`${e}::${t}::${r||t}`}function ia(e=fn){return{liveMessages:[],hasLiveSnapshot:!1,cursor:Oy([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Oy(e,t=fn){return{tailLimit:t}}function cc(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 la(e){if(typeof e=="string")return e;if(e==null)return"";if(Array.isArray(e))return e.map(la).join(`
|
|
43
|
+
`);if(typeof e=="object"){const t=e;return la(t.text??t.content??t.value??"")}return String(e)}function Ui(e){return la(e.content).replace(/[─━═│┃┄┅┈┉┌┐└┘├┤┬┴┼╭╮╰╯╴╶╷╵\s]+/g,"").length===0}function Hy(e){return e.length===0||e.every(Ui)}function dc(e){for(let t=e.length-1;t>=0;t-=1){const r=e[t],n=typeof(r==null?void 0:r.role)=="string"?r.role:"",a=typeof(r==null?void 0:r.kind)=="string"?r.kind:"";if(!(n==="system"||a==="system")&&!(a==="tool"||a==="thought"||a==="terminal"||a==="activity")&&!Ui(e[t]))return n}return""}function uc(e){for(let t=e.length-1;t>=0;t-=1){const r=e[t],n=typeof(r==null?void 0:r.role)=="string"?r.role:"",a=typeof(r==null?void 0:r.kind)=="string"?r.kind:"";if(n==="system"||a==="system"||a==="tool"||a==="thought"||a==="terminal"||a==="activity"||Ui(e[t]))continue;if(n!=="assistant")return"";const o=e[t];return`${String(o.bubbleId??o.providerUnitKey??o.id??"")}#${la(o.content).length}`}return""}function qu(e,t){if(dc(t)!=="assistant")return!1;const r=Array.isArray(e.liveMessages)?e.liveMessages:[];return dc(r)!=="assistant"}function Wy(e){return!!e&&typeof e=="object"&&e.selected==="native-history"}function Ky(e,t,r){return Wy(r)?qu(e,t):!1}function Yu(e){const t=typeof e=="string"?e.toLowerCase():"";return t==="generating"||t==="no_progress"||t==="long_generating"||t==="streaming"||t==="working"||t==="starting"}function Ju(e){const t=typeof e=="string"?e.trim().toLowerCase():"";return zu.has(t)}function Xu(e,t){return Math.max(Math.max(0,t),Array.isArray(e.liveMessages)?e.liveMessages.length:0)}function Uy(e,t,r,n,a,o){const i=Ju(n)||Yu(n),c=o&&e.hasLiveSnapshot;if(!i&&!c)return!1;const d=i?Xu(e,t):Array.isArray(e.liveMessages)?e.liveMessages.length:0;if(d<=0)return!1;if(Hy(r))return!0;if(c&&!i&&qu(e,r))return!1;if(a&&typeof a=="object"){const p=a.selected,u=a.fallbackReason;if(p==="native-history"||typeof u=="string"&&u!==""&&!u.startsWith("native_history_"))return!1}return r.length<d}function Gy(e,t,r,n){if(r.length!==0||Xu(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 zy(e,t,r,n,a,o){return Uy(e,t,r,n,a,o)?"defer-busy-shrink":Gy(e,t,r,a)?"skip-transient-empty":"apply"}function Vy(e){if(Array.isArray(e.messages))return e.messages;const t=e.messagesTail;return Array.isArray(t)?t:[]}function pc(e,t){const r=e[t];return typeof r=="string"?r:""}class qy{constructor(t){st(this,"manager");st(this,"sendData");st(this,"daemonId");st(this,"sessionId");st(this,"historySessionId");st(this,"subscriptionKey");st(this,"fallbackRecentCount");st(this,"snapshot");st(this,"transportSubscription",null);st(this,"listeners",new Set);st(this,"retainCount",0);st(this,"loadHistoryPromise",null);st(this,"pendingDisconnectTimer",null);st(this,"authoritativeRefreshPromise",null);st(this,"lastAuthoritativeRefreshAt",0);st(this,"now");st(this,"lastActiveStatusAt",0);this.manager=t.manager||is,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.now=t.now??(()=>Date.now()),this.snapshot=ia(Math.max(0,t.tailLimit??fn))}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.now&&(this.now=t.now),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={...ia(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>ic?d.slice(d.length-ic):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}refreshAuthoritativeTail(t,r={}){if(this.authoritativeRefreshPromise)return this.authoritativeRefreshPromise;const n=this.now();if(!r.force&&this.lastAuthoritativeRefreshAt>0&&n-this.lastAuthoritativeRefreshAt<Ey)return Promise.resolve();this.lastAuthoritativeRefreshAt=n;const a=(async()=>{try{const o=await t();o&&this.handleUpdate(o)}catch{}})().finally(()=>{this.authoritativeRefreshPromise=null});return this.authoritativeRefreshPromise=a,a}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:$y}))}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=pc(t,"sessionId");if(r&&r!==this.sessionId)return;const n=pc(t,"historySessionId");if(n&&this.historySessionId&&n!==this.historySessionId)return;const a=Vy(t),o=t.messageSource,i=this.now(),c=this.lastActiveStatusAt>0&&i-this.lastActiveStatusAt<=La;(Ju(t.status)||Yu(t.status))&&(this.lastActiveStatusAt=i);const d=Ky(this.snapshot,a,o);if(!d&&zy(this.snapshot,this.fallbackRecentCount,a,t.status,o,c)!=="apply")return;const p={tailLimit:this.snapshot.cursor.tailLimit};!d&&cc(this.snapshot.liveMessages)===cc(a)&&uc(this.snapshot.liveMessages)===uc(a)&&this.snapshot.cursor.tailLimit===p.tailLimit||(this.snapshot={...this.snapshot,liveMessages:a,hasLiveSnapshot:!0,cursor:p,messageSource:o},this.emit())}}function Qu(e){const t=xn(e.daemonId,e.sessionId,e.historySessionId),r=ln.get(t);if(r)return r.updateOptions(e),r;const n=new qy(e);return ln.set(t,n),By(),n}function Yy(e,t,r){if(!e||!t)return;const n=`${e}::${t}::`,a=xn(e,t,r);for(const[o,i]of ln.entries())(o===a||o.startsWith(n))&&i.clearLiveSnapshot()}function Zu(e){const t=er(e),r=e.sessionId||"";if(!t||!r)return;const n=Aa(e),a=xn(t,r,n||r),o=ln.get(a);if(!o)return;const i=o.getSnapshot();return i.hasLiveSnapshot?i:void 0}function Jy(e,t){return{...e,loadHistoryPage:t}}function Xy(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||(e.historySessionId||"").localeCompare(t.historySessionId||"")}function Qy(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(zu.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??La)),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 Zy(e=La){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function e0(e,t={}){const r=new Set,n=[];for(const a of e){if(!Qy(a,t))continue;const o=er(a),i=a.sessionId||"";if(!o||!i)continue;const c=Aa(a),d=xn(o,i,c||i);r.has(d)||(r.add(d),n.push({daemonId:o,sessionId:i,historySessionId:c,subscriptionKey:`daemon:${o}:session:${i}`}))}return n.sort(Xy),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function t0(e,t){const{sendData:r,sendCommand:n,isConnected:a}=bt(),o=(t==null?void 0:t.enabled)!==!1,i=er(e),c=e.sessionId||"",d=Aa(e),p=`daemon:${i}:session:${c}`,u=Math.max(0,(t==null?void 0:t.tailLimit)??fn),m=e.messages.length,h=l.useMemo(()=>!o||!i||!c?null:Qu({daemonId:i,sessionId:c,historySessionId:d,subscriptionKey:p,sendData:r,tailLimit:u,fallbackRecentCount:m}),[i,o,d,r,c,p,u]);l.useEffect(()=>{h==null||h.updateOptions({fallbackRecentCount:m})},[h,m]);const[g,k]=l.useState(()=>(h==null?void 0:h.getSnapshot())||ia(u));l.useEffect(()=>{if(!h){k(ia(u));return}h.retain(),k(h.getSnapshot());const w=h.subscribe(x=>{k(x)});return()=>{w(),h.release()}},[h,u]);const f=l.useCallback(async()=>{!h||!i||!c||await h.loadHistoryPage(async({offset:w,excludeRecentCount:x})=>{const j=e.agentType,C=await n(i,"chat_history",{agentType:j,offset:w,limit:30,targetSessionId:c,historySessionId:d,excludeRecentCount:x}),y=C&&typeof C=="object"&&"result"in C?C.result||{}:C||{};return{messages:Array.isArray(y.messages)?y.messages:[],hasMore:y.hasMore===!0}})},[e.agentType,h,i,d,n,c]),v=l.useCallback((w=!1)=>!h||!i||!c?Promise.resolve():h.refreshAuthoritativeTail(async()=>{const x=await n(i,"read_chat",{agentType:e.agentType,targetSessionId:c,historySessionId:d,...u>0?{tailLimit:u}:{}}),j=x&&typeof x=="object"&&"result"in x?x.result:x;if(!j||typeof j!="object"||j.success===!1)return null;const C=Array.isArray(j.messages)?j.messages:Array.isArray(j.messagesTail)?j.messagesTail:[];return{topic:"session.chat_tail",key:p,sessionId:c,historySessionId:d,seq:0,timestamp:0,messages:C,status:typeof j.status=="string"?j.status:"idle",...j.messageSource&&typeof j.messageSource=="object"?{messageSource:j.messageSource}:{}}},{force:w}),[e.agentType,h,i,d,n,c,p,u]);return l.useEffect(()=>{if(!h||!o||!i||!c)return;v(!0);const w=()=>{typeof document<"u"&&document.visibilityState==="visible"&&v()};typeof document<"u"&&document.addEventListener("visibilitychange",w);let x=a?a(i):!0;const j=setInterval(()=>{if(!a)return;const C=a(i);C&&!x&&v(),x=C},2e3);return()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",w),clearInterval(j)}},[h,i,o,c,d]),l.useMemo(()=>Jy(g,f),[f,g])}function s0(e,t){const{sendData:r}=bt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??fn),o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??La)),i=Zy(o),[c,d]=l.useState(0);l.useEffect(()=>{if(!n||e.length===0)return;const u=setInterval(()=>{d(m=>m+1)},i);return()=>{clearInterval(u)}},[e.length,n,i]);const p=l.useMemo(()=>e0(e,{recentActivityMs:o}),[e,o,c]);l.useEffect(()=>{if(!n||!r||p.descriptors.length===0)return;const u=p.descriptors.map(m=>Qu({...m,sendData:r,tailLimit:a}));return u.forEach(m=>{m.retain()}),()=>{u.forEach(m=>m.release())}},[p.signature,n,r,a])}function r0(e){const[t,r]=l.useState(0),n=l.useMemo(()=>{const i=[];for(const c of e){const d=er(c),p=c.sessionId||"";if(!d||!p)continue;const u=Aa(c);i.push(xn(d,p,u||p))}return i},[e]),a=n.join("|"),o=l.useSyncExternalStore(Fy,lc,lc);return l.useEffect(()=>{if(n.length===0)return;const i=[];for(const c of n){const d=ln.get(c);if(!d)continue;let p=!1;i.push(d.subscribe(()=>{if(!p){p=!0;return}r(u=>u+1)}))}return()=>{for(const c of i)c()}},[a,o]),t}function n0(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function a0(e){return n0(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Gn=new Map,ri=new Set;function mc(e,t){!e||Gn.get(e)===t||(t?Gn.set(e,!0):Gn.delete(e),ri.forEach(n=>n(e,t)))}function o0(e){return e?Gn.get(e)===!0:!1}function i0(e){return ri.add(e),()=>{ri.delete(e)}}function l0(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function c0(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function d0(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function ep(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function tp(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 u0(e){return ep(e)?!1:e.inboxBucket==="task_complete"&&tp(e).length>0}function hc(e){return e.branch||"detached HEAD"}function p0(e){if(e.error)return`${hc(e)} · Git error: ${e.error}`;const t=[hc(e)];return e.changedFiles>0?t.push(l0(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 m0(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${p0(t)}`}function h0(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function f0(e,t={}){if(t.enabled===!1)return[];if(!d0(e))return[];const r=ep(e)?"working":u0(e)?"complete":null;if(!r)return[];const n=r==="complete"?tp(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${c0(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:m0(r,e.git),timestamp:h0(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 x0=60;function b0(e){return e.status==="no_progress"||e.status==="long_generating"?"Agent shows no progress.":e.status==="generating"||e.status==="streaming"?"Agent is generating.":e.status==="waiting_approval"&&(!e.modalButtons||e.modalButtons.length===0)?"Agent is waiting for approval. Approval controls will appear when available.":null}function ni({activeConv:e,ideEntry:t,handleSendChat:r,handleForceSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:d,userName:p,scrollToBottomRequestNonce:u,isInputActive:m=!0,isVisible:h=!0}){var we,me,U,O,Z,V,he,le;const g=l.useRef(new Map),k=l.useRef(void 0),f=Ar(),{sendCommand:v}=bt(),{isVisible:w}=Ri();hn("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:d.length,isSendingChat:a});const x=Lt.useMemo(()=>Cr(e),[e.status,e.connectionState]);Lt.useEffect(()=>{const D=e.sessionId;if(D)return mc(D,x.isGenerating),()=>{mc(D,!1)}},[e.sessionId,x.isGenerating]);const j=l.useMemo(()=>uy(e,t),[e,t]),C=l.useMemo(()=>{var D;return Ei((D=j.targetEntry)==null?void 0:D.providerControls,{hostIdeType:e.hostIdeType,providerType:j.providerType})},[e.hostIdeType,j.providerType,(we=j.targetEntry)==null?void 0:we.providerControls]),y=Gu({isCliLike:j.isCli||j.isAcp}),b=Dy({isCliLike:j.isCli||j.isAcp}),N=t0(e,{enabled:h&&!!e.sessionId,tailLimit:b}),[S,I]=l.useState(y),[R,L]=l.useState(()=>Ll()),M=e.tabKey,P=N.historyMessages,$=N.hasMoreHistory,Y=N.historyError,_=Ru(e,N),H=su(_).length;l.useEffect(()=>{I(y)},[y,M]);const W=Math.max(0,_.length-S),B=Hi(e),T=er(e),A=a0(e),E=Wi(e),z=b0(e),G=o||E,re=G||z,X=!!E,[te,J]=l.useState(!1);l.useEffect(()=>{const D=j.targetEntry;T&&(!D||D.providerControls===void 0||D.controlValues===void 0)&&f(T,{minFreshMs:3e4}).catch(()=>{})},[T,j.isAcp,(me=j.targetEntry)==null?void 0:me.providerControls,(U=j.targetEntry)==null?void 0:U.controlValues,f]);const F=l.useCallback(async()=>{if(!te){if(_.length>S){I(D=>Math.min(_.length,D+x0));return}J(!0);try{await N.loadHistoryPage()}finally{J(!1)}}},[N,te,_.length,S]),{allMessages:K,receivedAtMap:fe}=l.useMemo(()=>{const D=ry({historyMessages:P,liveMessages:_,visibleLiveCount:S}),de=f0(e),Se=de.length>0?[...D,...de]:D,ue={};return Se.forEach((q,ve)=>{const Ae=`${e.tabKey}:${ta(q)}`;let Ne=Lu(q)||g.current.get(Ae)||0;Ne||(Ne=Date.now(),g.current.set(Ae,Ne)),ue[ta(q)]=Ne}),{allMessages:Se,receivedAtMap:ue}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,W,P,_,S]),be=l.useMemo(()=>d.filter(D=>D.routeId===e.tabKey).sort((D,de)=>D.timestamp-de.timestamp),[d,e.tabKey]),oe=l.useCallback(async()=>{var ve,Ae;if(!T)return;const D=Hu({activeConv:e,visibleMessages:K,actionLogs:d,controls:(ve=j.targetEntry)==null?void 0:ve.providerControls,controlValues:(Ae=j.targetEntry)==null?void 0:Ae.controlValues,visibleBarControlCount:C.length,chatTailState:{liveMessages:N.liveMessages,hasLiveSnapshot:N.hasLiveSnapshot,hasMoreHistory:$,historyError:Y,historyMessages:P},ui:{controlsVisible:w,visibleLiveCount:S,activityVisible:R,activityCount:H,hiddenLiveCount:W,isInputActive:m,isVisible:h}}),de=await v(T,"get_chat_debug_bundle",{agentType:j.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:D}),Se=Zr(de),ue=Uu(Se),q=await Ku(ue);q==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),ut.showToast(Wu(Se,{locatorCopyStatus:q}),q==="failed"?"warning":"success")},[e,d,H,K,w,N.hasLiveSnapshot,N.liveMessages,j.providerType,(O=j.targetEntry)==null?void 0:O.controlValues,(Z=j.targetEntry)==null?void 0:Z.providerControls,T,$,W,P,m,h,Y,v,R,C.length,S]);l.useEffect(()=>{const D=de=>{de.key===eu&&L(Ll())};return window.addEventListener("storage",D),()=>window.removeEventListener("storage",D)},[]);const je=l.useCallback(()=>{const D=gy(k.current);k.current=D.state,D.shouldCollect&&oe().catch(de=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",de),ut.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[oe]),ge=l.useMemo(()=>{if(_.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((x.isGenerating||e.status==="streaming")&&J(!1),e.status==="not_monitored"&&A)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(an,{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(br,{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"&&A)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(Yd,{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(br,{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"&&!te)return!$&&P.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,A,i,$,P.length,c,te,_.length,B,x.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.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[s.jsx(Qg,{sessionId:e.sessionId,daemonId:e.daemonId,muted:!!((V=j.targetEntry)!=null&&V.muted),sendDaemonCommand:v}),s.jsx(Jg,{sessionId:e.sessionId,daemonId:e.daemonId,conv:e})]})}),s.jsx(xx,{messages:K,actionLogs:be,agentName:gr(e)||B||"Agent",userName:p,isCliMode:j.isCli||j.isAcp,isWorking:x.isGenerating,contextKey:e.tabKey,receivedAtMap:fe,lastMessageHash:e.lastMessageHash,showActivityMessages:R,onLoadMore:F,isLoadingMore:te,hasMoreHistory:$,hiddenLiveCount:W,loadError:Y??void 0,emptyState:ge,scrollToBottomRequestNonce:u,isVisible:h}),s.jsx(kg,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:j.providerType,displayLabel:j.displayLabel,controls:(he=j.targetEntry)==null?void 0:he.providerControls,controlValues:(le=j.targetEntry)==null?void 0:le.controlValues,currentStatus:e.status,coordinatorHint:Ta(e),isActive:m,isCliTerminal:j.isCliTerminal}),!j.isCliTerminal&&s.jsx(Cu,{contextKey:e.tabKey,panelLabel:B,isSending:a,isBusy:X,statusMessage:re,inlineStatusMessage:G,onSend:r,onForceSend:n,canForceSend:!!n&&x.isGenerating&&!X,isActive:m,showControlsToggle:C.length>0,onControlsToggle:je,messageInput:e.messageInput})]})}let sp=gs;function rp(){return sp()}class g0{constructor(){st(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 np=new g0;class y0{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 vt=new y0;function v0(e){e.dashboardWS&&(np=e.dashboardWS),e.connectionManager&&(vt=e.connectionManager),e.useDaemonsHook&&(sp=e.useDaemonsHook)}const w0=.5,j0=1.25,ss="\x1B",fc={ArrowUp:"A",ArrowDown:"B",ArrowLeft:"D",ArrowRight:"C"};function k0(e){return 1+(e.shift?1:0)+(e.alt?2:0)+(e.ctrl?4:0)}function xc(e,t){let r=e;if(t.shift&&r.length===1&&(r=r.toUpperCase()),t.ctrl){const n=r.toUpperCase().charCodeAt(0);return String.fromCharCode(n&31)}return r}function S0(e,t){if(t in fc){const n=fc[t],a=k0(e);return a===1?`${ss}[${n}`:`${ss}[1;${a}${n}`}switch(t){case"Enter":return e.alt?`${ss}\r`:"\r";case"Escape":return e.alt?`${ss}${ss}`:ss;case"Backspace":{const n=e.ctrl?"\b":"";return e.alt?`${ss}${n}`:n}case"Tab":{const n=e.shift?`${ss}[Z`:" ";return e.alt&&!e.shift?`${ss} `:n}case"Space":{const n=xc(" ",e);return e.alt?`${ss}${n}`:n}}const r=xc(t,e);return e.alt?`${ss}${r}`:r}function xt(e){return Hi(e)}function yr(e){return Bu(e).join(" · ")}function ap(e){var t,r;return!!e.daemonId&&!!((t=e.coordinator)!=null&&t.meshId||typeof((r=e.settings)==null?void 0:r.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.trim().length>0)}function N0(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 C0(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:u,completed:m,failed:h}=e.meshQueueStats;t.push(`Queue: ${p} pending, ${u} assigned, ${m} completed, ${h} failed`)}return t.join(" · ")}function op(e,t){const r=Eu(e,t);return r||(e.title?e.title:yr(e)||"No messages yet")}function ip(e,t){const{isReconnecting:r,isConnecting:n}=Cr(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function I0(e,t){const r=["Chat",...Bu(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function Us(e){return ip(e)||yr(e)}function A0(e,t){return`${xt(e)} · ${op(e,t)}`}function M0(e){const t=aa(e),r=t?$t(t):gr(e);return`${xt(e)} — ${r||"Agent"}`}function T0(e){return gr(e)||"CLI"}function lp(e){return $u(e)}function cp(e){return e?`Remote · ${xt(e)||e.workspaceName||"Session"}`:"Remote"}const bc=[{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:""}})}],_0=[{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 L0(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 Gi({cond:e,path:t,sections:r,onChange:n,onRemove:a,onPreview:o,preview:i}){const c=L0(e),d=i[t],p=u=>{const m=bc.find(h=>h.kind===u);m&&n(m.make(r))};return s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-1.5 space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("select",{value:c,onChange:u=>p(u.target.value),className:"bg-bg-secondary text-text-primary text-[10px] font-mono rounded border border-border-default px-1 py-0.5",children:bc.map(u=>s.jsx("option",{value:u.kind,children:u.label},u.kind))}),(c==="regex"||c==="stable"||c==="changed"||c==="elapsed")&&s.jsx("button",{type:"button",className:"text-[10px] text-accent-primary hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/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-status-online bg-status-online/20":"text-text-secondary bg-bg-glass"}`,children:d.result?"match ✓":"no match"}),d==="loading"&&s.jsx("span",{className:"text-[10px] text-text-muted",children:"testing…"}),a&&s.jsx("button",{type:"button",className:"ml-auto text-text-muted hover:text-status-error 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:u=>n({...e,section:u.target.value||void 0}),className:"bg-bg-secondary text-accent-primary text-[10px] font-mono rounded border border-border-default px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(whole screen)"}),r.map(u=>s.jsx("option",{value:u,children:u},u))]}),s.jsx("input",{value:e.matches??"",onChange:u=>n({...e,matches:u.target.value}),placeholder:"regex",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-primary text-[10px] font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),c==="elapsed"&&s.jsx(Ms,{label:"elapsed_ms",value:e.elapsed_ms,onChange:u=>n({elapsed_ms:u})}),c==="stable"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ms,{label:"stable_ms",value:e.stable_ms,onChange:u=>n({...e,stable_ms:u})}),s.jsx(Ms,{label:"cursor_above",value:e.cursor_above??0,onChange:u=>n({...e,cursor_above:u||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:u=>n({...e,cursor_above:u})}),s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-secondary",children:[s.jsx("input",{type:"checkbox",checked:!!e.changed,onChange:u=>n({...e,changed:u.target.checked}),className:"accent-[var(--accent-primary)]"}),"changed"]})]}),(c==="all"||c==="any")&&s.jsx(R0,{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-border-default",children:s.jsx(Gi,{cond:e.not,path:`${t}.not`,sections:r,onChange:u=>n({not:u}),onPreview:o,preview:i})})]})}function R0({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-border-default space-y-1",children:[c.map((p,u)=>s.jsx(Gi,{cond:p,path:`${r}.${e}[${u}]`,sections:n,onChange:m=>d(c.map((h,g)=>g===u?m:h)),onRemove:()=>d(c.filter((m,h)=>h!==u)),onPreview:o,preview:i},u)),s.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[s.jsx("button",{type:"button",className:"text-[10px] text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>d([...c,{section:n[0],matches:""}]),children:"+ condition"}),_0.map(p=>s.jsxs("button",{type:"button",className:"text-[10px] text-accent-primary/80 hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",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-text-secondary 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-bg-secondary text-text-primary rounded border border-border-default px-1 py-0.5 outline-none focus:border-accent"})]})}function P0({sections:e,otherSectionIds:t,onChange:r,onTest:n,testResult:a}){const o=Object.keys(e),i=a&&a!=="loading"&&!("error"in a)?Object.fromEntries(a.sections.map(m=>[m.id,m])):{},c=(m,h)=>{if(!h||h===m||e[h])return;const g={};for(const[k,f]of Object.entries(e))g[k===m?h:k]=f;r(g)},d=(m,h)=>r({...e,[m]:h}),p=m=>{const h={...e};delete h[m],r(h)},u=()=>{let m="section",h=1;for(;e[m];)m=`section${h++}`;r({...e,[m]:{from_top:0}})};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-text-secondary text-[10px] uppercase tracking-widest font-semibold",children:"Sections"}),s.jsx("span",{className:"text-text-muted text-[10px]",children:"— how the screen is split; conditions match against these"}),s.jsx("button",{type:"button",className:"ml-auto text-[10px] text-accent-primary hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/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-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:u,children:"+ section"})]}),a&&a!=="loading"&&"error"in a&&s.jsx("div",{className:"text-status-error bg-status-error/15 border border-status-error/40 rounded p-1.5 text-[10px] mb-1",children:a.error}),s.jsx("div",{className:"space-y-1.5",children:o.map(m=>{var f;const h=e[m],g=h.anchor!=null?"anchor":"positional",k=v=>{v==="anchor"?d(m,{anchor:h.anchor??"^",anchor_last:h.anchor_last,until:h.until}):d(m,{from_top:h.from_top??0,until:h.until})};return s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{value:m,onChange:v=>c(m,v.target.value.trim()),className:"w-28 bg-bg-secondary text-accent-primary font-mono text-[11px] rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),s.jsxs("div",{className:"inline-flex rounded border border-border-default overflow-hidden text-[10px]",children:[s.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${g==="positional"?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>k("positional"),children:"positional"}),s.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${g==="anchor"?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>k("anchor"),children:"anchor"})]}),s.jsx("button",{type:"button",className:"ml-auto text-text-muted hover:text-status-error text-sm px-1",onClick:()=>p(m),children:"×"})]}),g==="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:v=>d(m,{...h,from_top:v,from_bottom:void 0})}),s.jsx(Ms,{label:"from_bottom",value:typeof h.from_bottom=="number"?h.from_bottom:0,onChange:v=>d(m,{...h,from_bottom:v||void 0})}),s.jsx(gc,{def:h,otherIds:t(m),onChange:v=>d(m,v)})]}):s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-[10px] text-text-muted w-16",children:"anchor"}),s.jsx("input",{value:h.anchor??"",onChange:v=>d(m,{...h,anchor:v.target.value}),placeholder:"^regex locating section start",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-primary text-[10px] font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-secondary",children:[s.jsx("input",{type:"checkbox",checked:!!h.anchor_last,onChange:v=>d(m,{...h,anchor_last:v.target.checked||void 0}),className:"accent-[var(--accent-primary)]"}),"last"]})]}),s.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:s.jsx(gc,{def:h,otherIds:t(m),onChange:v=>d(m,v)})}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-[10px] text-text-muted w-16",children:"ctx next"}),s.jsx("input",{value:((f=h.anchor_context)==null?void 0:f.next)??"",onChange:v=>d(m,{...h,anchor_context:{...h.anchor_context,next:v.target.value||void 0}}),placeholder:"optional: line after anchor must match",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-secondary text-[10px] font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]})]}),i[m]&&s.jsxs("div",{className:"border-t border-border-subtle pt-1",children:[s.jsxs("div",{className:"text-[9px] text-text-muted mb-0.5",children:["captured lines ",i[m].fromLine,"–",i[m].toLine,i[m].text.trim()===""&&s.jsx("span",{className:"text-amber-400 ml-1",children:"(empty — check bounds)"})]}),s.jsx("pre",{className:"font-mono text-[10px] text-text-secondary whitespace-pre-wrap break-all bg-bg-secondary rounded border border-border-subtle px-2 py-1 max-h-28 overflow-y-auto",children:i[m].text||"(empty)"})]})]},m)})})]})}function gc({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-text-secondary",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-bg-secondary text-accent-primary rounded border border-border-default 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-bg-secondary text-text-primary font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]})}function D0({model:e,onChange:t,onPreview:r,preview:n,onTestSections:a,sectionPreview:o}){const i=e.states.map(m=>m.id),c=Object.keys(e.sections??{}),d=l.useCallback(m=>t({...e,...m}),[e,t]),p=(m,h)=>d({states:e.states.map((g,k)=>k===m?{...g,...h}:g)}),u=(m,h)=>d({transitions:e.transitions.map((g,k)=>k===m?{...g,...h}:g)});return s.jsxs("div",{className:"space-y-3",children:[s.jsx(P0,{sections:e.sections??{},otherSectionIds:m=>c.filter(h=>h!==m),onChange:m=>d({sections:m}),onTest:()=>a(e.sections??{}),testResult:o}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-text-secondary text-[10px] uppercase tracking-widest font-semibold",children:"States"}),s.jsx("button",{type:"button",className:"text-[10px] text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>d({states:[...e.states,{id:`state${e.states.length}`,label:"New"}]}),children:"+ state"})]}),s.jsx("div",{className:"space-y-1.5",children:e.states.map((m,h)=>s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary 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-text-muted uppercase tracking-wide",children:"id (used by transitions)"}),s.jsx("input",{value:m.id,onChange:g=>p(h,{id:g.target.value}),placeholder:"idle",className:"w-32 bg-bg-secondary text-accent-primary font-mono text-[11px] rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),s.jsxs("label",{className:"flex flex-col gap-0.5 flex-1",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide",children:"label (shown in dashboard)"}),s.jsx("input",{value:m.label,onChange:g=>p(h,{label:g.target.value}),placeholder:"Ready",className:"w-full bg-bg-secondary text-text-primary text-[11px] rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),s.jsx("button",{type:"button",className:"text-text-muted hover:text-status-error text-sm px-1 pb-0.5",onClick:()=>d({states:e.states.filter((g,k)=>k!==h)}),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-[10px] text-text-secondary flex-wrap",children:[s.jsxs("label",{className:"flex items-center gap-1",children:[s.jsx("input",{type:"radio",name:"initial",checked:!!m.initial,onChange:()=>d({states:e.states.map((g,k)=>({...g,initial:k===h}))}),className:"accent-[var(--accent-primary)]"}),"initial"]}),s.jsxs("label",{className:"flex items-center gap-1",children:[s.jsx("input",{type:"checkbox",checked:!!m.modal,onChange:g=>p(h,{modal:g.target.checked||void 0}),className:"accent-[var(--accent-primary)]"}),"modal"]}),s.jsxs("label",{className:"flex items-center gap-1",children:["status",s.jsxs("select",{value:m.status??"",onChange:g=>p(h,{status:g.target.value||void 0}),className:"bg-bg-secondary text-text-primary rounded border border-border-default 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-text-secondary text-[10px] uppercase tracking-widest font-semibold",children:"Transitions"}),s.jsx("button",{type:"button",className:"text-[10px] text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>d({transitions:[...e.transitions,{from:i[0]??"",to:i[0]??""}]}),children:"+ transition"})]}),s.jsx("div",{className:"space-y-1.5",children:e.transitions.map((m,h)=>s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary 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-text-muted",children:"from"}),s.jsx($0,{value:m.from,states:i,onChange:g=>u(h,{from:g})}),s.jsx("span",{className:"text-[10px] text-text-muted",children:"→"}),s.jsx("select",{value:m.to,onChange:g=>u(h,{to:g.target.value}),className:"bg-bg-secondary text-status-online font-mono text-[10px] rounded border border-border-default px-1 py-0.5",children:i.map(g=>s.jsx("option",{value:g,children:g},g))}),s.jsx("span",{className:"text-[10px] text-text-muted ml-1",children:"label"}),s.jsx("input",{value:m.label??"",onChange:g=>u(h,{label:g.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-bg-secondary text-text-secondary text-[10px] rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),s.jsx("button",{type:"button",className:"text-text-muted hover:text-status-error text-sm px-1",onClick:()=>d({transitions:e.transitions.filter((g,k)=>k!==h)}),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(Ms,{label:"min_hold_ms",value:m.min_hold_ms??0,onChange:g=>u(h,{min_hold_ms:g||void 0})}),s.jsx(Ms,{label:"priority",value:m.priority??0,onChange:g=>u(h,{priority:g||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-text-muted",children:"when"}),!m.when&&s.jsx("button",{type:"button",className:"text-[10px] text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>u(h,{when:{section:c[0],matches:""}}),children:"+ guard condition"}),m.when&&s.jsx("button",{type:"button",className:"text-[10px] text-text-muted hover:text-status-error",onClick:()=>u(h,{when:void 0}),children:"remove guard"})]}),m.when&&s.jsx(Gi,{cond:m.when,path:`t${h}`,sections:c,onChange:g=>u(h,{when:g}),onPreview:r,preview:n})]})]},h))})]})]})}function $0({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-accent-primary bg-accent-primary/20 border-accent":"text-text-muted border-border-default hover:border-border-default"}`,children:i},i))})}function Er(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 yc(e){return e<=0?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}const E0={busy_hold_expired:"text-status-warning bg-status-warning/20 border border-status-warning/40",idle_hold_committed:"text-status-online bg-status-online/20 border border-status-online/40",completion_idle_after:"text-accent-primary bg-accent-primary/20 border border-accent",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-text-secondary bg-bg-glass border border-border-default"},B0={idle:"text-status-online bg-status-online/20 border border-status-online/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-accent-primary bg-accent-primary/20 border border-accent",signing_in:"text-accent-primary bg-accent-primary/20 border border-accent"};function no(e){return B0[e]??"text-text-primary bg-bg-glass border border-border-default"}function In({children:e}){return s.jsx("div",{className:"text-text-secondary text-[10px] uppercase tracking-widest font-semibold mb-1.5 mt-0.5",children:e})}function An(){return s.jsx("div",{className:"border-t border-white/8 my-2"})}function dp({node:e,depth:t=0}){var a;const r=e.result?"text-status-online":"text-text-muted",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-text-secondary",children:e.kind}),s.jsxs("span",{className:"text-text-muted",children:[" ",e.detail]}),e.remainingMs!=null&&e.remainingMs>0&&s.jsxs("span",{className:"text-status-warning",children:[" (",e.remainingMs,"ms left)"]}),(a=e.children)==null?void 0:a.map((o,i)=>s.jsx(dp,{node:o,depth:t+1},i))]})}function F0({t:e}){const[t,r]=l.useState(!1),n=e.fires?"text-status-online bg-status-online/20 border-status-online/40":e.holdSatisfied?"text-text-secondary bg-bg-glass border-border-default":"text-status-warning bg-status-warning/20 border-status-warning/40";return s.jsxs("div",{className:"border border-border-default rounded bg-surface-secondary overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2 py-1 hover:bg-bg-glass-hover text-left",onClick:()=>r(a=>!a),children:[s.jsx("span",{className:"text-[10px] text-text-muted 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-text-secondary 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-status-online text-[10px] font-mono",children:"FIRES"}),!e.holdSatisfied&&s.jsxs("span",{className:"text-status-warning text-[10px] font-mono",children:["hold ",e.holdRemainingMs,"ms"]}),s.jsx("span",{className:`text-[10px] font-mono ${e.condResult?"text-status-online":"text-text-muted"}`,children:e.condResult?"cond✓":"cond✗"})]})]}),t&&e.cond&&s.jsx("div",{className:"px-3 pb-1.5 pt-0.5 bg-bg-secondary border-t border-border-default",children:s.jsx(dp,{node:e.cond})})]})}function O0({activeConv:e,onClose:t}){var oe,je,ge,we,me;const{sendCommand:r}=bt(),[n,a]=l.useState(!0),[o,i]=l.useState(null),[c,d]=l.useState(null),[p,u]=l.useState(!1),[m,h]=l.useState(new Set(["footer"])),[g,k]=l.useState("Snapshot"),[f,v]=l.useState(!1),[w,x]=l.useState(null),[j,C]=l.useState(!1),[y,b]=l.useState(""),[N,S]=l.useState(!1),[I,R]=l.useState("idle"),[L,M]=l.useState(null),[P,$]=l.useState([]),[Y,_]=l.useState({}),[H,W]=l.useState(null),[B,T]=l.useState(!1),A=e.daemonId||((oe=e.routeId)==null?void 0:oe.split(":")[0])||e.routeId||"",E=e.sessionId||"",z=l.useCallback(async()=>{a(!0),d(null);try{const U=await r(A,"get_spec_debug",{targetSessionId:E}),O=U&&typeof U=="object"?U:{},Z=O.result&&typeof O.result=="object"?O.result:O;Z!=null&&Z.success?i(Z):(d((Z==null?void 0:Z.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,A,E]);l.useEffect(()=>{z()},[z]),l.useEffect(()=>{if(!B)return;const U=setInterval(()=>{z()},1e3);return()=>clearInterval(U)},[B,z]),l.useEffect(()=>{const U=O=>{O.key==="Escape"&&!f&&t()};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[t,f]);const G=l.useCallback(async U=>{try{const O=await r(A,"validate_spec",{content:JSON.stringify(U)}),Z=O&&typeof O=="object"?O:{},V=Z.result&&typeof Z.result=="object"?Z.result:Z;$(V!=null&&V.valid?[]:(V==null?void 0:V.errors)??["validation failed"])}catch(O){$([(O==null?void 0:O.message)||String(O)])}},[r,A]),re=l.useCallback(async()=>{M(null),R("idle"),_({});try{const U=await r(A,"get_spec_source",{targetSessionId:E}),O=U&&typeof U=="object"?U:{},Z=O.result&&typeof O.result=="object"?O.result:O;if(!(Z!=null&&Z.success)||typeof Z.content!="string"){M((Z==null?void 0:Z.error)||"Failed to load spec source");return}b(Z.content);let V=null;try{V=JSON.parse(Z.content)}catch{}V&&V.$schema==="adhdev:cli/spec@4"?(x(V),C(!1),G(V)):(x(null),C(!0)),S(!1),v(!0)}catch(U){M((U==null?void 0:U.message)||String(U))}},[r,A,E,G]),X=l.useCallback(U=>{x(U),b(JSON.stringify(U,null,2)),S(!0),R("idle"),G(U)},[G]),te=l.useCallback(async(U,O)=>{_(Z=>({...Z,[U]:"loading"}));try{const Z=await r(A,"eval_condition_preview",{targetSessionId:E,condition:O}),V=Z&&typeof Z=="object"?Z:{},he=V.result&&typeof V.result=="object"?V.result:V;!(he!=null&&he.success)||!he.result?_(le=>({...le,[U]:{result:!1,detail:he==null?void 0:he.error}})):_(le=>({...le,[U]:{result:he.result.result,detail:he.result.detail}}))}catch(Z){_(V=>({...V,[U]:{result:!1,detail:Z==null?void 0:Z.message}}))}},[r,A,E]),J=l.useCallback(async U=>{W("loading");try{const O=await r(A,"resolve_section_preview",{targetSessionId:E,sections:U}),Z=O&&typeof O=="object"?O:{},V=Z.result&&typeof Z.result=="object"?Z.result:Z;!(V!=null&&V.success)||!Array.isArray(V.sections)?W({error:(V==null?void 0:V.error)||"resolve failed"}):W({sections:V.sections,screenLineCount:V.screenLineCount??0})}catch(O){W({error:(O==null?void 0:O.message)||String(O)})}},[r,A,E]),F=l.useCallback(async()=>{var Z,V;const U=(Z=o==null?void 0:o.snapshot)==null?void 0:Z.specPath;if(!U){M("No spec path on this session");return}if(!j&&P.length>0){M("Fix validation errors before saving");return}const O=!j&&w?JSON.stringify(w,null,2):y;R("saving"),M(null);try{const he=await r(A,"write_spec_source",{specPath:U,content:O}),le=he&&typeof he=="object"?he:{},D=le.result&&typeof le.result=="object"?le.result:le;if(!(D!=null&&D.success)){R("error"),M(((V=D==null?void 0:D.validationErrors)==null?void 0:V.join(`
|
|
44
|
+
`))||(D==null?void 0:D.error)||"Save failed");return}R("saved"),S(!1),setTimeout(()=>{z()},400),setTimeout(()=>R("idle"),1500)}catch(he){R("error"),M((he==null?void 0:he.message)||String(he))}},[r,A,(je=o==null?void 0:o.snapshot)==null?void 0:je.specPath,y,w,j,P,z]),K=o==null?void 0:o.snapshot,fe=async()=>{var D,de,Se;let U=o;U||(await z(),U=o);const O=U==null?void 0:U.snapshot,Z=[];if(Z.push("# Spec Debug Snapshot"),Z.push(`Generated: ${new Date().toISOString()}`),Z.push(`Session: ${(U==null?void 0:U.sessionId)??""} (${(U==null?void 0:U.providerType)??""})`),Z.push(`Spec: ${(O==null?void 0:O.spec_id)??""} (${(O==null?void 0:O.specPath)??""})`),Z.push(`Provider: ${(O==null?void 0:O.name)??""} (${(O==null?void 0:O.cliType)??""})`),Z.push(`Working dir: ${(O==null?void 0:O.workingDir)??""}`),Z.push(`Spawned: ${O!=null&&O.spawnedAtMs?new Date(O.spawnedAtMs).toISOString():""}`),Z.push(""),Z.push("## Current State"),Z.push(`State: ${((D=O==null?void 0:O.current_state)==null?void 0:D.id)??"none"} (${((de=O==null?void 0:O.current_state)==null?void 0:de.label)??""})`),Z.push(`Status: ${(O==null?void 0:O.status)??""}`),Z.push(`Idle hold pending: ${(O==null?void 0:O.idleHoldPending)??!1}`),Z.push(`Exited: ${(O==null?void 0:O.exited)??!1}`),Z.push(`Last busy: ${O!=null&&O.lastBusyAt?Er(O.lastBusyAt):""}`),Z.push(`Cursor: ${(O==null?void 0:O.cursorPosition)!=null?`(${O.cursorPosition.row},${O.cursorPosition.col})`:"n/a"}`),(Se=O==null?void 0:O.completionIdleDebounce)!=null&&Se.active){const ue=O.completionIdleDebounce;Z.push(`completion_idle_after: age=${ue.ageMs}ms hold=${ue.holdMs}ms force=${ue.forceAfterMs}ms remaining=${Math.max(0,ue.holdMs-ue.ageMs)}ms`)}if(Z.push(""),Z.push("## Modal"),O!=null&&O.current_modal){const ue=O.current_modal.buttons.map(q=>q.label).join(" / ");Z.push(`${O.current_modal.title??""} [${ue}]`)}else Z.push("none");Z.push(""),Z.push("## State History (last 20)");const V=O!=null&&O.stateHistory?[...O.stateHistory].reverse().slice(0,20):[];for(const ue of V){const q=ue.reason!=null?typeof ue.reason=="string"?ue.reason:JSON.stringify(ue.reason):"",ve=ue.debounceKind!=null?typeof ue.debounceKind=="string"?ue.debounceKind:JSON.stringify(ue.debounceKind):"",Ae=ue.matchedStateId!=null?String(ue.matchedStateId):"",Ne=(ue.matchedRules??[]).map(Ke=>typeof Ke=="string"?Ke:JSON.stringify(Ke)).join(", ");Z.push(`- ${ue.stateId} @ ${new Date(ue.at).toISOString()} held ${ue.durationMs}ms | reason: ${q} | debounce: ${ve} | eval→${Ae} | rules: ${Ne}`)}if(Z.push(""),Z.push("## Sections"),O!=null&&O.sections)for(const[ue,q]of Object.entries(O.sections)){const ve=q.split(`
|
|
45
|
+
`).slice(0,3).join(`
|
|
46
|
+
`);Z.push(`${ue}: ${ve}`)}Z.push(""),Z.push("## Last Assistant Message");const le=[...(O==null?void 0:O.messages)??(O==null?void 0:O.committedMessages)??[]].reverse().find(ue=>ue.role==="assistant");Z.push(le?le.content.slice(0,400):""),Z.push(""),Z.push("## Screen (first 50 lines)"),Z.push(O!=null&&O.screen?O.screen.split(`
|
|
47
|
+
`).slice(0,50).join(`
|
|
48
|
+
`):"");try{await navigator.clipboard.writeText(Z.join(`
|
|
49
|
+
`)),k("Copied!"),setTimeout(()=>k("Snapshot"),1500)}catch(ue){console.error("[SpecDebugPanel] clipboard write failed",ue)}},be=U=>{h(O=>{const Z=new Set(O);return Z.has(U)?Z.delete(U):Z.add(U),Z})};return s.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Spec debug",className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center bg-black/60 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] px-0 sm:items-center sm:p-4",onClick:t,style:{pointerEvents:"auto"},children:s.jsxs("div",{className:"bg-bg-secondary text-text-primary border border-border-default rounded-t-xl sm:rounded-lg shadow-2xl max-w-2xl w-full max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[88vh] flex flex-col",onClick:U=>U.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-border-default 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-text-primary shrink-0",children:"Spec Debug"}),K&&s.jsx("span",{className:"text-[11px] text-text-secondary font-mono bg-surface-secondary px-1.5 py-0.5 rounded truncate",children:K.spec_id})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[(K==null?void 0:K.specPath)&&s.jsx("button",{type:"button",className:`text-[11px] transition-colors px-2 py-1 rounded border ${f?"text-accent-primary bg-accent-primary/20 border-accent":"text-text-secondary hover:text-text-primary hover:bg-bg-glass-hover border-transparent hover:border-border-default"}`,onClick:()=>{f?v(!1):re()},disabled:n,children:f?"Close Editor":"Edit Spec"}),s.jsx("button",{type:"button",className:"text-[11px] text-text-secondary hover:text-text-primary transition-colors px-2 py-1 rounded hover:bg-bg-glass-hover border border-transparent hover:border-border-default",onClick:()=>{fe()},disabled:n,children:g}),s.jsx("button",{type:"button",className:"text-[11px] text-text-secondary hover:text-text-primary transition-colors px-2 py-1 rounded hover:bg-bg-glass-hover border border-transparent hover:border-border-default",onClick:()=>{z()},disabled:n,children:n?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"text-text-secondary hover:text-text-primary transition-colors text-xl leading-none w-7 h-7 flex items-center justify-center rounded hover:bg-bg-glass-hover",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-border-default overflow-hidden text-[10px]",children:[s.jsx("button",{type:"button",className:`px-2 py-0.5 ${j?"text-text-secondary hover:bg-bg-glass-hover":"bg-accent-primary/20 text-accent-primary"}`,onClick:()=>{if(j)try{const U=JSON.parse(y);x(U),G(U)}catch{return}C(!1)},disabled:!w&&j,children:"Form"}),s.jsx("button",{type:"button",className:`px-2 py-0.5 ${j?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>{w&&b(JSON.stringify(w,null,2)),C(!0)},children:"JSON"})]}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate flex-1",title:K==null?void 0:K.specPath,children:((K==null?void 0:K.specPath)??"").split("/").slice(-3).join("/")}),N&&s.jsx("span",{className:"text-status-warning text-[10px]",children:"unsaved"}),!j&&P.length>0&&s.jsxs("span",{className:"text-status-error text-[10px]",children:[P.length," error",P.length>1?"s":""]}),s.jsx("button",{type:"button",className:`text-[11px] px-2.5 py-1 rounded border transition-colors ${I==="saving"||!j&&P.length>0?"text-text-muted border-border-default cursor-not-allowed":"text-status-online bg-status-online/20 border-status-online/40 hover:bg-status-online/20"}`,onClick:()=>{F()},disabled:I==="saving"||!j&&P.length>0,children:I==="saving"?"Saving…":I==="saved"?"Saved ✓ (reloading)":"Save & Apply"})]}),L&&s.jsx("pre",{className:"text-status-error bg-status-error/20 border border-status-error/40 rounded p-2 text-[10px] whitespace-pre-wrap shrink-0 max-h-28 overflow-y-auto",children:L}),!j&&P.length>0&&s.jsx("div",{className:"text-status-error bg-status-error/20 border border-status-error/40 rounded p-1.5 text-[10px] shrink-0 max-h-24 overflow-y-auto space-y-0.5",children:P.map((U,O)=>s.jsx("div",{className:"font-mono",children:U},O))}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:j||!w?s.jsx("textarea",{value:y,onChange:U=>{b(U.target.value),S(!0),R("idle")},spellCheck:!1,className:"w-full h-full min-h-[300px] font-mono text-[11px] leading-relaxed bg-bg-secondary text-text-primary border border-border-default rounded p-3 resize-none outline-none focus:border-accent"}):s.jsx(D0,{model:w,onChange:X,onPreview:te,preview:Y,onTestSections:J,sectionPreview:H})}),s.jsx("div",{className:"text-[10px] text-text-muted shrink-0",children:j?"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 pb-[calc(12px+env(safe-area-inset-bottom,0px))] space-y-3 text-[12px]",children:[c&&s.jsx("div",{className:"text-status-error bg-status-error/20 border border-status-error/40 rounded p-2",children:c}),n&&!o&&s.jsx("div",{className:"text-text-muted text-center py-6",children:"Loading…"}),o&&!o.isSpecProvider&&s.jsxs("div",{className:"text-text-muted text-center py-6",children:["Not a spec-driven provider (",o.providerType||"unknown",")."]}),K&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-[11px] bg-surface-secondary rounded-md px-3 py-2 border border-border-default",children:[K.name&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"Provider"}),s.jsxs("span",{className:"font-mono text-text-primary",children:[K.name," ",s.jsxs("span",{className:"text-text-muted",children:["(",K.cliType,")"]})]})]}),K.workingDir&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"Dir"}),s.jsx("span",{className:"font-mono text-text-secondary truncate",title:K.workingDir,children:K.workingDir})]}),K.spawnedAtMs?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"Spawned"}),s.jsx("span",{className:"text-text-secondary",children:Er(K.spawnedAtMs)})]}):null,K.providerSessionId&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"Session"}),s.jsx("span",{className:"font-mono text-text-muted text-[10px] truncate",title:K.providerSessionId,children:K.providerSessionId})]})]}),s.jsxs("div",{className:"flex items-center gap-2 flex-wrap bg-surface-secondary rounded-md px-3 py-2 border border-border-default",children:[s.jsx("span",{className:`font-semibold font-mono text-[12px] px-2 py-0.5 rounded ${K.current_state?no(K.current_state.id):"text-text-muted"}`,children:K.current_state?K.current_state.id:"none"}),((ge=K.current_state)==null?void 0:ge.label)&&K.current_state.label!==K.current_state.id&&s.jsx("span",{className:"text-text-secondary text-[11px]",children:K.current_state.label}),K.status&&K.status!==((we=K.current_state)==null?void 0:we.id)&&s.jsxs("span",{className:"text-text-muted text-[11px]",children:["engine: ",s.jsx("span",{className:`font-mono ${no(K.status)} px-1 py-0.5 rounded text-[10px]`,children:K.status})]}),K.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"}),K.exited&&s.jsx("span",{className:"text-status-error text-[10px] bg-status-error/20 border border-status-error/40 px-1.5 py-0.5 rounded font-mono",children:"exited"}),K.cursorPosition!=null&&s.jsxs("span",{className:"text-text-muted text-[11px] font-mono",children:["cursor: ",s.jsxs("span",{className:"text-text-secondary",children:[K.cursorPosition.row,",",K.cursorPosition.col]})]}),K.lastBusyAt>0&&s.jsxs("span",{className:"text-text-muted text-[11px] ml-auto",children:["last busy: ",s.jsx("span",{className:"text-text-secondary",children:Er(K.lastBusyAt)})]})]}),((me=K.completionIdleDebounce)==null?void 0:me.active)&&s.jsxs("div",{className:"flex items-center gap-2 text-[11px] bg-accent-primary/20 border border-accent rounded-md px-3 py-1.5 font-mono",children:[s.jsx("span",{className:"text-accent-primary",children:"completion_idle_after"}),s.jsxs("span",{className:"text-text-secondary",children:["age: ",s.jsxs("span",{className:"text-accent-primary",children:[K.completionIdleDebounce.ageMs,"ms"]})]}),s.jsx("span",{className:"text-text-muted",children:"/"}),s.jsxs("span",{className:"text-text-secondary",children:["hold: ",s.jsxs("span",{className:"text-text-secondary",children:[K.completionIdleDebounce.holdMs,"ms"]})]}),s.jsxs("span",{className:"text-text-secondary",children:["force: ",s.jsxs("span",{className:"text-text-secondary",children:[K.completionIdleDebounce.forceAfterMs,"ms"]})]}),s.jsx("span",{className:"text-text-muted ml-auto",children:K.completionIdleDebounce.ageMs<K.completionIdleDebounce.holdMs?s.jsxs("span",{className:"text-status-warning",children:["hold remaining: ",K.completionIdleDebounce.holdMs-K.completionIdleDebounce.ageMs,"ms"]}):K.completionIdleDebounce.ageMs<K.completionIdleDebounce.forceAfterMs?s.jsxs("span",{className:"text-orange-300",children:["force in: ",K.completionIdleDebounce.forceAfterMs-K.completionIdleDebounce.ageMs,"ms"]}):s.jsx("span",{className:"text-status-error",children:"overdue"})})]}),K.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-text-secondary",children:K.current_modal.title||""}),K.current_modal.buttons.length>0&&s.jsxs("span",{className:"text-text-secondary ml-2",children:["[",K.current_modal.buttons.map(U=>U.label).join(" / "),"]"]})]}),K.fsm&&s.jsxs(s.Fragment,{children:[s.jsx(An,{}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsxs(In,{children:["FSM — outgoing from ",s.jsx("span",{className:"text-accent-primary font-mono normal-case",children:K.fsm.currentState})," (held ",yc(K.fsm.stateAgeMs),")"]}),s.jsxs("label",{className:"ml-auto flex items-center gap-1 text-[10px] text-text-muted cursor-pointer select-none mb-1.5",children:[s.jsx("input",{type:"checkbox",checked:B,onChange:U=>T(U.target.checked),className:"accent-[var(--accent-primary)]"}),"live"]})]}),s.jsxs("div",{className:"space-y-1",children:[K.fsm.transitions.length===0&&s.jsx("div",{className:"text-text-muted text-[11px] italic px-1",children:"no outgoing transitions (terminal state)"}),K.fsm.transitions.map((U,O)=>s.jsx(F0,{t:U},O))]})]})]}),s.jsx(An,{}),K.sections&&Object.keys(K.sections).length>0&&s.jsxs("div",{children:[s.jsx(In,{children:"Sections"}),s.jsx("div",{className:"space-y-1",children:Object.entries(K.sections).map(([U,O])=>{var le;const Z=m.has(U),V=O.split(`
|
|
50
|
+
`),he=((le=V[0])==null?void 0:le.slice(0,80))||"(empty)";return s.jsxs("div",{className:"border border-border-default rounded overflow-hidden bg-surface-secondary",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2.5 py-1.5 hover:bg-bg-glass-hover transition-colors text-left",onClick:()=>be(U),children:[s.jsx("span",{className:"text-[10px] text-text-muted w-3",children:Z?"▾":"▸"}),s.jsx("span",{className:"font-mono text-accent-primary w-20 shrink-0 text-[11px]",children:U}),!Z&&s.jsx("span",{className:"text-text-secondary truncate font-mono text-[11px]",children:he}),s.jsxs("span",{className:"ml-auto text-text-muted text-[10px] shrink-0",children:[V.length,"L"]})]}),Z&&s.jsx("pre",{className:"px-3 pb-2.5 pt-1 font-mono text-[11px] text-text-secondary whitespace-pre-wrap break-all bg-bg-secondary max-h-40 overflow-y-auto border-t border-border-default",children:O||"(empty)"})]},U)})})]}),s.jsx(An,{}),K.stateHistory&&K.stateHistory.length>0&&s.jsxs("div",{children:[s.jsxs(In,{children:["State History (",K.stateHistory.length,")"]}),s.jsx("div",{className:"space-y-px",children:[...K.stateHistory].reverse().slice(0,20).map((U,O)=>s.jsxs("div",{className:"rounded px-2 py-1 hover:bg-bg-glass-hover 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 ${no(U.stateId)}`,children:U.stateId}),s.jsx("span",{className:"text-text-secondary text-[11px] shrink-0 tabular-nums",children:Er(U.at)}),U.durationMs>0&&s.jsxs("span",{className:"text-text-muted text-[11px]",children:["held ",s.jsx("span",{className:"text-text-secondary",children:yc(U.durationMs)})]}),U.reason&&s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-mono shrink-0 ${E0[String(U.reason)]??"text-text-secondary bg-bg-glass border border-border-default"}`,children:String(U.reason)}),U.debounceKind&&String(U.debounceKind)!=="none"&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["debounce:",String(U.debounceKind)]}),U.matchedStateId&&String(U.matchedStateId)!==U.stateId&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["eval→",s.jsx("span",{className:"text-text-secondary",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-border-default",children:[U.matchedRules.slice(0,3).map((Z,V)=>s.jsx("span",{className:"font-mono text-[10px] text-accent-primary bg-accent-primary/20 border border-accent px-1.5 py-0.5 rounded break-all",children:typeof Z=="string"?Z:JSON.stringify(Z)},V)),U.matchedRules.length>3&&s.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",U.matchedRules.length-3," more"]})]})]},O))})]}),s.jsx(An,{}),(()=>{const U=K.messages??K.committedMessages??[];if(U.length===0)return null;const O=U.filter(he=>he.role==="user").length,Z=U.filter(he=>he.role==="assistant").length,V=[...U].reverse().find(he=>he.role==="assistant");return s.jsxs("div",{children:[s.jsxs(In,{children:["Transcript (",U.length," — ",O,"u / ",Z,"a)"]}),V&&s.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-md p-2.5 text-[11px]",children:[s.jsxs("div",{className:"text-text-muted mb-1 text-[10px]",children:["Last assistant ",V.receivedAt?Er(V.receivedAt):""]}),s.jsxs("div",{className:"text-text-secondary font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[V.content.slice(0,400),V.content.length>400?"…":""]})]})]})})(),K.specPath&&s.jsx("div",{className:"text-[10px] text-text-muted font-mono truncate border-t border-border-default pt-2 mt-1",title:K.specPath,children:K.specPath}),s.jsxs("div",{children:[s.jsxs("button",{type:"button",className:"text-[11px] text-text-secondary hover:text-text-primary transition-colors flex items-center gap-1.5",onClick:()=>u(U=>!U),children:[s.jsx("span",{className:"text-text-muted",children:p?"▾":"▸"}),s.jsxs("span",{children:["Raw screen (",K.screen?K.screen.split(`
|
|
51
|
+
`).length:0," lines)"]})]}),p&&s.jsx("pre",{className:"mt-1.5 px-3 py-2 font-mono text-[11px] text-text-secondary whitespace-pre bg-bg-secondary rounded-md border border-border-default max-h-64 overflow-auto",children:K.screen||"(empty)"})]})]})]})]})})}function H0({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:i=!0,isInputActive:c=!0}){var Oe;gs();const{sendPtyInput:d}=bt(),[p,u]=l.useState(!1),m=l.useRef(!1);m.current=p;const[h,g]=l.useState("Runtime terminal unavailable"),[k,f]=l.useState(!1),[v,w]=l.useState(null),[x,j]=l.useState(!1),[C,y]=l.useState(!1),[b,N]=l.useState(1),[S,I]=l.useState(!1),[R,L]=l.useState(!1),[M,P]=l.useState(!1),[$,Y]=l.useState(!1),[_,H]=l.useState(!1),[W,B]=l.useState({width:0,height:0}),[T,A]=l.useState({width:0,height:0}),[E,z]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[G,re]=l.useState(null),X=l.useRef(null),te=l.useRef(null),J=l.useRef(!1),F=l.useRef(!1),K=l.useRef(i),fe=l.useRef(0),be=l.useRef(!1),oe=l.useRef(""),je=l.useRef(null),ge=l.useRef(!1),we=l.useRef(!1),me=l.useRef(null),U=l.useRef(null),O=l.useRef(null),Z=32*1024,V=()=>{var ne,ce,ye,Be;return((ce=(ne=X.current)==null?void 0:ne.ownerDocument)==null?void 0:ce.defaultView)||((Be=(ye=te.current)==null?void 0:ye.ownerDocument)==null?void 0:Be.defaultView)||window},he=ne=>{const ce=V();return{ownerWindow:ce,frameId:ce.requestAnimationFrame(ne)}},le=()=>{const ne=me.current;if(ne){try{ne.ownerWindow.cancelAnimationFrame(ne.frameId)}catch{}me.current=null}},D=()=>{const ne=U.current;if(ne){try{ne.ownerWindow.clearTimeout(ne.timeoutId)}catch{}U.current=null}},de=()=>{const ne=O.current;if(ne){try{ne.ownerWindow.clearTimeout(ne.timeoutId)}catch{}O.current=null}},Se=()=>{i&&me.current===null&&(me.current=he(()=>{Ot()}))},ue=e.tabKey,q=e.sessionId||"",ve=e.daemonId||((Oe=e.routeId)==null?void 0:Oe.split(":")[0])||e.routeId||"",Ae=Wi(e),Ne=p?o||Ae:h,Ke=w0,ie=j0,Fe=.05,$e=()=>{const ne=T.width,ce=T.height;if(!Number.isFinite(W.width)||W.width<=0||!Number.isFinite(W.height)||W.height<=0||!Number.isFinite(ne)||ne<=0||!Number.isFinite(ce)||ce<=0)return 1;const ye=W.width/ne,Be=W.height/ce;return Number(Math.min(ie,Math.max(Ke,Math.min(ye,Be))).toFixed(2))},tt=$e(),qe=J.current&&b>tt,ke=Number.isFinite(T.width)&&T.width>0?Math.max(W.width,Math.round(T.width*b)):W.width,ot=Number.isFinite(T.height)&&T.height>0?Math.max(W.height,Math.round(T.height*b)):W.height,Ie=()=>{he(()=>{const ne=te.current;ne&&(ne.scrollLeft=0,ne.scrollTop=ne.scrollHeight-ne.clientHeight)})},it=()=>{var ne,ce;fe.current=0,be.current=!1,oe.current="",je.current=null,ge.current=!1,we.current=!1,J.current||(F.current=!1,N(1)),me.current!==null&&le(),u(!1),g("Runtime terminal unavailable"),de(),D(),w(null),re(null),I(!1),f(!1),j(!1),y(!1),(ce=(ne=r.current)==null?void 0:ne.reset)==null||ce.call(ne)},ct=()=>{var ne,ce;fe.current=0,be.current=!1,oe.current="",je.current=null,ge.current=!1,we.current=!1,me.current!==null&&le(),u(!0),g(""),de(),D(),w(null),re(null),I(!1),f(!1),j(!1),y(!1),(ce=(ne=r.current)==null?void 0:ne.reset)==null||ce.call(ne)},Ze=()=>{we.current&&(we.current=!1,he(()=>{var ne,ce;(ce=(ne=r.current)==null?void 0:ne.scrollToTop)==null||ce.call(ne)}))},Ot=()=>{if(me.current=null,!i)return;const ne=oe.current;if(!ne)return;const ce=ne.slice(0,Z);oe.current=ne.slice(ce.length);const ye=r.current;if(!ye){oe.current=ce+oe.current,Se();return}ye.write(ce,()=>{if(oe.current.length>0){Se();return}Ze()})},Q=ne=>{ne&&(oe.current+=ne,Se())},ee=(ne,ce=0,ye,Be,Ue={})=>{var et,Ye,Ve,Ct;const Qe=!!Ue.force;!Qe&&ce>0&&fe.current>=ce||!Qe&&ce===0&&be.current||(fe.current=ce,ce>0&&j(!0),u(!0),g(""),typeof ye=="number"&&typeof Be=="number"&&ye>0&&Be>0&&((Ye=(et=r.current)==null?void 0:et.resize)==null||Ye.call(et,ye,Be)),oe.current="",(Ct=(Ve=r.current)==null?void 0:Ve.reset)==null||Ct.call(Ve),ne?Q(ne):Ze())};l.useEffect(()=>{it()},[q]),l.useEffect(()=>{var ce;if(!q)return;const ne=((ce=vt.onRuntimeEvent)==null?void 0:ce.call(vt,q,ye=>{if(!(!ye||ye.sessionId!==q)){if(ye.type==="runtime_snapshot"){if(!i){je.current={text:ye.text||"",seq:ye.seq||0,cols:ye.cols,rows:ye.rows,force:!!ye.force};return}ee(ye.text||"",ye.seq||0,ye.cols,ye.rows,{force:!!ye.force});return}if(ye.type==="session_output"){be.current=!0,typeof ye.seq=="number"&&(fe.current=Math.max(fe.current,ye.seq),ye.seq>0&&j(!0)),m.current||u(!0),m.current||g(""),typeof ye.data=="string"&&Q(ye.data);return}if(ye.type==="session_cleared"){if(!i){ge.current=!0,oe.current="",je.current=null;return}ct();return}if(ye.type==="session_io_error"){const Be=typeof ye.error=="string"&&ye.error?ye.error:typeof ye.reason=="string"&&ye.reason?ye.reason:"unknown error";u(!1),g(`Runtime input failed: ${Be}`);return}}},ve))||(()=>{});return()=>{ne()}},[ve,q,r,i]);const ae=async(ne={})=>{var ce;if(!ve||!q)return{success:!1,error:"daemonId and sessionId are required"};ne.preserveStatus||g(ne.loadingMessage||"Loading runtime terminal...");try{const ye=await((ce=vt.requestRuntimeSnapshot)==null?void 0:ce.call(vt,ve,q,{sinceSeq:ne.sinceSeq,force:ne.force}));return ye&&ye.success===!1?(ne.preserveStatus||(u(!1),g(`Runtime terminal unavailable: ${ye.error}`)),ye):ye||{success:!0}}catch(ye){const Be=(ye==null?void 0:ye.message)||String(ye);return ne.preserveStatus||(u(!1),g(`Runtime terminal unavailable: ${Be}`)),{success:!1,error:Be}}},pe=async ne=>{var Qe,et;const ce=((Qe=X.current)==null?void 0:Qe.ownerDocument)||document,ye=ce.defaultView||window,Be=(et=ye.navigator)==null?void 0:et.clipboard;if(Be!=null&&Be.writeText&&ye.isSecureContext)try{return await Be.writeText(ne),!0}catch{}let Ue=null;try{return Ue=ce.createElement("textarea"),Ue.value=ne,Ue.setAttribute("readonly","true"),Ue.style.position="fixed",Ue.style.left="-9999px",Ue.style.top="0",ce.body.appendChild(Ue),Ue.focus(),Ue.select(),ce.execCommand("copy")}catch{return!1}finally{Ue==null||Ue.remove()}},xe=ne=>{D(),re(ne);const ce=V();U.current={ownerWindow:ce,timeoutId:ce.setTimeout(()=>{U.current=null,re(ye=>ye===ne?null:ye)},2200)}},Me=ne=>{de(),w(ne);const ce=V();O.current={ownerWindow:ce,timeoutId:ce.setTimeout(()=>{O.current=null,w(ye=>ye===ne?null:ye)},2200)}},Le=async()=>{var Ue,Qe,et,Ye;const ne=((Qe=(Ue=r.current)==null?void 0:Ue.getSelection)==null?void 0:Qe.call(Ue))||"",ce=((Ye=(et=r.current)==null?void 0:et.getVisibleText)==null?void 0:Ye.call(et))||"",ye=ne.trimEnd()||ce.trimEnd();if(!ye){xe("Nothing to copy");return}if(!await pe(ye)){xe("Copy failed");return}xe(ne.trimEnd()?"Copied selection":"Copied visible terminal")},Ce=ne=>{if(!p||!i)return;((d==null?void 0:d(ve,q,ne))??!1)||xe("Terminal input failed")},Ee=ne=>{Ce(S0({ctrl:R,alt:M,shift:$},ne)),L(!1),P(!1),Y(!1)},Ge=async()=>{if(k)return;f(!0),w("Loading older terminal output..."),we.current=!0;const ne=await ae({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:p});if(f(!1),(ne==null?void 0:ne.success)===!1){we.current=!1,w(`Older terminal output unavailable: ${ne.error}`);return}y(!0),Me("Older terminal output loaded"),he(()=>{var ce;(ce=r.current)==null||ce.bumpResize()})};l.useEffect(()=>{var ce,ye;if(!q)return;ve&&((ce=vt.getState)==null?void 0:ce.call(vt,ve))==="connected"&&ae();const ne=(ye=vt.onStateChange)==null?void 0:ye.call(vt,(Be,Ue)=>{Be!==ve||Ue!=="connected"||ae()});return()=>{ne==null||ne()}},[ve,q,r]),l.useEffect(()=>{t&&it()},[t,ue,r]),l.useEffect(()=>{var Be,Ue;const ne=X.current,ce=(Ue=(Be=ne==null?void 0:ne.ownerDocument)==null?void 0:Be.defaultView)==null?void 0:Ue.ResizeObserver;if(!ne||!ce)return;const ye=new ce(Qe=>{const et=Qe[0];if(!et)return;const{width:Ye,height:Ve}=et.contentRect;B(Ct=>{const us=Math.round(Ye),ts=Math.round(Ve);return Ct.width===us&&Ct.height===ts?Ct:{width:us,height:ts}})});return ye.observe(ne),()=>ye.disconnect()},[]),l.useEffect(()=>{if(J.current)return;const ne=$e();!Number.isFinite(ne)||ne<=0||N(ce=>F.current?ne<ce-Fe?ne:ce:(F.current=!0,ne))},[T.height,T.width,W.height,W.width]),l.useEffect(()=>{qe&&Ie()},[qe,ot,ke]),l.useEffect(()=>{var ye;const ne=K.current;if(K.current=i,!i)return;ne||y(!1),ge.current&&(ge.current=!1,ct());const ce=je.current;ce&&(je.current=null,ee(ce.text,ce.seq,ce.cols,ce.rows,{force:!!ce.force})),ve&&q&&((ye=vt.getState)==null?void 0:ye.call(vt,ve))==="connected"&&ae(),oe.current&&me.current===null&&Se(),he(()=>{var Be;(Be=r.current)==null||Be.bumpResize()})},[ve,i,q]),l.useEffect(()=>()=>{me.current!==null&&le(),D(),de()},[]),l.useEffect(()=>{const ne=Be=>{var Qe;const Ue=Be.detail;Ue!=null&&Ue.sessionId&&Ue.sessionId!==q||p&&((Qe=r.current)==null||Qe.bumpResize())},ce=V(),ye=ce===window?[window]:[window,ce];for(const Be of ye)Be.addEventListener("adhdev:fit-cli-terminal",ne);return()=>{for(const Be of ye)Be.removeEventListener("adhdev:fit-cli-terminal",ne)}},[p,q,r]);const De=p&&x&&!C&&(E.atTop||!E.canScroll)||k||!!v;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:X,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[De&&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:()=>{Ge()},disabled:!q||k,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:k?"Loading older...":"Load older terminal output"}),v&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:v})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[G&&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:G}),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:()=>H(ne=>!ne),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:()=>{Le()},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(ne=>!ne),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-72 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.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",R,L],["Alt",M,P],["Shift",$,Y]].map(([ne,ce,ye])=>s.jsx("button",{type:"button","aria-pressed":ce,className:`h-9 rounded-lg border text-[12px] font-semibold transition-colors ${ce?"border-sky-400/50 bg-sky-400/25 text-white":"border-white/10 bg-white/[0.06] hover:bg-white/[0.12]"}`,onClick:()=>ye(Be=>!Be),children:ne},ne))}),s.jsx("div",{className:"grid grid-cols-6 gap-1",children:"abcdefghijklmnopqrstuvwxyz0123456789".split("").map(ne=>s.jsx("button",{type:"button",className:"h-8 rounded-md border border-white/10 bg-white/[0.06] text-[12px] font-semibold uppercase hover:bg-white/[0.12]",onClick:()=>Ee(ne),children:ne},ne))}),s.jsx("div",{className:"my-2 h-px bg-white/10"}),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:()=>Ee("Escape"),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:()=>Ee("Tab"),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:()=>Ee("Enter"),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:()=>Ee("ArrowUp"),"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:()=>Ee("ArrowLeft"),"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:()=>Ee("ArrowDown"),"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:()=>Ee("ArrowRight"),"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:()=>Ce(""),title:"Send SIGINT (Ctrl-C)",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:()=>Ee("Space"),children:"Space"}),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:()=>Ee("Backspace"),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:()=>{J.current=!0,N(ne=>{const ce=Math.max(tt,Number((ne-.1).toFixed(2)));return ce>tt&&Ie(),ce})},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:()=>{J.current=!0,N(ne=>{const ce=Math.min(ie,Number((ne+.1).toFixed(2)));return ce>tt&&Ie(),ce})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:te,className:qe?"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:ot>0?`${ot}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:T.width>0?`${T.width}px`:"100%",height:T.height>0?`${T.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:b},children:s.jsx(ou,{ref:r,readOnly:!p||!i,sizingMode:"measured",onViewportMetrics:A,onScrollMetrics:z,onInput:ne=>{!p||(d==null||d(ve,q,ne))}})})})}),!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(Cu,{contextKey:e.tabKey,panelLabel:xt(e),isSending:a,isBusy:!!Ae,statusMessage:Ne,inlineStatusMessage:Ne,onSend:async ne=>Ae?!1:n(ne),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),_&&s.jsx(O0,{activeConv:e,onClose:()=>H(!1)})]})}const W0=5e3,K0=12e3;function U0(e){return e==="disconnected"||e==="reconnecting"}function G0({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=W0,reconnectActionDelayMs:o=K0}){const{t:i}=Pt(),c=U0(e),[d,p]=l.useState(()=>!c||a<=0),[u,m]=l.useState(()=>!c||o<=0),h=l.useRef(!1);l.useEffect(()=>{if(!c){p(!1);return}if(h.current=!1,a<=0){h.current=!0,p(!0);return}p(!1);const b=setTimeout(()=>{h.current=!0,p(!0)},a);return()=>clearTimeout(b)},[a,c]),l.useEffect(()=>{if(!c){m(!1);return}if(o<=0){m(!0);return}m(!1);const b=setTimeout(()=>{m(!0)},o);return()=>clearTimeout(b)},[o,c]);const g=c?d:e==="offline"||e==="auth_failed",k=!!(n&&e!=="auth_failed"&&(!c||u)),f=l.useMemo(()=>!t||e!=="connected"?!1:a<=0||h.current,[a,t,e]),v=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))"},x={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)"},j={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},C="fixed left-1/2 top-4 z-[var(--z-toast)] flex items-center justify-center pointer-events-none",y={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[g&&s.jsx("div",{className:C,style:y,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[v],border:x[v],color:j[v]},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"&&i("connection.networkOffline"),e==="disconnected"&&i("connection.reconnecting"),e==="reconnecting"&&i("connection.reconnecting"),e==="auth_failed"&&(r?s.jsxs(s.Fragment,{children:[i("connection.sessionExpired")," ",s.jsx("a",{href:r,className:"text-inherit underline",children:i("connection.logInAgain")})]}):i("connection.connectionFailed"))]}),k&&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:i("connection.reconnectNow")})]})}),f&&s.jsx("div",{className:C,style:y,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"}),i("connection.connected")]})})]})}function up({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(Mi,{size:n}):s.jsx(Zs,{size:n})})}const fs="New session",pp="A connected machine is ready. Start a new session with any installed provider — CLI, ACP, or IDE.";function z0(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 V0(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 q0(e){switch(e){case"conflict":return"border-status-error/40 bg-status-error/10 text-status-error";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-status-online/40 bg-status-online/10 text-status-online"}}function ca({git:e,className:t="",compact:r=!1}){const n=z0(e),a=V0(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 ${q0(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 Y0({wsStatus:e,isConnected:t,daemonCount:r,p2pStates:n={}}){if(e!=="connected")return{tone:"disconnected",titleKey:"connection.disconnected",subtitleKey: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",titleKey:"connection.connectedToDashboard",subtitleKey:"connection.connectingToMachine"}:t?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:null}}function vc({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function wc({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const{t:i}=Pt(),c=Sa(e.updatedAt),d=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${d?"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"?i("notification.actionNeeded"):i("notification.taskComplete"),c].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:[d?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),n()},children:i("notification.markRead")}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),a()},children:i("notification.markUnread")}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),o()},children:i("notification.delete")})]})]})}function J0({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:p,hiddenConversations:u=[],onShowConversation:m,onShowAllHidden:h,onResetPanelsToMain:g,inboxOpen:k,onInboxOpenChange:f,hiddenOpen:v,onHiddenOpenChange:w,onOpenNewSession:x,onOpenDashboardGuide:j,guideNudgeVisible:C=!1,actionShortcuts:y,notifications:b,notificationUnreadCount:N,onOpenNotification:S,onMarkNotificationRead:I,onMarkNotificationUnread:R,onDeleteNotification:L,onOpenGitDialog:M,onOpenMeshGraph:P}){var Z;const{t:$}=Pt(),{ides:Y,p2pStates:_={}}=gs(),H=!!e&&dt(e)&&!lt(e),W=!!e&<(e),B=!!(e!=null&&e.daemonId)&&!!((Z=e==null?void 0:e.coordinator)!=null&&Z.meshId),T=c||(e?Pu(e)?"terminal":"chat":null),[A,E]=l.useState(!1),[z,G]=l.useState(!1),re=l.useRef(null),X=l.useRef(null),te=l.useRef(null),J=Y.filter(V=>V.type==="adhdev-daemon"),F=Y0({wsStatus:t,isConnected:r,daemonCount:J.length,p2pStates:_}),K=$(F.titleKey),fe=F.subtitleKey?$(F.subtitleKey):null,be=F.tone==="connected"?"#22c55e":F.tone==="limited"?"#eab308":"#ef4444",oe=F.tone==="connected"?"0 0 4px #22c55e80":F.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",je=l.useMemo(()=>b.filter(V=>!V.readAt),[b]),ge=l.useMemo(()=>b.filter(V=>!!V.readAt),[b]),we=l.useMemo(()=>je.slice(0,9),[je]),me=N;l.useEffect(()=>{if(!k)return;const V=he=>{var le;(le=X.current)!=null&&le.contains(he.target)||f(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[k,f]),l.useEffect(()=>{if(!v)return;const V=he=>{var le;(le=te.current)!=null&&le.contains(he.target)||w(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[v,w]),l.useEffect(()=>{if(!v&&!k)return;const V=he=>{if(!he.altKey)return;const le=he.code.match(/^Digit([1-9])$/);if(!le)return;const D=Number(le[1])-1,de=v?u[D]:void 0,Se=k?we[D]:void 0;if(!(!de&&!Se)){if(he.preventDefault(),he.stopPropagation(),de){m==null||m(de),w(!1);return}Se&&(S(Se),f(!1))}};return window.addEventListener("keydown",V,!0),()=>window.removeEventListener("keydown",V,!0)},[u,v,k,we,w,f,S,m]),l.useEffect(()=>{const V=u.length;if(re.current===null){re.current=V;return}V>re.current&&G(!0),re.current=V},[u.length]);const U=()=>G(!1),O=V=>{if(!V)return;const he=n.find(le=>le.tabKey===V);he&&(p==null||p(he))};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(Zs,{size:18}),s.jsx("span",{className:"header-title-desktop",children:$("dashboard.header.title")}),s.jsx("span",{className:"header-title-mobile",children:e?xt(e):$("dashboard.header.title")}),s.jsx("span",{title:K,"aria-label":K,className:"header-title-status-dot",style:{background:be,boxShadow:oe}}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:be,boxShadow:oe}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[fe&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",fe]}),x&&s.jsx("button",{type:"button",onClick:x,className:"btn btn-secondary btn-sm ml-2",title:`${fs}${y!=null&&y.openNewSession?` (${y.openNewSession})`:""}`,"aria-label":fs,children:s.jsx(Ti,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[j&&s.jsxs("button",{type:"button",onClick:j,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:$("dashboard.header.guide"),"aria-label":$("dashboard.header.guideOpen"),children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),C&&s.jsx("span",{children:$("dashboard.header.guideShort")})]}),e&&(H||W||!lt(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:yr(e)||xt(e),children:xt(e)}),M&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:$("dashboard.header.openGitStatus"),onClick:()=>M(e.daemonId,e.workspacePath),children:s.jsx(ca,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(ca,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),B&&P&&s.jsxs("button",{type:"button",onClick:()=>P(e),className:"btn btn-secondary btn-sm dashboard-header-mesh-button",title:$("dashboard.header.openMeshGraph"),children:[s.jsx(Zt,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:$("dashboard.header.meshGraph")})]}),(H||W)&&i&&s.jsxs(s.Fragment,{children:[H&&d&&T&&s.jsx(up,{mode:T,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:$(W?"dashboard.header.stopAcpSession":"dashboard.header.stopCliProcess"),style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(Nt,{size:14})})]}),!lt(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:$("dashboard.header.chatHistory"),children:s.jsx(Ii,{size:14})}),!H&&!lt(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:$("dashboard.header.remoteControl"),children:s.jsx(ds,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:X,children:[s.jsxs("div",{className:`dashboard-header-hidden${A?" is-drop-target":""}${z?" hidden-spawn-flash":""}`,onAnimationEnd:U,ref:te,onDragEnter:V=>{V.dataTransfer.types.includes("text/tab-key")&&(V.preventDefault(),E(!0))},onDragOver:V=>{V.dataTransfer.types.includes("text/tab-key")&&(V.preventDefault(),V.dataTransfer.dropEffect="move",E(!0))},onDragLeave:V=>{V.currentTarget.contains(V.relatedTarget)||E(!1)},onDrop:V=>{const he=V.dataTransfer.getData("text/tab-key");V.preventDefault(),E(!1),O(he)},children:[s.jsxs("button",{type:"button",onClick:()=>w(!v),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`${$("dashboard.hidden.title")}${y!=null&&y.toggleHiddenTabs?` (${y.toggleHiddenTabs})`:""}. ${$("dashboard.hidden.dragHint")}`,children:[s.jsx(Ai,{size:16}),u.length>0&&s.jsx("span",{className:`dashboard-header-hidden-badge${z?" hidden-badge-pop":""}`,children:u.length})]}),v&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:$("dashboard.hidden.title")}),s.jsx(vc,{value:y==null?void 0:y.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[g&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:g,children:$("dashboard.hidden.resetPanels")}),u.length>0&&h&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{h(),w(!1)},children:$("dashboard.hidden.restoreAll")})]})]}),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:$("dashboard.hidden.hideCurrentTab")}),s.jsx(vc,{value:y==null?void 0:y.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:xt(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(V=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{m==null||m(V),w(!1)},children:[s.jsxs("span",{className:"dashboard-header-inbox-item-title",children:[V.status==="generating"&&s.jsx("span",{className:"tab-spinner dashboard-header-inbox-item-spinner","aria-label":$("dashboard.header.generating")}),xt(V)]}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(V)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(V)+1]}):null,yr(V)]})]},V.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:$("dashboard.hidden.empty")})]})]}),s.jsxs("button",{type:"button",onClick:()=>f(!k),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:$("dashboard.header.activityInbox"),children:[s.jsx(Nr,{size:16}),me>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:me})]}),k&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[je.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:$("dashboard.inbox.unread")}),je.map(V=>s.jsx(wc,{notification:V,shortcutIndex:we.indexOf(V)>=0?we.indexOf(V)+1:void 0,onOpen:()=>S(V),onMarkRead:()=>I(V.id),onMarkUnread:()=>R(V.id),onDelete:()=>L(V.id)},V.id))]}),ge.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:$("dashboard.inbox.read")}),ge.map(V=>s.jsx(wc,{notification:V,onOpen:()=>S(V),onMarkRead:()=>I(V.id),onMarkUnread:()=>R(V.id),onDelete:()=>L(V.id)},V.id))]}),b.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:$("dashboard.inbox.empty")})]})]})]})]})}function Bt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function X0(e,t){return String(e||"")!==String(t||"")}function Q0(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(`
|
|
52
|
+
`).includes(r)||n&&!String(i.workspace||"").toLowerCase().includes(n)||a&&!vu(i.summaryMetadata).map(d=>d.toLowerCase()).join(`
|
|
53
|
+
`).includes(a)))}function Z0(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 mp(e,t={}){return Z0(Q0(e,t),t.sortMode||"recent")}function ai(e){return e?"Resume saved history":"Start fresh"}function hp(e){return e?"Resuming saved history…":"Starting fresh…"}function ev(){return"Start fresh"}function tv(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function sv(){return"Open saved history"}function rv(){return"Saved History"}function zi(){return"Use saved history when you want continuity in the same provider conversation."}function nv(){return"No saved history found yet."}function av(){return"Refresh saved history"}function ov(){return"Refreshing saved history…"}function da(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function ua(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 pa(e){return e==="start-fresh"?"Start fresh":"Restart"}function ma(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function fp(e){return`Resume saved history with ${e}?`}function xp(){return"Review or change the target workspace before resuming saved history."}function iv(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 bp({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:p,onClose:u,onNewChat:m,onSwitchSession:h,onRefreshHistory:g,onResumeSavedSession:k}){var L;const f=t.find(M=>M.id===e.routeId),v=(f==null?void 0:f.chats)||[],w=(L=f==null?void 0:f.activeChat)==null?void 0:L.id,x=dt(e)&&!lt(e),[j,C]=l.useState(()=>Bt()),y=c||j,b=String(d||"").trim(),N=M=>{if(p){p(M);return}C(M)},S=l.useMemo(()=>a.map(M=>{const P=String(M.workspace||"").trim();return M.canResume||P||!b?M:{...M,workspace:b,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[b,a]),I=l.useMemo(()=>mp(S,{textQuery:y.textQuery,workspaceQuery:y.workspaceQuery,modelQuery:y.modelQuery,resumableOnly:y.resumableOnly,sortMode:y.sortMode}),[S,y.modelQuery,y.resumableOnly,y.sortMode,y.textQuery,y.workspaceQuery]),R=s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:x?rv():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:M0(e)}),x&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:zi()})]}),s.jsx("button",{onClick:u,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(Nt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!x&&s.jsx("button",{onClick:m,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),x?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:y.textQuery,onChange:M=>N({...y,textQuery:M.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:y.workspaceQuery,onChange:M=>N({...y,workspaceQuery:M.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:y.modelQuery,onChange:M=>N({...y,modelQuery:M.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:y.sortMode,onChange:M=>N({...y,sortMode:M.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:y.resumableOnly,onChange:M=>N({...y,resumableOnly:M.target.checked})}),"Resume-ready only"]})]}),I.map(M=>{const P=e.providerSessionId===M.providerSessionId,$=P||!M.canResume||!!i,Y=M.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{$||!k||k(M)},disabled:$,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${P?"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 ${P?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:M.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:M.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:iv(M.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:M.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:[M.workspace||"Workspace unknown",Y?" · selected workspace":"",Js(M.summaryMetadata)?` · ${Js(M.summaryMetadata)}`:"",M.messageCount>0?` · ${M.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:P?"ACTIVE":M.canResume?Y?"RESUME IN SELECTED WORKSPACE":i===M.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},M.id)})]}):v.map(M=>s.jsxs("div",{onClick:()=>{h(e.routeId,M.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${w===M.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 ${w===M.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:M.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:[M.id.substring(0,12),"..."]}),w===M.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},M.id)),(x&&!o&&I.length===0||!x&&v.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Hf,{size:32})}),s.jsx("div",{className:"text-[13px]",children:x?a.length>0?"No saved history matches these filters.":nv():"No recent chat sessions found."})]}),x&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:ov()})})]}),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:g,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(ka,{size:13})," ",x?av():"Refresh History"]})})})]})]});return typeof document>"u"?R:hr.createPortal(R,document.body)}const jc={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.success"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.warning"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.info"}};function gp({toasts:e,onDismiss:t,onClickToast:r}){const{t:n}=Pt();return s.jsx("div",{className:"fixed right-4 z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(a=>{const o=jc[a.type]||jc.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 i;(i=a.actions)!=null&&i.length||r&&r(a)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${o.accent}, color-mix(in srgb, ${o.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:i=>{i.stopPropagation(),t(a.id)},"aria-label":n("toast.dismiss"),children:s.jsx(Nt,{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:o.chipBg,color:o.chipText,border:`1px solid color-mix(in srgb, ${o.accent} 22%, transparent)`},children:n(o.labelKey)})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:a.message}),a.actions&&a.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:a.actions.map((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.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)"}:i.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:d=>{d.stopPropagation(),i.onClick(),t(a.id)},children:i.label},c))})]})]},a.id)})})}const lv=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function cv(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function dv(e,t){return yp(e)||t}function yp(e){var a,o,i;const t=(o=(a=e.summaryMetadata)==null?void 0:a.items)==null?void 0:o.find(c=>(c==null?void 0:c.id)==="model"),r=((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim();if(r)return r;const n=(i=e.controlValues)==null?void 0:i.model;return typeof n=="string"&&n.trim()?n.trim():""}function uv(e){return yp(e)||void 0}function pv(e){return e.sessionId||e.instanceId||e.agentType}function vp(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=es(r,{fallbackId:r.id}));return t}function wp(e,t={}){var n;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:Lb(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[r]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Vi(e,t={}){return mv(e,wp(e,t))}function mv(e,t={}){var h,g,k,f,v,w,x,j,C;const r=[],n=t.machineName,a=t.connectionState,o=cv(e),i=e.workspace||"",c=Bb(e.type,{agentName:e.cliName}),d=dt(e)||lt(e)?c:$t(e.type),p=dv(e,d),u=Array.isArray(e.childSessions)?e.childSessions.map(y=>{var b,N,S;return{sessionId:y.id,instanceId:y.id,providerSessionId:y.providerSessionId,activeChatId:(b=y.activeChat)==null?void 0:b.id,transport:y.transport,sessionCapabilities:y.capabilities,agentType:y.providerType,agentName:y.providerName||$t(y.providerType),model:uv(y),status:y.status,title:y.title,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,messages:((N=y.activeChat)==null?void 0:N.messages)||[],activeModal:((S=y.activeChat)==null?void 0:S.activeModal)||void 0,unread:y.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,surfaceHidden:y.surfaceHidden,muted:y.muted,git:y.git,settings:y.settings,coordinator:y.coordinator,messageInput:y.messageInput}}):[],m=lv(e);if(m){const y=e.sessionId||e.instanceId,b=(h=e.settings)==null?void 0:h.meshCoordinatorFor,N=((g=e.settings)==null?void 0:g.meshNodeFor)||!((k=e.settings)!=null&&k.meshCoordinatorFor)&&((f=e.settings)==null?void 0:f.launchedByCoordinator),S=b?" (Coordinator)":N?" (Mesh Node)":"",I=c+S,R=(v=e.activeChat)==null?void 0:v.activeModal,L=R&&Array.isArray(R.buttons)&&R.buttons.length>0,M=Fb(e.activeChat,[{status:e.status,activeModal:(w=e.activeChat)==null?void 0:w.activeModal}],e.agents||[]),P=e.activeChat||{title:"",messages:[]};let $=P.title&&String(P.title).trim()?String(P.title).trim():"";const Y=(x=e.activeChat)==null?void 0:x.id,_=e.chats;if(Y&&Array.isArray(_)&&_.length>0){const G=_.find(re=>re.id===Y||re.id&&String(re.id)===String(Y));G!=null&&G.title&&String(G.title).trim()&&($=String(G.title).trim())}const H=(dt(e)||lt(e),e.type),W=(dt(e)||lt(e))&&zl($,I,H)?"":$,B=P.messages||[],T=typeof Y=="string"?Y.trim():"",A=(dt(e)||lt(e))&&T===String(e.type||"").trim(),E=T&&!A?T:e.providerSessionId,z=e.coordinator||(typeof((j=e.settings)==null?void 0:j.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);r.push({routeId:e.id,sessionId:y,providerSessionId:e.providerSessionId,historySessionId:E,nativeSessionId:y,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:dt(e)&&e.mode||"chat",agentName:I,agentType:H,status:M,title:W,messages:B,resume:e.resume,hostIdeType:!dt(e)&&!lt(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||W||(dt(e)?e.mode==="chat"?I:`Terminal${S}`:I),displaySecondary:p,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:L?R.buttons:void 0,modalMessage:L?R.message:void 0,streamSource:"native",tabKey:Ja(y,e.id),machineName:n,connectionState:a,settings:e.settings,coordinator:z,messageInput:e.messageInput})}if(m&&(dt(e)||lt(e)))return r;for(const y of u){const b=y.activeModal&&Array.isArray(y.activeModal.buttons)&&y.activeModal.buttons.length>0,N=Ob(y),S=pv(y),I=`${e.id}:${S}`,R=y.title&&String(y.title).trim()||"",L=zl(R,y.agentName,y.agentType)?"":R,M=y.messages||[];if(!(y.transport==="cdp-webview"||!!y.sessionId||!!y.providerSessionId||M.length>0||b||!!L||!["idle","panel_hidden","disconnected","not_monitored"].includes(N)))continue;const $=y.coordinator||(typeof((C=y.settings)==null?void 0:C.meshCoordinatorFor)=="string"&&y.settings.meshCoordinatorFor?{meshId:y.settings.meshCoordinatorFor,role:"coordinator"}:void 0);r.push({routeId:e.id,sessionId:y.sessionId||y.instanceId,providerSessionId:y.providerSessionId,historySessionId:y.activeChatId||y.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:y.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:y.sessionCapabilities,mode:"chat",agentName:y.agentName,agentType:y.agentType,status:N,title:L,messages:M,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:y.git||e.git,displayPrimary:o||L||y.agentName||d,displaySecondary:y.model&&y.model.trim()?y.model.trim():`${d} · ${y.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,lastUpdated:y.lastUpdated||e.lastUpdated,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,modalButtons:b?y.activeModal.buttons:void 0,modalMessage:b?y.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Ja(y.sessionId||y.instanceId,I),machineName:n,connectionState:a,settings:y.settings,coordinator:$,messageInput:y.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:p,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Ja(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),r}function jp(e){return String(e.type||e.id||"").trim()}function ha(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function hv(e,t){const r=(t||"").trim();if(!r)return[];const n=(e||[]).find(a=>a.type===r);return ha(n==null?void 0:n.modelOptions)}function fv(e,t){const r=(t||"").trim();if(!r)return[];const n=(e||[]).find(a=>a.type===r);return ha(n==null?void 0:n.thinkingLevelOptions)}function kp(e){const t=new Map;for(const r of e||[])r!=null&&r.type&&t.set(r.type,{models:ha(r.modelOptions),thinking:ha(r.thinkingLevelOptions)});return t}function xv(e){var t;return e.category!=="cli"||!jp(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 vr(e){var n;const t=new Set,r=[];for(const a of e||[]){if(!xv(a))continue;const o=jp(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,...Array.isArray(a.modelOptions)&&a.modelOptions.length?{modelOptions:a.modelOptions}:{},...Array.isArray(a.thinkingLevelOptions)&&a.thinkingLevelOptions.length?{thinkingLevelOptions:a.thinkingLevelOptions}:{}})}return r}function wr(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],r=new Set,n=[];for(const a of t){const o=typeof a=="string"?a.trim():"";!o||r.has(o)||(r.add(o),n.push(o))}return n}function cn(e){return e.map(t=>t.type)}function bv(e,t){const r=wr(e),n=t.trim();return!n||r.includes(n)?r:[...r,n]}function gv(e,t){return wr(e).filter(r=>r!==t)}function kc(e,t,r){const n=wr(e),a=n.indexOf(t);if(a<0)return n;const o=n.filter(c=>c!==t);if(r==="top")return[t,...o];if(r==="bottom")return[...o,t];const i=r==="up"?Math.max(0,a-1):Math.min(o.length,a+1);return o.splice(i,0,t),o}function 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 yv({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(()=>wr(e),[e]),p=d.filter(h=>!c.has(h)).length,u=t.filter(h=>!d.includes(h.type)),m=()=>{o&&(r(bv(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,g)=>{const k=c.get(h),f=!!k;return s.jsxs("div",{className:`flex flex-col gap-2 rounded-md border border-border-subtle px-3 py-2 sm:flex-row sm:items-center sm:justify-between ${f?"bg-bg-primary":"bg-bg-primary/40"}`,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:["#",g+1]}),(k==null?void 0:k.icon)&&s.jsx("span",{"aria-hidden":"true",children:k.icon}),s.jsx("span",{className:`font-mono text-[12px] ${f?"text-text-primary":"text-text-muted"}`,children:h}),f?s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:"available"}):s.jsx("span",{className:"rounded border border-amber-500/25 bg-amber-500/10 px-1.5 py-px text-[9px] font-semibold text-amber-400",children:"not on this machine"})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:k?`${k.label} · ${k.statusLabel}`:"Kept in order; skipped at launch until detected here."})]}),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||g===0,title:"Move up",onClick:()=>r(kc(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||g===d.length-1,title:"Move down",onClick:()=>r(kc(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(gv(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||u.length===0,children:[s.jsx("option",{value:"",children:u.length?"Select provider…":"No additional detected CLI providers"}),u.map(h=>s.jsxs("option",{value:h.type,children:[h.label," (",h.type,")"]},h.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:n||!o,onClick:m,children:"Add provider"}),a]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Launches use this order, top to bottom.",p>0?` ${p} provider${p===1?"":"s"} not detected here — kept in order, skipped until available.`:""]})]})}function vv(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 Sp(e,t){const r=vv(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Np=[{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:"🏄"}],Cp=[{id:"antigravity-cli",name:"Antigravity CLI",icon:"🪐"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"hermes-cli",name:"Hermes",icon:"⚕️"},{id:"kimi",name:"Kimi",icon:"🌙"},{id:"opencode",name:"OpenCode CLI",icon:"◆"}],Ip=[{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:"🟠"}],wv=Np,jv=Cp,kv=Ip;function Sv({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:Ft("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 bn({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(Sv,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Ft("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const oi="adhdev:themechange";function Nv(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function ir(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function lr(e){return e==="system"?Nv():e}function Ap(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function zn(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(oi,{detail:{preference:e,theme:t}}))}function Cv(){const e=ir(),t=lr(e);Ap(t),zn(e,t)}function Ps(){const[e,t]=l.useState(ir),[r,n]=l.useState(()=>lr(ir()));l.useEffect(()=>{Ap(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),zn("system",p)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=d=>{const p=d.detail||{},u=p.preference,m=p.theme;t(u==="dark"||u==="light"||u==="system"?u:ir()),n(m==="dark"||m==="light"?m:lr(ir()))},c=d=>{if(d.key!=="theme")return;const p=ir(),u=lr(p);t(p),n(u)};return window.addEventListener(oi,i),window.addEventListener("storage",c),()=>{window.removeEventListener(oi,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{const c=lr(i);t(i),n(c);try{localStorage.setItem("theme",i)}catch{}zn(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",d=lr(c);n(d);try{localStorage.setItem("theme",c)}catch{}return zn(c,d),c})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const Nc={dark:"Dark",light:"Light",system:"System"};function Iv({collapsed:e}){const{preference:t,cycleTheme:r}=Ps(),n=t==="dark"?s.jsx(Kf,{size:16}):t==="light"?s.jsx(Wf,{size:16}):s.jsx(Uf,{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]})]})}const ii="adhdev:langchange";function Av(){const e=yt.language;return dr(e)?e:hu()}function Mv(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(ii,{detail:{language:e}}))}function Tv(){const[e,t]=l.useState(Av);l.useEffect(()=>{const n=i=>{dr(i)&&t(i)},a=i=>{const c=i.detail||{};dr(c.language)&&t(c.language)},o=i=>{if(i.key!==zo)return;const c=i.newValue;dr(c)&&c!==yt.language&&(yt.changeLanguage(c),Vo(c))};return yt.on("languageChanged",n),window.addEventListener(ii,a),window.addEventListener("storage",o),()=>{yt.off("languageChanged",n),window.removeEventListener(ii,a),window.removeEventListener("storage",o)}},[]);const r=l.useCallback(n=>{if(dr(n)){t(n);try{localStorage.setItem(zo,n)}catch{}yt.changeLanguage(n),Vo(n),Mv(n)}},[]);return{language:e,setLanguage:r}}function _v({collapsed:e}){const{language:t,setLanguage:r}=Tv(),{t:n}=Pt("common"),a=qa.find(i=>i.code===t)??qa[0],o=n("language.select",{defaultValue:"Select language"});return s.jsxs("div",{className:`nav-item relative cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,title:`${n("language.label",{defaultValue:"Language"})}: ${a.label}`,children:[s.jsx("span",{className:"nav-icon",children:s.jsx(Zf,{size:16})}),!e&&s.jsx("span",{className:"text-xs",children:a.label}),s.jsx("select",{"aria-label":o,value:t,onChange:i=>r(i.target.value),className:"absolute inset-0 w-full h-full opacity-0 cursor-pointer",children:qa.map(i=>s.jsx("option",{value:i.code,children:i.label},i.code))})]})}function ao(e,t){return e?typeof e=="function"?e(t):e:null}function Lv({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const[p,u]=l.useState(!1),[m,h]=l.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),g=()=>u(!0),k=()=>u(!1),f=()=>{h(j=>{const C=!j;try{localStorage.setItem(d,C?"1":"0")}catch{}return C})},v=l.useMemo(()=>({collapsed:m,mobileMenuOpen:p,openMobileMenu:g,closeMobileMenu:k,toggleCollapsed:f}),[m,p]),w=j=>`nav-item${j.active?" active":""} cursor-pointer ${m?"justify-center py-2.5 px-0":""}${j.className?` ${j.className}`:""}`,x=j=>s.jsxs("div",{className:w(j),id:`nav-${j.id}`,onClick:()=>{j.onSelect(),k()},title:m?j.title??(typeof j.label=="string"?j.label:void 0):j.title,children:[s.jsx("span",{className:"nav-icon",children:j.icon}),!m&&j.label]},j.id);return s.jsxs("div",{className:`app-layout${p?" mobile-menu-open":""}${m?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:g,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:k,onKeyDown:j=>j.key==="Escape"&&k()}),s.jsxs("aside",{className:`sidebar ${p?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${m?"justify-center gap-0":""}`,children:ao(t,v)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:k,children:s.jsx(Nt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(x)}),n.map(j=>s.jsxs("div",{className:j.className??"border-t border-border-subtle pt-2 mt-2",children:[!m&&j.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:j.title}):null,j.items.map(x)]},j.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(x),ao(o,v),s.jsx(Iv,{collapsed:m}),s.jsx(_v,{collapsed:m}),ao(i,v)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function ht({title:e,icon:t,description:r,accentColor:n,className:a,collapsible:o,defaultOpen:i=!0,badge:c,children:d}){const[p,u]=l.useState(i),m=o?p:!0,h=(e||r)&&s.jsxs("div",{className:Ft("flex items-start justify-between gap-3",m&&"mb-4"),children:[s.jsxs("div",{className:"min-w-0",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary flex items-center gap-1.5",children:[t&&s.jsx("span",{children:t}),s.jsx("span",{children:e}),c]}),r&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),o&&s.jsx("span",{className:Ft("mt-0.5 shrink-0 text-text-muted transition-transform select-none",m?"rotate-90":"rotate-0"),"aria-hidden":!0,children:"▸"})]});return s.jsxs("div",{className:Ft("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:()=>u(g=>!g),"aria-expanded":m,children:h}):h,m&&d]})}function Ra({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:Ft("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 Rv={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"},Pv={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Kt({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:Ft("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Rv[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Pv[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:Ft("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 os(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:Ft("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 Dv={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},ks=l.forwardRef(function({variant:t="secondary",size:r="md",type:n,className:a,...o},i){return s.jsx("button",{ref:i,type:n??"button",className:Ft("btn",Dv[t],r==="sm"&&"btn-sm",a),...o})}),$v=l.forwardRef(function({options:t,children:r,className:n,...a},o){return s.jsx("select",{ref:o,className:Ft("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none cursor-pointer","focus:border-accent transition-colors",n),...a,children:r??(t==null?void 0:t.map(i=>s.jsx("option",{value:i.value,disabled:i.disabled,children:i.label},i.value)))})}),Ev={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"},Bv={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Fv({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:Ft("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Ev[e],r),children:[s.jsx("span",{className:Ft("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Bv[e])}),n]})}function Fs({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 Ov({onPrefChange:e}){const[t,r]=Jb(),[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(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Nr,{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(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ds,{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-status-warning",children:[s.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),s.jsx("button",{onClick:()=>{ku().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-status-warning",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-status-warning",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(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Zd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:i=>o("completionAlert",i)}),s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Gf,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:i=>o("approvalAlert",i)}),s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(an,{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 li(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);if(!t)return null;const r=t[4]??null;let n=null;if(r){const a=r.match(/(?:^|\.)(\d+)$/);n=a?Number(a[1]):null}return{base:[Number(t[1]),Number(t[2]),Number(t[3])],prereleaseNumber:n,isPrerelease:r!==null}}function fa(e){var t;return((t=li(e))==null?void 0:t.base)??null}function Hv(e,t){const r=fa(e),n=fa(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 Wv(e,t){const r=li(e),n=li(t);if(!r||!n)return e!==t;for(let a=0;a<3;a+=1){if(r.base[a]<n.base[a])return!0;if(r.base[a]>n.base[a])return!1}return r.isPrerelease&&n.isPrerelease?r.prereleaseNumber===null||n.prereleaseNumber===null?!1:r.prereleaseNumber<n.prereleaseNumber:!1}function qi(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:Wv(r,t)}function en(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||Hv(r,t)>=0)return!1;const n=fa(r),a=fa(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Kv(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function oo(e,t){return e instanceof Error?e.message:t}function Uv({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(Ra,{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(zv,{ide:i,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},i.id))})}function Cc({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:o}){const i=n==="red"?"bg-status-error/20 text-status-error border-status-error/40 hover:bg-status-error/30":"";return hr.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:"var(--z-modal)"},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 Gv(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...wv,...jv,...kv].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 zv({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var $,Y;const[o,i]=l.useState("idle"),[c,d]=l.useState(""),[p,u]=l.useState(null),[m,h]=l.useState("idle"),[g,k]=l.useState(""),f=e.version||null,v=(($=e.machine)==null?void 0:$.platform)||((Y=e.system)==null?void 0:Y.platform)||"",w=es(e,{fallbackId:e.id}),x=v==="win32"?"🪟":v==="darwin"?"🍎":"🐧",j=t.filter(_=>_.daemonId===e.id&&_.transport==="cdp-page"),C=t.filter(_=>_.daemonId===e.id&&_.transport==="pty"),y=t.filter(_=>_.daemonId===e.id&&_.transport==="acp"),b=e.p2p,N=async()=>{if(r){i("upgrading"),d("Starting upgrade...");try{const _=Kv(await r(e.id,"daemon_upgrade",{}));_.alreadyLatest?(i("done"),d(`Already on v${_.version||"latest"}.`)):_.upgraded||_.success?(i("done"),d(`Upgrade to v${_.version||"latest"} started. Daemon is restarting...`)):(i("error"),d(_.error||"Upgrade failed"))}catch(_){i("error"),d(oo(_,"Connection lost during upgrade"))}}},S=async()=>{if(u(null),!!n){h("loading");try{await n(e.id),h("done"),k("Machine disconnected.")}catch(_){h("error"),k(oo(_,"Failed to disconnect"))}}},I=async()=>{if(u(null),!!a){h("loading");try{await a(e.id),h("done"),k("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(_){h("error"),k(oo(_,"Failed to revoke token"))}}},R="0.9.82",L=qi(e,R),M=en(e,R),P=j.length+C.length+y.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:x}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:w}),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:N,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${R}`,children:o==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${M?"↑ Update now":`↑ Update${` to v${R}`}`}`}),n&&s.jsx("button",{onClick:()=>u("disconnect"),disabled:m==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>u("revoke"),disabled:m==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(Fv,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[b&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${b.state==="connected"?"bg-status-online":"bg-text-muted/30"} ${b.state==="connecting"||b.state==="new"?"animate-pulse":""}`,style:b.state==="connecting"||b.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",b.state==="connected"?"connected":b.state==="connecting"||b.state==="new"?"connecting...":b.state||"off"]}),b.peers!==void 0&&b.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",b.peers," peer",b.peers!==1?"s":"",")"]})]}),b&&P>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),P>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[j.map(_=>{const H=Gv(_.type),W=_.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:H.icon}),s.jsx("span",{children:H.name}),W!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${W?"bg-status-online":"animate-pulse"}`,style:W?void 0:{background:"var(--status-warning)"},title:W?"CDP connected":"CDP connecting..."})]},_.id)}),C.map(_=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:_.cliName||"CLI"})]},_.id)),y.map(_=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:_.cliName||"ACP"})]},_.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(c||g)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||m==="error"?"text-status-error":o==="done"||m==="done"?"text-status-online":"text-text-muted"}`,children:g||c})]}),p==="disconnect"&&s.jsx(Cc,{title:"🔌 Disconnect Machine",message:`Disconnect "${w}" from ADHDev?
|
|
54
|
+
|
|
55
|
+
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
56
|
+
|
|
57
|
+
Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:S,onCancel:()=>u(null)}),p==="revoke"&&s.jsx(Cc,{title:"⚠️ Remove Machine",message:`Remove "${w}" from your dashboard?
|
|
58
|
+
|
|
59
|
+
This will:
|
|
60
|
+
• Immediately disconnect the machine
|
|
61
|
+
• Delete the machine registration
|
|
62
|
+
• Require restarting ADHDev on that machine
|
|
63
|
+
|
|
64
|
+
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:I,onCancel:()=>u(null)})]})}const Vv=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function qv({daemonId:e,knownCliTypes:t=Vv}){const{sendCommand:r}=bt(),[n,a]=l.useState({}),[o,i]=l.useState({}),[c,d]=l.useState(!0),[p,u]=l.useState(null),[m,h]=l.useState(null),[g,k]=l.useState(""),f=l.useCallback(async()=>{if(e){d(!0),h(null);try{const x=await r(e,"list_coordinator_prompts",{}),j=x!=null&&x.result&&typeof x.result=="object"?x.result:x;if(!(j!=null&&j.success)){h((j==null?void 0:j.error)||"Failed to load");return}const C=j.entries||{};k(j.dir||"");const y={};for(const b of t)y[b]=C[b]||{override:"",append:""};for(const b of Object.keys(C))y[b]||(y[b]=C[b]);a(y),i(JSON.parse(JSON.stringify(y)))}catch(x){h((x==null?void 0:x.message)||String(x))}finally{d(!1)}}},[r,e,t]);l.useEffect(()=>{f()},[f]);const v=l.useCallback(async(x,j)=>{var C;if(e){u(`${x}:${j}`),h(null);try{const y=((C=n[x])==null?void 0:C[j])||"",b=await r(e,"write_coordinator_prompt",{key:x,kind:j,content:y}),N=b!=null&&b.result&&typeof b.result=="object"?b.result:b;if(!(N!=null&&N.success)){h((N==null?void 0:N.error)||"Save failed");return}i(S=>({...S,[x]:{...S[x]||{override:"",append:""},[j]:y}}))}catch(y){h((y==null?void 0:y.message)||String(y))}finally{u(null)}}},[r,e,n]),w=l.useMemo(()=>(x,j)=>{var C,y;return(((C=n[x])==null?void 0:C[j])||"")!==(((y=o[x])==null?void 0:y[j])||"")},[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:g||"~/.adhdev/coordinator-prompts/"})]}),s.jsxs("p",{className:"mt-1",children:[s.jsx("strong",{children:"Override"})," replaces the daemon's built-in base prompt for that CLI."," ",s.jsx("strong",{children:"Append"})," stacks after whichever base wins. Leave a field empty + Save to remove it (reset to default). Supports placeholders: ","{{meshName}}",", ","{{repo}}",", ","{{nodes}}",", ","{{rules}}",", etc."]})]}),m&&s.jsx("div",{className:"text-[12px] text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:m}),c&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Loading…"}),s.jsx("div",{className:"flex flex-col gap-6",children:Object.entries(n).map(([x,j])=>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:x}),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:j.override,onChange:C=>a(y=>({...y,[x]:{...y[x],override:C.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:p===`${x}:override`}),s.jsx("div",{className:"mt-1 mb-3 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void v(x,"override"),disabled:p===`${x}:override`||!w(x,"override"),children:p===`${x}:override`?"Saving…":w(x,"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:j.append,onChange:C=>a(y=>({...y,[x]:{...y[x],append:C.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:p===`${x}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void v(x,"append"),disabled:p===`${x}:append`||!w(x,"append"),children:p===`${x}:append`?"Saving…":w(x,"append")?"Save append":"Saved"})})]},x))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const Yv=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Jv(){const{preference:e,setPreference:t}=Ps();return s.jsx("div",{className:"flex gap-2",children:Yv.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 Xv(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 Qv(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function io(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Ic(e){const{r:t,g:r,b:n}=Qv(e);return .2126*io(t)+.7152*io(r)+.0722*io(n)}function Ac(e,t){const r=Ic(e),n=Ic(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function Mp(e){const t=Xv(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return Ac(t,r)>=Ac(t,n)?r:n}const ci={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},di={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},Zv=[{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"}}}],Tp="adhdev-chat-theme",_p="adhdev-chat-theme-custom";function Vn(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Tp)||"ember"}catch{return"ember"}}function as(e){try{const t=localStorage.getItem(_p);if(t){const r=JSON.parse(t);return{...e==="dark"?ci:di,...r[e]}}}catch{}return e==="dark"?ci:di}function Mn(e,t){try{localStorage.setItem(_p,JSON.stringify({dark:e,light:t}))}catch{}}function Jt(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 xa(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 ew={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function tn(e,t){var a;const r=(a=ew[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",xa(r,24)),n.style.setProperty("--accent-on-primary",Mp(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${xa(r,18)})`),n.style.setProperty("--border-accent",Jt(r,.35)),n.style.setProperty("--nav-active-bg",Jt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Jt(r,.06)}`)}function Gs(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Jt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Jt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Jt(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",Jt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Jt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",xa(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Mp(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${xa(e.accentColor,40)})`),t.style.setProperty("--border-accent",Jt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Jt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Jt(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 ${Jt(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 Yi(){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 tw(e){try{localStorage.setItem(Tp,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=zs()?"dark":"light";Gs(as(t))}else Yi(),tn(e,zs()?"dark":"light")}function sw(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Vn();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=zs()?"dark":"light";Gs(as(t))}else Yi(),tn(e,zs()?"dark":"light")}function zs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Et({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 Br({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 rw({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=l.useState(()=>as(r));l.useEffect(()=>{a(as(r))},[r]);const o=l.useCallback((i,c)=>{a(d=>{const p={...d,[i]:c},m=as(r==="dark"?"light":"dark");return r==="dark"?Mn(p,m):Mn(m,p),Gs(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(Br,{title:"App Background",children:[s.jsx(Et,{label:"Background",value:n.bgPrimary,onChange:i=>o("bgPrimary",i)}),s.jsx(Et,{label:"Surface",value:n.bgSecondary,onChange:i=>o("bgSecondary",i)}),s.jsx(Et,{label:"Card",value:n.surfacePrimary,onChange:i=>o("surfacePrimary",i)})]}),s.jsxs(Br,{title:"App Text",children:[s.jsx(Et,{label:"Primary",value:n.textPrimary,onChange:i=>o("textPrimary",i)}),s.jsx(Et,{label:"Secondary",value:n.textSecondary,onChange:i=>o("textSecondary",i)}),s.jsx(Et,{label:"Muted",value:n.textMuted,onChange:i=>o("textMuted",i)})]}),s.jsxs(Br,{title:"Borders & Accent",children:[s.jsx(Et,{label:"Border subtle",value:n.borderSubtle,onChange:i=>o("borderSubtle",i)}),s.jsx(Et,{label:"Border default",value:n.borderDefault,onChange:i=>o("borderDefault",i)}),s.jsx(Et,{label:"Accent",value:n.accentColor,onChange:i=>o("accentColor",i)})]})]}),s.jsxs("div",{children:[s.jsxs(Br,{title:"Chat Bubbles",children:[s.jsx(Et,{label:"User bubble",value:n.userBubble,onChange:i=>o("userBubble",i)}),s.jsx(Et,{label:"User text",value:n.userText,onChange:i=>o("userText",i)}),s.jsx(Et,{label:"Agent bubble",value:n.assistantBubble,onChange:i=>o("assistantBubble",i)}),s.jsx(Et,{label:"Agent text",value:n.assistantText,onChange:i=>o("assistantText",i)})]}),s.jsxs(Br,{title:"Chat Layout",children:[s.jsx(Et,{label:"Chat BG",value:n.containerBg,onChange:i=>o("containerBg",i)}),s.jsx(Et,{label:"Send button",value:n.sendButton,onChange:i=>o("sendButton",i)}),s.jsx(Et,{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?ci:di,d=as(e?"light":"dark");e?Mn(i,d):Mn(d,i),a(i),Gs(i),t(i)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:"Reset to defaults"})]})}function nw(){const[e,t]=l.useState(Vn),[r,n]=l.useState(!0),[a,o]=l.useState(()=>as("dark"));l.useEffect(()=>{n(zs());const d=new MutationObserver(()=>{const m=zs();n(m);const h=Vn();h==="custom"?Gs(as(m?"dark":"light")):tn(h,m?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const m=zs();n(m);const h=Vn();h==="custom"?Gs(as(m?"dark":"light")):tn(h,m?"dark":"light")};return p.addEventListener("change",u),()=>{d.disconnect(),p.removeEventListener("change",u)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?Gs(as(r?"dark":"light")):(Yi(),tn(e,r?"dark":"light"))},[e,r]),l.useEffect(()=>{o(as(r?"dark":"light"))},[r]);const i=d=>{t(d),tw(d)},c=[...Zv,{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,u=r?d.preview.dark:d.preview.light,m=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>i(d.id),className:"text-left rounded-xl p-3 transition-all",style:{background: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:u.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"Hello! How can I help?"}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.userBubble,color:m},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.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(rw,{dark:r,onColorsChange:d=>o(d)})]})}const Ji="adhdev_mobileDashboardMode_v1",ui="adhdev:mobile-dashboard-mode-change";function Xi(){try{return localStorage.getItem(Ji)==="workspace"?"workspace":"chat"}catch{return"chat"}}function aw(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Xi())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==Ji||t()};return window.addEventListener(ui,r),window.addEventListener("storage",n),()=>{window.removeEventListener(ui,r),window.removeEventListener("storage",n)}}function ow(e){try{localStorage.setItem(Ji,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ui,{detail:e}))}function iw(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(Xi()==="chat")},[]),s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Zs,{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),ow(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const lw="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",cw="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function dw({themeDescription:e=lw,mobileDescription:t=cw,fontsSlot:r}){return s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),s.jsx(Jv,{})]}),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:e}),s.jsx(nw,{})]}),r,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:t}),s.jsx(iw,{})]})]})}const lo=new Map,Mc=new Map;function uw(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 pw(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 Lp(){const{sendCommand:e}=bt(),{injectEntries:t,getIdes:r}=nn();return l.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??Iy,i=Mc.get(n)||0;if(!(a!=null&&a.force)&&i>0&&Date.now()-i<o)return;const c=lo.get(n);if(c)return c;const d=(async()=>{const p=await e(n,"get_machine_runtime_stats"),u=uw(p);if(!u)return;const m=r().find(g=>g.id===n),h=pw(m,n,u.machine,u.timestamp||Date.now());t([h]),Mc.set(n,Date.now())})().finally(()=>{lo.delete(n)});return lo.set(n,d),d},[r,t,e])}function mw(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 hw(e,t){const{sendData:r}=bt(),{injectEntries:n,getIdes:a}=nn(),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=>is.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const m=a().find(g=>g.id===d),h=mw(m,d,u);n([h])}));return()=>{c.forEach(d=>d())}},[o,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function fw(e,t){const{sendData:r}=bt(),[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=is.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)},Ty):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 xw(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Rp(e){const{sendData:t}=bt(),[r,n]=l.useState({});return l.useEffect(()=>{const a=xw(e);if(!a||!e.sessionId||!t){n({});return}const o=is.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}),fr.record({interactionId:i.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:i.status,modalButtonCount:Array.isArray(i.modalButtons)?i.modalButtons.length:0}})});return o.initialSendAccepted||n({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),r}function bw(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function gw(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 yw(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 vw({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(!bw(o))throw new Error(gw(o));return}await yw(e.sessionId,t,a)}function Pp(e){const{ides:t,isP2PActive:r,p2pStates:n}=gs(),{sendCommand:a}=bt(),[o,i]=l.useState(null),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useRef(!1),h=l.useMemo(()=>Mx(t,e),[t,e]),g=!!h,k=l.useMemo(()=>h?h.prompt.promptId===o?null:h:null,[o,h]),f=l.useCallback(async x=>{if(!k||m.current)return;m.current=!0;const j=lu(k.prompt,x);d(!0),u(null);try{const C=(n==null?void 0:n[k.daemonId])==="connected"||r===!0;await vw({promptSession:k,response:j,useP2PCommand:C,sendCommand:a}),i(k.prompt.promptId)}catch(C){throw u(C instanceof Error?C.message:String(C)),C}finally{d(!1),m.current=!1}},[r,n,k,a]),v=l.useCallback(()=>{k&&i(k.prompt.promptId)},[k]),w=l.useCallback(()=>{i(null),u(null)},[]);return{promptSession:k,hasActivePrompt:g,responseError:p,isSubmitting:c,submit:f,cancel:v,reopen:w}}function Dp(e){return e instanceof Error?e.message:String(e||"")}function ww(e){const t=Dp(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 jw(e){const t=Dp(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function $p({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!dt(e)||lt(e))return;const o=Ir(e);if(o===t)return;const i=e.sessionId;i&&a(c=>({...c,[i]:t}));try{await n(Rs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:bs(e),mode:t})}catch(c){const d=jw(c);i&&!d&&a(p=>{const u={...p};return o===Sw(r,i)?delete u[i]:u[i]=o,u}),ww(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 Tc(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 kw(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=Tc(a,t),i=Array.isArray(a.childSessions)?a.childSessions.map(d=>Tc(d,t)):a.childSessions,c=i!==a.childSessions;return o!==a||c?(r=!0,{...o,...c?{childSessions:i}:{}}):a});return r?n:e}function Sw(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 Nw({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n,isConversationMuted:a}){l.useEffect(()=>{ku()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:lp(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null,target:{providerSessionId:i.providerSessionId,sessionId:i.sessionId,tabKey:i.tabKey,routeId:i.routeId},muted:a?a(i):!1})),[e,a]);return eg(o),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{r(d=>{const p=Date.now(),u={};for(const[m,h]of Object.entries(d))p-h<5e3&&(u[m]=h);return Object.keys(u).length===Object.keys(d).length?d:u})},5500);return()=>clearTimeout(c)},[t,r]),l.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(d=>{const p=d.filter(u=>u.timestamp>c).slice(-100);return p.length===d.length?d:p})},6e4);return()=>clearInterval(i)},[n]),null}function _c(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function Vs(e){const t=[...e.messages].reverse().find(a=>!(a!=null&&a._localId))||e.messages[e.messages.length-1],r=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,n=_c(t==null?void 0:t.receivedAt)||_c(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function pi(e,t=0){return Vs(e)||e.lastUpdated||t||0}function Ep(e){return Vs(e)||e.lastUpdated||0}function Bp(e,t,r=Ep){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 mi(e){var r;const t=Qt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function Cw(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!mi(e)&&!e.title.trim()}function Iw(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(mi(r))-Number(mi(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:Bp(t,r)})[0]||null}function ls(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=Iw(a);return n?o&&Cw(n)?o:n:o||r[0]||null}function Aw(e){const t=e.filter(a=>a.type!=="adhdev-daemon"),r=new Set;for(const a of t){if(!Xo(a))continue;const o=bu(a);o&&r.add(o)}const n=new Map;for(const a of t){const o=_b(a,r),i=n.get(o);if(!i){n.set(o,a);continue}const c=m=>(m.workspace?1:0)+(m.activeChat?1:0)+(m.lastMessagePreview?1:0),d=c(i),p=c(a),u=p>d||p===d&&(a.timestamp||0)>(i.timestamp||0)?a:i;n.set(o,Mw(u,u===a?i:a))}return Array.from(n.values())}function Mw(e,t){const r=Xo(t),n=Xo(e);if(!r&&!n)return e;const a=n?r?void 0:t:e,o=n?e:r?t:void 0,i=a&&String(a.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,c=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,d=o==null?void 0:o.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...d&&!n&&{settings:{...d,...e.settings??{}}}}}function co(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 Tw(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 Lc(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Tw(xr(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 _w(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||""),Lc(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||""),Lc(r.activeChat)].join(":"))].join("|")}function Lw(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 Rw(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const o of Xr({routeId:n.routeId}))r.set(o,a);for(const o of Xr({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of Xr({tabKey:n.tabKey}))r.set(o,n)}return r}function Pw(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Dw(e){const t=Pw(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=xr(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function $w({ides:e,connectionStates:t,clearedTabs:r}){const n=l.useMemo(()=>Aw(e),[e]),a=l.useMemo(()=>uu(e),[e]),o=l.useMemo(()=>vp(e),[e]),i=l.useRef([]),c=l.useRef([]),d=l.useRef([]),p=l.useRef(new Map),u=l.useRef(new Map),m=l.useMemo(()=>{const C=new Map,y=[];for(const I of n){const{connectionState:R="new",machineName:L}=wp(I,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),M=_w(I),P=p.current.get(I.id);if(P&&P.ide===I&&P.sourceSignature===M&&P.connectionState===R&&P.machineName===L){C.set(I.id,P),y.push(...P.conversations);continue}const $=Vi(I,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),Y={ide:I,sourceSignature:M,connectionState:R,machineName:L,conversations:$};C.set(I.id,Y),y.push(...$)}p.current=C;const b=new Map,N=I=>{const R=Dw(I),L=u.current.get(I.tabKey);if(L&&L.signature===R)return b.set(I.tabKey,L),L.timestamp;const M={signature:R,timestamp:Ep(I)||(L==null?void 0:L.timestamp)||0};return b.set(I.tabKey,M),M.timestamp},S=[...y].sort((I,R)=>Bp(I,R,N));return u.current=b,S},[n,t,o]),h=l.useMemo(()=>{const C=Lw(m,r);return co(i.current,C)?i.current:(i.current=C,C)},[m,r]),g=l.useMemo(()=>{const C=new Map,y=Array.from(new Set(h.map(b=>b.routeId)));for(const b of y){const N=ls(h,b);N&&C.set(b,N)}return C},[h]),k=l.useMemo(()=>{const C=new Map;for(const y of h){const b=g.get(y.routeId),N=y.streamSource==="native"&&b?b:y;for(const S of Xr({providerSessionId:y.providerSessionId,sessionId:y.sessionId,tabKey:y.tabKey}))C.set(S,N)}return C},[h,g]),f=l.useMemo(()=>Rw(h,g),[h,g]),v=l.useCallback(C=>{if(C)return k.get(C)},[k]),w=l.useCallback(C=>{if(C)return f.get(C)},[f]),x=l.useMemo(()=>{const C=h.filter(y=>!Ls(y,a).surfaceHidden);return co(c.current,C)?c.current:(c.current=C,C)},[h,a]),j=l.useMemo(()=>{const C=x.map(y=>y.tabKey);return co(d.current,C)?d.current:(d.current=C,C)},[x]);return{chatIdes:n,conversations:h,visibleConversations:x,visibleTabKeys:j,resolveConversationBySessionId:v,resolveConversationByTarget:w}}function Ew({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 Bw({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){l.useEffect(()=>{ut.setIdes(e)},[e]),l.useEffect(()=>{ut.setResolveAction((a,o,i)=>{t(a,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const a=ut.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=np.on("status_event",o=>{ut.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),u=(p==null?void 0:p.routeId)||c.daemonId;if(!u)return;const m=Number(c.buttonIndex),h=c.button||((f=p==null?void 0:p.modalButtons)==null?void 0:f[m])||"Approve",g=String(h).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(g);t(u,"resolve_action",{action:k?"approve":"reject",button:h,...Number.isFinite(m)&&{buttonIndex:m},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(v=>console.error("[SW Action] approval failed:",v))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",a)}},[n,t])}const Fw="adhdev_dashboardLayout_v1",Ow="adhdev_dashboardDockview_v1",Hw="adhdev_dashboardDockviewHiddenRestore_v1",Fr={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Qi(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Ww(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Fp(e){return`${Fw}:${e}`}function Kw(e){const t=Fp(e);return Qi(t,null)}function Uw(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=Fp(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Op(e){return`${Ow}:${e}`}function Gw(e){const t=Op(e);return Qi(t,null)}function zw(e,t){try{const r=Op(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Hp(e){return`${Hw}:${e}`}function Vw(e){const t=Hp(e);return Qi(t,{})}function qw(e,t){try{const r=Hp(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Yw(){return{groupAssignments:[...Fr.groupAssignments],focusedGroup:Fr.focusedGroup,groupActiveTabIds:{...Fr.groupActiveTabIds},groupTabOrders:{...Fr.groupTabOrders},groupSizes:[...Fr.groupSizes]}}function Jw(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Xw(){const[e]=l.useState(()=>Ww(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,u]=l.useState([]),[m,h]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[g,k]=l.useState(!1),f=l.useCallback(()=>{if(g)return;const I=Kw(e)??Yw();r(new Map(I.groupAssignments)),a(I.focusedGroup),i(I.groupActiveTabIds),d(I.groupTabOrders),u(I.groupSizes),k(!0)},[g,e]);l.useEffect(()=>{g&&Uw(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:c,groupSizes:p})},[g,e,t,n,o,c,p]),l.useEffect(()=>{const I=window.matchMedia("(max-width: 767px)"),R=L=>h(L.matches);return I.addEventListener("change",R),()=>I.removeEventListener("change",R)},[]);const v=l.useCallback(I=>{r(I)},[]),w=l.useCallback(I=>{a(I)},[]),x=l.useCallback(I=>{i(I)},[]),j=l.useCallback(I=>{d(I)},[]),C=l.useCallback(I=>{u(I)},[]),y=l.useCallback(I=>{w(I)},[w]),b=l.useCallback((I,R)=>{i(L=>(L[I]??null)===(R??null)?L:{...L,[I]:R})},[]),N=l.useCallback((I,R)=>{d(L=>{const M=L[I];return Jw(M,R)?L:{...L,[I]:R}})},[]),S=l.useCallback((I,R)=>{const L=R.get(I)??0;return b(L,I),y(L),L},[y,b]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:v,focusedGroup:n,updateFocusedGroup:w,focusGroup:y,groupActiveTabIds:o,updateGroupActiveTabIds:x,setGroupActiveTab:b,groupTabOrders:c,updateGroupTabOrders:j,setGroupTabOrder:N,groupSizes:p,updateGroupSizes:C,isMobile:m,hasHydratedStoredLayout:g,hydrateStoredLayout:f,focusConversationTab:S}}function Qw(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Ca(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Zw({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:d,activeConv:p,isRefreshingHistory:u,ides:m,handleRefreshHistory:h}){const g=l.useRef(!1),k=l.useRef(!1),f=l.useRef(null),v=l.useRef(!1);l.useEffect(()=>{if(!e||g.current||t.length===0)return;if(!a){o();return}const w=r(e);w&&(i(w.tabKey,n),g.current=!0,k.current=!0,f.current!=null&&(window.clearTimeout(f.current),f.current=null),c(x=>{const j=new URLSearchParams(x);return j.delete("activeTab"),j},{replace:!0}))},[e,t,r,n,a,o,i,c]),l.useEffect(()=>{if(!(k.current||a)&&t.length!==0){if(!e){o(),k.current=!0;return}if(g.current){k.current=!0;return}if(f.current==null)return f.current=window.setTimeout(()=>{f.current=null,!(k.current||a)&&(o(),k.current=!0)},1500),()=>{f.current!=null&&(window.clearTimeout(f.current),f.current=null)}}},[e,t.length,a,o]),l.useEffect(()=>{if(!d){v.current=!1;return}if(!p||v.current||u)return;const w=m.find(x=>x.id===p.routeId);w&&(!w.chats||w.chats.length===0||Qw(w.chats,p))&&(v.current=!0,h())},[d,p,u,m,h])}function uo(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=Ca(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Wp({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[i,c]=l.useState(!1),[d,p]=l.useState(!1),u=l.useCallback(async k=>{try{await e("standalone","launch_ide",{ideType:k,enableCdp:!0})}catch(f){console.error("Launch failed",f)}},[e]),m=l.useCallback(async(k,f)=>{try{const v=k||(t==null?void 0:t.daemonId)||"",w=await e(v,"switch_chat",{id:f,sessionId:f,...Ws(t)}),x=w==null?void 0:w.result;if((w==null?void 0:w.success)===!0||x==="switched"||x==="switched-by-title")return;x===!1||x==="not_found"?or(a,"⚠️ Session tab not found — try refreshing history"):typeof x=="string"&&x.startsWith("error:")?or(a,`⚠️ Switch error: ${x}`):or(a,"⚠️ Session switch failed")}catch(v){console.error("Switch failed",v),or(a,`❌ Switch failed: ${v.message||"connection error"}`)}},[t,e,a]),h=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const k=Ks(t);await e(k,"new_chat",{...Ws(t)}),Yy(k,t.sessionId,Ca(t)[0]),o(f=>({...f,[t.tabKey]:Date.now()}))}catch(k){console.error("New chat failed",k)}finally{c(!1)}}},[t,i,e,o]),g=l.useCallback(async()=>{var k,f;if(!(!t||d)){p(!0);try{const v=Ks(t),w=async()=>e(v,"list_chats",{forceExpand:!0,...Ws(t)});let x=await w(),j=(x==null?void 0:x.chats)||((k=x==null?void 0:x.result)==null?void 0:k.chats);uo(j,t)&&(await new Promise(C=>setTimeout(C,450)),x=await w(),j=(x==null?void 0:x.chats)||((f=x==null?void 0:x.result)==null?void 0:f.chats)),x!=null&&x.success&&Array.isArray(j)&&(n(t.routeId,j),uo(j,t)&&!uo(r,t)&&or(a,"⚠️ History dialog did not fully open — try once more"))}catch(v){console.error("Refresh history failed",v)}finally{p(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:m,handleNewChat:h,handleRefreshHistory:g}}function ej(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 tj(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function Rc(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 Tn(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 Pc(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 sj(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 rj(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 Dc(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 $c(e){return Array(e).fill(100/e)}function nj({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:d,visibleTabKeys:p}){const u=l.useRef(null),m=l.useMemo(()=>Tn(e,p),[e,p]),h=m.assignments,g=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),k=g>1,f=l.useCallback((y,b)=>{t(N=>{const S=new Map(Tn(N,p).assignments);return b===0?S.delete(y):S.set(y,b),S}),n(N=>({...N,[b]:y})),r(b)},[t,p,n,r]),v=l.useCallback(y=>{t(b=>{const N=Tn(b,p).assignments,S=new Map;for(const[I,R]of N)R!==y&&(R>y?S.set(I,R-1):S.set(I,R));return S}),i(b=>{if(b.length<=1)return[];const N=[...b];N.splice(y,1);const S=N.reduce((I,R)=>I+R,0);return S>0?N.map(I=>I/S*100):[]}),r(0)},[t,p,i,r]),w=l.useCallback((y,b)=>{b.preventDefault();const N=u.current;if(!N)return;const S=b.clientX,I=N.offsetWidth,R=o.length===g?[...o]:$c(g),L=P=>{const Y=(P.clientX-S)/I*100,_=[...R];_[y]=Math.max(15,R[y]+Y),_[y+1]=Math.max(15,R[y+1]-Y),i(_)},M=()=>{document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",M),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",M)},[o,g,i]),x=l.useCallback((y,b,N)=>{if(g>=4)return;const S=N==="left"?b:b+1;t(I=>{const R=Tn(I,p).assignments,L=new Map;for(const M of d){const P=R.get(M.tabKey)??0,$=P>=S?P+1:P;$>0&&L.set(M.tabKey,$)}return S>0&&L.set(y,S),L}),i(I=>{const R=I.length===g?[...I]:$c(g),L=R[b]??100/g,M=Math.max(15,L/2),P=Math.max(15,L/2),$=[...R];$[b]=M,$.splice(S,0,P);const Y=$.reduce((_,H)=>_+H,0);return $.map(_=>_/Y*100)}),n(I=>{const R=Dc(I,S);return R[S]=y,R}),a(I=>{const R=Dc(I,S);return R[S]=[y],R}),r(S)},[g,t,p,d,i,n,a,r]);l.useEffect(()=>{ej(e,h)||t(h)},[e,h,t]),l.useEffect(()=>{const{mapping:y,usedGroups:b}=m;n(N=>{const S=Pc(N,y);return Rc(N,S)?N:S}),a(N=>{const S=Pc(N,y);return Rc(N,S)?N:S}),r(N=>{const S=c?0:sj(N,b,y);return N===S?N:S}),i(N=>{const S=c?[]:rj(N,b,m.groupCount);return tj(N,S)?N:S})},[m,c,n,a,r,i]);const j=l.useMemo(()=>{const y=Array.from({length:g},()=>[]);for(const b of d){const N=h.get(b.tabKey)??0,S=Math.min(N,g-1);y[S].push(b)}return y},[d,h,g]),C=l.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:h,numGroups:g,isSplitMode:k,groupedConvs:j,moveTabToGroup:f,closeGroup:v,handleResizeStart:w,splitTabRelative:x,clearAllSplits:C}}function po(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 aj(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 _n(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Zi(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=po(t.channel)||po(e.updateChannel)||po(e.releaseChannel)||void 0,n=aj(t.npmTag)||(r==="preview"?"next":r==="stable"?"latest":void 0),a=_n(t.targetVersion)||_n(e.serverVersion)||void 0,o=_n(t.minVersion)||void 0,i=_n(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 cr(e,t=null){return Zi(e).targetVersion||t}function Kp(e){return Zi(e).channel||null}function Up(e){const t=Zi(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 oj({ides:e,sendDaemonCommand:t}){const r="0.9.82",n=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:qi(m,cr(m,r))).sort((m,h)=>Number(en(h,cr(h,r)))-Number(en(m,cr(m,r)))),[r,e]),a=l.useMemo(()=>n.some(m=>en(m,cr(m,r))),[r,n]),o=l.useMemo(()=>n.map(m=>cr(m,r)).find(m=>typeof m=="string"&&m.trim().length>0)||r,[r,n]),[i,c]=l.useState(!1),[d,p]=l.useState({}),u=l.useCallback(async m=>{var g,k;const h=e.find(f=>f.id===m);if(h){p(f=>({...f,[m]:"upgrading"}));try{const f=await t(m,"daemon_upgrade",Up(h));(g=f==null?void 0:f.result)!=null&&g.upgraded||(k=f==null?void 0:f.result)!=null&&k.success?p(v=>({...v,[m]:"done"})):p(v=>({...v,[m]:"error"}))}catch{p(f=>({...f,[m]:"error"}))}}},[e,t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const Gp=80;function qn(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function ij(e){return{...e,createdAt:qn(e.createdAt),updatedAt:qn(e.updatedAt,e.createdAt),lastEventAt:qn(e.lastEventAt,e.updatedAt||e.createdAt)}}function lj(e){const t=xu(e);return t==="unknown:"?e.id:t}function cj(e){return[e.type,fu(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function dj(e,t=Gp){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=lj(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 uj(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||o!=null&&o.muted)continue;const i=Na(a,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const d=qn(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),p=cj({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(ij({id:p,dedupKey:p,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:$u(a),preview:iy(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return dj(n)}function pj(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function mj(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=Gp}=e,a=l.useMemo(()=>uj(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=l.useMemo(()=>pj(a),[a]);return{notifications:a,unreadCount:o}}function hj({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 el(...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 fj(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 tl(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=fj(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 xj(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 bj(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function sl(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=bj(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,u)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${u}`:p==="/"||p==="\\"?`${i}${u}`:`${p.replace(/[\\/]+$/,"")}${i}${u}`,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,u)=>p.name.localeCompare(u.name)):[];return{path:o,directories:d}}function Ec(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 zp(e,t={}){const r=e==null?void 0:e.mcpConfig;if((r==null?void 0:r.mode)!=="manual")return null;const a=Ec(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"}).trim();return!a.includes(`
|
|
65
|
+
`)&&!a.startsWith("{")?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:Ec(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function gj(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 dn(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Vp(e){return Ia(e)||e.tabKey||e.routeId||null}function qp(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=ls(e.conversations,n)||e.conversations.find(i=>i.routeId===n);if(o!=null&&o.tabKey)return o.tabKey}return t||r||n||null}function Is(e){return String(e||"").trim()}function Yp(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ba(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function yj(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function vj(e,t){const r=Is(e.providerSessionId),n=Is(e.targetSessionId),a=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Is).filter(Boolean);return!!(r&&i.includes(r)||n&&i.includes(n))});return a?a.tabKey:n||r||null}function wj(e,t,r){if(t.event!=="agent:generating_completed")return null;const n=Yp(t.daemonId);if(n&&n!==e.machineId)return null;const a=Is(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=Is(e.resumeSessionId),i=Is(e.launchedSessionId),c=Is(t.providerSessionId),d=Is(t.targetSessionId);if(o&&o!==c&&o!==d||i&&i!==c&&i!==d)return null;const p=ba(e.workspacePath);if(p){const u=ba(t.workspaceName);if(u&&!yj(u,p))return null}return vj(t,r)}function Bc(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function jj({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=ba(n.workspacePath),p=e.find(m=>{var v,w,x,j;if(!m||m.type==="adhdev-daemon"||Yp(m.daemonId||m.id)!==n.machineId||(on(m)?"cli":pr(m)?"acp":"ide")!==n.kind)return!1;const k=String(m.agentType||m.type||"");if(n.providerType&&k!==n.providerType)return!1;if(n.resumeSessionId)return String(m.providerSessionId||"")===n.resumeSessionId;if(n.launchedSessionId){const C=String(n.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(b=>String(b||"")).filter(Boolean).includes(C)}if(d){const C=ba(m.workspace||m.runtimeWorkspaceLabel);return C?C===d:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((j=(x=(w=(v=m.activeChat)==null?void 0:v.messages)==null?void 0:w.at)==null?void 0:x.call(w,-1))==null?void 0:j.timestamp)||0)>=n.startedAt-5e3});if(!p)return;const u=qp({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});u&&(i(),r(u))},[i,t,e,r,n]),l.useEffect(()=>ut.onStatusEvent(d=>{const p=o.current;if(!p)return;const u=wj(p,d,t);u&&(i(),r(u))}),[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 kj({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const i=Bi(),{launchCli:c}=wa(),d=l.useCallback(async(v,w)=>sl(e,v,w),[e]),p=l.useCallback(async(v,w)=>{if(!w.trim())return{ok:!1,error:"Choose a workspace path first."};try{const x=await e(v,"workspace_add",{path:w.trim()});return x!=null&&x.success?{ok:!0}:{ok:!1,error:(x==null?void 0:x.error)||"Could not save workspace"}}catch(x){return{ok:!1,error:x instanceof Error?x.message:"Could not save workspace"}}},[e]),u=l.useCallback(async(v,w,x)=>{var j;try{const C={ideType:w,enableCdp:!0};(j=x==null?void 0:x.workspacePath)!=null&&j.trim()&&(C.workspace=x.workspacePath.trim());const y=await e(v,"launch_ide",C);return!(y!=null&&y.success)&&(y==null?void 0:y.success)!==void 0?{ok:!1,error:(y==null?void 0:y.error)||"Could not launch IDE"}:(t({machineId:v,kind:"ide",providerType:w,workspacePath:(x==null?void 0:x.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(C){return{ok:!1,error:C instanceof Error?C.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(v,w,x,j)=>{var y,b,N,S;const C=Date.now();try{const I={cliType:x};(y=j==null?void 0:j.workspacePath)!=null&&y.trim()?I.dir=j.workspacePath.trim():j!=null&&j.workspaceId&&(I.workspaceId=j.workspaceId),(b=j==null?void 0:j.resumeSessionId)!=null&&b.trim()&&(I.resumeSessionId=j.resumeSessionId.trim()),Array.isArray(j==null?void 0:j.cliArgs)&&j.cliArgs.length>0&&(I.cliArgs=j.cliArgs),(N=j==null?void 0:j.initialModel)!=null&&N.trim()&&(I.initialModel=j.initialModel.trim()),(S=j==null?void 0:j.initialThinkingLevel)!=null&&S.trim()&&(I.initialThinkingLevel=j.initialThinkingLevel.trim());const R=await c(v,I),L=(R==null?void 0:R.result)||R,M=(L==null?void 0:L.sessionId)||(L==null?void 0:L.id);return R!=null&&R.success&&M?(t({machineId:v,kind:w,providerType:x,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,launchedSessionId:M,startedAt:C}),{ok:!0}):R!=null&&R.success?(t({machineId:v,kind:w,providerType:x,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:(R==null?void 0:R.error)||(L==null?void 0:L.error)||`Could not launch ${w.toUpperCase()} session`}}catch(I){return Bc(I)?(t({machineId:v,kind:w,providerType:x,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:I instanceof Error?I.message:`Could not launch ${w.toUpperCase()} session`}}},[c,e,t]),h=l.useCallback(async v=>{var w;if(i!=null&&i.listMeshes)return i.listMeshes(v);if(!v)return[];try{const x=await e(v,"list_meshes",{}),j=(x==null?void 0:x.result)??x;if((j==null?void 0:j.success)===!1)throw new Error((j==null?void 0:j.error)||"Could not load meshes");return(Array.isArray(j==null?void 0:j.meshes)?j.meshes:Array.isArray((w=j==null?void 0:j.result)==null?void 0:w.meshes)?j.result.meshes:[]).map(y=>{var b;return{id:String((y==null?void 0:y.id)||""),name:String((y==null?void 0:y.name)||(y==null?void 0:y.id)||"Untitled mesh"),repoIdentity:(y==null?void 0:y.repoIdentity)||(y==null?void 0:y.repo_identity)||null,workspace:Array.isArray(y==null?void 0:y.nodes)&&y.nodes.length>0?String(((b=y.nodes[0])==null?void 0:b.workspace)||""):null,nodesCount:Array.isArray(y==null?void 0:y.nodes)?y.nodes.length:void 0,status:(y==null?void 0:y.status)||null}}).filter(y=>y.id)}catch(x){throw console.error("List meshes failed",x),x}},[i,e]),g=l.useCallback(async(v,w,x,j)=>{var y,b;if(!w.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(v,w,x,j);const C=Date.now();try{const N={meshId:w.trim()};x.trim()&&(N.cliType=x.trim());const S=(y=j==null?void 0:j.initialModel)==null?void 0:y.trim(),I=(b=j==null?void 0:j.initialThinkingLevel)==null?void 0:b.trim();S&&(N.initialModel=S),I&&(N.initialThinkingLevel=I);const R=await e(v,"launch_mesh_coordinator",N),L=(R==null?void 0:R.result)??R;if((L==null?void 0:L.success)===!1||(R==null?void 0:R.success)===!1){const P=String((L==null?void 0:L.code)||(R==null?void 0:R.code)||""),$=gj((L==null?void 0:L.meshCoordinatorSetup)||(L==null?void 0:L.manualSetup)||(R==null?void 0:R.meshCoordinatorSetup)||(R==null?void 0:R.manualSetup));return{ok:!1,error:(L==null?void 0:L.error)||(R==null?void 0:R.error)||"Could not launch mesh coordinator",code:P||void 0,manualSetup:$}}const M=(L==null?void 0:L.sessionId)||(L==null?void 0:L.id);return M?r(M):t({machineId:v,kind:"cli",providerType:(L==null?void 0:L.cliType)||x.trim()||void 0,workspacePath:(L==null?void 0:L.workspace)||null,startedAt:C}),{ok:!0}}catch(N){return Bc(N)?(t({machineId:v,kind:"cli",providerType:x.trim()||void 0,startedAt:C}),{ok:!0}):{ok:!1,error:N instanceof Error?N.message:"Could not launch mesh coordinator"}}},[i,r,e,t]),k=l.useCallback(async(v,w)=>{if(!v||!w)return[];try{const x=await e(v,"list_saved_sessions",{providerType:w,kind:"cli",limit:30}),j=(x==null?void 0:x.result)??x;return Array.isArray(j==null?void 0:j.sessions)?j.sessions:[]}catch(x){return console.error("List saved sessions failed",x),[]}},[e]),f=l.useCallback(async v=>{await $p({conversation:n,mode:v,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:p,handleLaunchMachineIde:u,handleLaunchMachineProvider:m,handleListMachineMeshes:h,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:k,setActiveCliViewMode:f}}function Sj(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 Nj(e,t,r=Date.now()){return!e||!Sj(t)?null:{tabKey:e,nonce:r}}function Cj({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:i}){const[c,d]=l.useState(null),[p,u]=l.useState(null),m=l.useMemo(()=>{var v,w;if(!e){if(c){const x=t.find(j=>j.tabKey===c);if(x)return x}return r[0]}const f=n[a];if(f){const x=t.find(j=>j.tabKey===f);if(x)return x}return((v=o[a])==null?void 0:v[0])||((w=o[0])==null?void 0:w[0])},[t,c,a,n,o,e,r]),h=l.useCallback(f=>{d(f)},[]),g=l.useCallback(f=>{d(f.tabKey),i(v=>{const w=new URLSearchParams(v),x=cy(f);return x?w.set("activeTab",x):w.delete("activeTab"),w},{replace:!0})},[i]),k=l.useCallback((f,v)=>{const w=Nj(f,v);w&&u(w)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:k,scrollToBottomRequest:p,setDesktopActiveTab:h}}function Ij(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 Aj(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 Mj({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 u=Ls(e,r),m=Aj({tabKey:e.tabKey,historySessionId:Ia(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:Vs(e),liveState:u}),h=m.autoReadKey,g=Ij({autoReadKey:h,shouldMarkSeen:m.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!m.shouldMarkSeen){g.shouldCancelPending&&p(),a.current=h;return}if(!g.shouldSchedule)return;g.shouldCancelPending&&p();const k=()=>{if(document.visibilityState!=="visible"||a.current===h)return;a.current=h,o.current=null,i.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const v=m.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:v,completionMarker:m.completionMarker}).catch(()=>{})};if(o.current=g.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(k,1500);const v=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};d.current=v,document.addEventListener("visibilitychange",v);return}const f=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(k,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 mo(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 Tj({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:d}){var W;const{launchCli:p}=wa(),[u,m]=l.useState(!1),[h,g]=l.useState([]),[k,f]=l.useState(()=>Bt()),[v,w]=l.useState(!1),[x,j]=l.useState(null),C=l.useRef(null),y=l.useMemo(()=>r||t||e,[e,r,t]),b=!!y&&dt(y)&&!lt(y),N=l.useMemo(()=>{if(!y||!b)return null;const B=y.daemonId||y.routeId||"",T=bs(y),A=mo(y);return`${B}:${T}:${y.providerSessionId||""}:${A}`},[y,b]),S=l.useMemo(()=>!y||!b?"":mo(y),[y,b]),{isCreatingChat:I,isRefreshingHistory:R,handleSwitchSession:L,handleNewChat:M,handleRefreshHistory:P}=Wp({sendDaemonCommand:a,activeConv:y,chats:(W=n.find(B=>B.id===(y==null?void 0:y.routeId)))==null?void 0:W.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),$=l.useCallback(()=>{m(!0)},[]),Y=l.useCallback(()=>{m(!1)},[]),_=l.useCallback(async()=>{if(!(!y||!b||v)){w(!0);try{const B=y.daemonId||y.routeId,T=bs(y),A=mo(y),E=await a(B,"list_saved_sessions",{agentType:T,providerType:T,kind:"cli",limit:50,...y.providerSessionId?{providerSessionId:y.providerSessionId}:{},...A?{workspace:A}:{}}),z=(E==null?void 0:E.result)??E;g(Array.isArray(z==null?void 0:z.sessions)?z.sessions:[])}catch(B){console.error("Refresh saved sessions failed",B),g([])}finally{w(!1)}}},[y,v,b,a]);l.useEffect(()=>{if(!u){C.current=null;return}if(!b){C.current=null,g([]),w(!1);return}!N||v||C.current!==N&&(C.current=N,_())},[_,u,v,b,N]);const H=l.useCallback(async B=>{if(!y||!b||!B.providerSessionId||!B.workspace)return;const T=y.daemonId||y.routeId,A=bs(y);try{j(B.providerSessionId);const E=await p(T,{cliType:A,dir:B.workspace,resumeSessionId:B.providerSessionId,initialModel:wu(B.summaryMetadata,"model",{preferShortValue:!0})||void 0}),z=(E==null?void 0:E.result)??E,G=typeof(z==null?void 0:z.sessionId)=="string"?z.sessionId:typeof(z==null?void 0:z.id)=="string"?z.id:"";G&&d(re=>{const X=new URLSearchParams(re);return X.set("activeTab",G),X},{replace:!0}),Y()}catch(E){console.error("Resume saved session failed",E)}finally{j(null)}},[Y,y,b,a,d]);return{historyModalOpen:u,openHistoryModal:$,closeHistoryModal:Y,historyTargetConv:y,isSavedSessionHistoryTarget:b,isHistoryCreatingChat:I,isHistoryRefreshingHistory:R,handleHistorySwitchSession:L,handleHistoryNewChat:M,handleHistoryRefresh:P,savedHistorySessions:h,savedHistoryFilters:k,setSavedHistoryFilters:f,missingWorkspaceResumePath:S,isSavedHistoryLoading:v,resumingSavedHistorySessionId:x,handleRefreshSavedHistory:_,handleResumeSavedHistorySession:H}}function _j({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}){const[d,p]=l.useState(null),[u,m]=l.useState(null),h=l.useMemo(()=>{if(e||!n)return null;const w=c(n);return w&&!dt(w)&&!lt(w)?w:null},[e,n,c]),g=l.useMemo(()=>{const w=d==null?void 0:d.routeId;if(!w)return null;const x=d!=null&&d.tabKey?o.find(j=>j.tabKey===d.tabKey):a?o.find(j=>j.tabKey===a):null;return(x==null?void 0:x.routeId)===w?x:ls(o,w)},[o,d,a]),k=l.useMemo(()=>{if(g)return i.find(w=>w.id===g.routeId)},[i,g]);l.useEffect(()=>{h&&(p({routeId:h.routeId,tabKey:ec(h)}),m(h),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,h]);const f=l.useCallback(w=>{w&&(p({routeId:w.routeId,tabKey:ec(w)}),m(w))},[]),v=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:k,remoteDialogActiveConv:u,setRemoteDialogActiveConv:m,openRemoteDialog:f,closeRemoteDialog:v}}function Lj({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:p}){const{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:h,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:f}=_j({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}),[v,w]=l.useState(!1),[x,j]=l.useState(null),C=l.useCallback(async N=>{const S=N||d;!S||!dt(S)&&!lt(S)||(j(S),w(!0))},[d]),y=l.useCallback(()=>{w(!1),j(null)},[]),b=l.useCallback(async N=>{const S=x||d;if(!S||!dt(S)&&!lt(S)){y();return}w(!1);try{const I=bs(S),R=S.routeId||S.daemonId||"";await p(R,"stop_cli",{cliType:I,targetSessionId:S.sessionId,mode:N,...Ta(S)})}catch(I){console.error("Stop CLI failed:",I)}finally{j(null)}},[d,y,x,p]);return{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:h,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:f,cliStopDialogOpen:v,cliStopTargetConv:x,requestCliStop:C,cancelCliStop:y,confirmCliStop:b}}function ho(e,t=!0){return(e??!0)&&t}const rl=l.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m=null,handleFocusAgent:h,isFocusingAgent:g,actionLogs:k,userName:f,scrollToBottomRequestNonce:v,isInputActive:w=!0,isVisible:x=!0}){const j=n,C=!n,y=ho(x,j),b=ho(x,C),N=ho(x),S=Rp(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(pu,{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(Ys,{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:j?"visible":"hidden",pointerEvents:j?"auto":"none"},children:s.jsx(H0,{activeConv:I,clearToken:r,terminalRef:o,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,isVisible:y,isInputActive:w&&y})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(ni,{activeConv:I,ideEntry:a,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:g,actionLogs:k,userName:f,scrollToBottomRequestNonce:v,isInputActive:w&&b,isVisible:b})})]}):s.jsx(ni,{activeConv:I,ideEntry:a,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:g,actionLogs:k,userName:f,scrollToBottomRequestNonce:v,isInputActive:w&&N,isVisible:N})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.handleForceSendChat===t.handleForceSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function Rj({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:o=!1}){var j,C,y;const i=mn(),c=Rs(e),d=o?null:Du(e),p=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),u=!o&&e.streamSource==="agent-stream"&&!!e.agentName,m=!o&&!u&&(e.transport==="pty"||e.transport==="acp"),h=gr(e),g=ly(e),k=(j=e.settings)==null?void 0:j.meshNodeFor,f=e.meshQueueStats,v=((C=e.coordinator)==null?void 0:C.meshId)||((y=e.settings)==null?void 0:y.meshCoordinatorFor),w=l.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),x=l.useCallback(()=>{if(r){r();return}const b=Vp(e);b&&i(dn(b))},[e,i,r]);return!p&&!u&&!m&&!d&&!k&&!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:x,title:g,children:[s.jsx(ds,{size:12}),s.jsx("span",{children:g})]}):s.jsxs("span",{className:"conversation-meta-chip",title:g,children:[s.jsx(ds,{size:12}),s.jsx("span",{children:g})]})),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(an,{size:12}),s.jsx("span",{children:h})]}),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(an,{size:12}),s.jsx("span",{children:h})]}),d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:w,title:d,children:[s.jsx(Ts,{size:12}),s.jsx("span",{children:d})]}):s.jsxs("span",{className:"conversation-meta-chip",title:d,children:[s.jsx(Ts,{size:12}),s.jsx("span",{children:d})]})),k&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Ts,{size:12}),s.jsx("span",{children:"Mesh Node"})]}),v&&f&&s.jsxs("span",{className:`conversation-meta-chip ${f.pending>0?"is-active":""}`,style:f.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${f.pending} pending, ${f.assigned} assigned, ${f.completed} completed, ${f.failed} failed`,children:[s.jsx(Df,{size:12}),s.jsxs("span",{children:[f.pending," Pending"]})]})]})}function Pj({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:p,onOpenNativeConversation:u,onOpenMachine:m,onOpenHistory:h,onOpenRemote:g,onOpenMeshGraph:k,onStopCli:f,cliViewMode:v,onSetCliViewMode:w,handleSendChat:x,handleForceSendChat:j,handleFocusAgent:C,handleModalButton:y,handleRelaunch:b}){var M,P;const N=l.useRef(null),S=dt(e)&&!t,I=S&&v==="terminal",R=!!e.daemonId&&!!((M=e.coordinator)!=null&&M.meshId||(P=e.settings)!=null&&P.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:xt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(Rj,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[S&&v&&s.jsx(up,{mode:v,onChange:w,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(Nt,{size:14})}),R&&k&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(Zt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>h(e),type:"button",children:s.jsx(Ii,{size:14})}),!t&&!S&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:s.jsx(ds,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(rl,{activeConv:e,clearToken:0,isCliTerminal:I,ideEntry:n,terminalRef:N,handleModalButton:y,handleRelaunch:b,handleSendChat:x,handleForceSendChat:j,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:C,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const fo={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 Dj(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Jp(){const[e,t]=l.useState("unix"),[r,n]=l.useState("powershell"),[a,o]=l.useState(!1),i=e==="unix"?"unix":r;l.useEffect(()=>{t(Dj())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(fo[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:fo[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:fo[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 Xp({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:ds},{key:"chats",label:"Chats",icon:Zs}];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 Ln({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 rr({children:e,className:t=""}){return s.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${t}`,children:e})}function Or({icon:e,title:t,subtitle:r,children:n}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function $j({conversation:e,onCancel:t,onConfirm:r}){const{t:n}=Pt(),a=xt(e);return s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] 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:t,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"card fade-in mobile-compact-dialog 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-bg-primary",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base md:text-lg font-extrabold",children:n("mobileInbox.hideTitle",{title:a})}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:n("mobileInbox.hideDescription")})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s.jsx("button",{onClick:r,className:"btn btn-primary w-full justify-center min-h-[42px]",children:n("mobileInbox.hide")}),s.jsx("button",{onClick:t,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:n("common.cancel")})]})]})]})}function Rn({item:e,type:t,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onRequestStopCli:o,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:d,onToggleMute:p}){const{t:u}=Pt(),m=t==="needs_attention"||t==="task_complete",h=t==="working",g=t==="earlier",k=t==="task_complete",{isReconnecting:f,isConnecting:v}=Cr(e.conversation),w=xt(e.conversation),x=yr(e.conversation),j=ip(e.conversation,{requiresAction:t==="needs_attention"}),C=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":h?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":g?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",y=m?"bg-accent-primary shadow-glow":h?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":g?"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",b=g?"text-text-secondary":"text-text-primary",N=g?"text-text-muted":"text-text-secondary",S=g?"text-text-secondary opacity-80":"text-text-muted",I=g?"text-text-muted opacity-80":"text-text-muted",R=!h&&!k,L=ap(e.conversation),M="text-[color:var(--status-warning)]",P=$=>{if(!c)return;$.preventDefault(),$.stopPropagation();const Y=c==null?void 0:c(e.conversation);Promise.resolve(Y).catch(_=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",_)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${C}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||h?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 ${y}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:r(w)}),L&&i&&s.jsx("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:$=>{$.preventDefault(),$.stopPropagation(),i(e.conversation)},"aria-label":u("mobileInbox.openMeshGraphFor",{title:w}),title:u("mobileInbox.openLiveMeshGraph"),children:s.jsx(Zt,{size:13})})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>n(e.conversation),onContextMenu:P,type:"button",children:[s.jsx("div",{className:"flex items-center gap-2 pr-[124px]",children:s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${b}`,children:w})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${N}`,children:[s.jsx("span",{className:"truncate",children:x}),s.jsx(ca,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),f?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${M} animate-pulse`,children:u("mobileInbox.reconnectingItem")})]}):v?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:u("mobileInbox.connectingItem")})]}):j==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:M,children:u("mobileInbox.actionNeeded")})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${S}`,children:e.preview})]}),s.jsxs("div",{className:"mobile-inbox-corner-actions absolute top-3 right-3 flex items-center gap-1.5",children:[R&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${I}`,children:du(e.timestamp)}),k&&s.jsx("span",{className:"rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:u("mobileInbox.done")}),p&&s.jsx("button",{type:"button",className:`mobile-inbox-mute-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors ${d?"border-amber-500/60 bg-amber-500 text-white hover:bg-amber-600":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:$=>{$.preventDefault(),$.stopPropagation(),p()},"aria-label":d?u("mobileInbox.unmute",{title:w}):u("mobileInbox.mute",{title:w}),title:u(d?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:d?s.jsx(Qd,{size:13}):s.jsx(Nr,{size:13})}),a&&s.jsx("button",{type:"button",className:"mobile-inbox-hide-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:$=>{$.preventDefault(),$.stopPropagation(),a()},"aria-label":u("mobileInbox.hideConversationAria",{title:w}),title:u("mobileInbox.hideConversationTitle"),children:s.jsx(Ai,{size:13})}),o&&s.jsx("button",{type:"button",className:"mobile-inbox-stop-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-status-error/30 bg-bg-primary/70 text-status-error transition-colors hover:border-status-error/60 hover:bg-status-error/10",onClick:$=>{$.preventDefault(),$.stopPropagation(),o()},"aria-label":u("mobileInbox.stopSessionAria",{title:w}),title:u("mobileInbox.stopSessionTitle"),children:s.jsx(Nt,{size:13})})]})]})},e.conversation.tabKey)}function Fc({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 Ej({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:d,sendDaemonCommand:p,onOpenConversation:u,onShowAllHidden:m,onHideConversation:h,onOpenMeshGraph:g,onStopCli:k,onOpenNewSession:f,onOpenMachine:v,onOpenSettings:w,onSectionChange:x,wsStatus:j="connected",isStandalone:C=!1,onCollectChatDebugBundle:y,isConversationMuted:b,onToggleMuteConversation:N}){const{t:S}=Pt(),[I,R]=l.useState(null),L=j==="disconnected"||j==="reconnecting"||j==="offline"||j==="auth_failed",M=i.length>0,P=t.length>0||r.length>0||n.length>0||a.length>0,$=S(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),Y=C?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",_=C?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",H=l.useCallback(async T=>{const A=Ks(T);if(!A)return;const E=Array.isArray(T.messages)?T.messages:[],z=Hu({activeConv:T,visibleMessages:E,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:E.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),G=await p(A,"get_chat_debug_bundle",{...Ws(T),delivery:"daemon_file",frontendSnapshot:z}),re=Zr(G),X=Uu(re),te=await Ku(X);te==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ut.showToast(Wu(re,{locatorCopyStatus:te}),te==="failed"?"warning":"success")},[d,p]),W=y||H,B=l.useCallback(()=>{I&&(h==null||h(I),R(null))},[I,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 ${Y}`,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:$}),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(Nr,{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(ja,{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:L?s.jsx(Or,{icon:s.jsx(Fc,{}),title:S(j==="offline"?"mobileInbox.networkOffline":j==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:S(j==="offline"?"mobileInbox.waitingForNetwork":j==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):i.length===0?s.jsx(Or,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:S(C?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:S(C?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!C&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Jp,{})})}):s.jsx(rr,{children:i.map((T,A)=>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] ${A>0?"border-t border-border-subtle/70":""}`,onClick:()=>v(T.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(T.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:T.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:T.unread>0?s.jsx("span",{className:"text-accent-primary",children:S("mobileInbox.newCount",{count:T.unread})}):T.total>0?S("mobileInbox.chatCount",{count:T.total}):S("mobileInbox.idle")})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:T.subtitle}),T.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[S("mobileInbox.chatCount",{count:T.total}),T.unread>0?S("mobileInbox.unreadSuffix",{count:T.unread}):""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:S("mobileInbox.noActiveChats")})]})]},T.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(Ln,{title:S("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(rr,{children:t.map((T,A)=>s.jsx("div",{className:A>0?"border-t border-border-subtle/70":"",children:s.jsx(Rn,{item:T,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:h?()=>R(T.conversation):void 0,onRequestStopCli:k?()=>k(T.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:W,isMuted:b==null?void 0:b(T.conversation),onToggleMute:N?()=>N(T.conversation):void 0})},T.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(Ln,{title:S("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(rr,{children:r.map((T,A)=>s.jsx("div",{className:A>0?"border-t border-border-subtle/70":"",children:s.jsx(Rn,{item:T,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:h?()=>R(T.conversation):void 0,onRequestStopCli:k?()=>k(T.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:W,isMuted:b==null?void 0:b(T.conversation),onToggleMute:N?()=>N(T.conversation):void 0})},T.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(Ln,{title:S("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(rr,{children:n.map((T,A)=>s.jsx("div",{className:A>0?"border-t border-border-subtle/70":"",children:s.jsx(Rn,{item:T,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:h?()=>R(T.conversation):void 0,onRequestStopCli:k?()=>k(T.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:W,isMuted:b==null?void 0:b(T.conversation),onToggleMute:N?()=>N(T.conversation):void 0})},T.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(Ln,{title:S("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(rr,{children:a.map((T,A)=>s.jsx("div",{className:A>0?"border-t border-border-subtle/70":"",children:s.jsx(Rn,{item:T,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:h?()=>R(T.conversation):void 0,onRequestStopCli:k?()=>k(T.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:W,isMuted:b==null?void 0:b(T.conversation),onToggleMute:N?()=>N(T.conversation):void 0})},T.conversation.tabKey))}):P?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:S("mobileInbox.allCaughtUp")}):L?s.jsx(Or,{icon:s.jsx(Fc,{size:28}),title:S("mobileInbox.connecting"),subtitle:S("mobileInbox.connectingSubtitle")}):M?s.jsx(Or,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(Zs,{size:20})}),title:S("mobileInbox.noConversations"),subtitle:pp,children:f&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:f,"aria-label":fs,title:fs,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:fs})]})}):s.jsx(Or,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:S("mobileInbox.noMachinesConnected"),subtitle:S("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&o.length>0&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(rr,{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:S("mobileInbox.hiddenTabs")}),s.jsx("div",{className:"mt-0.5 text-[13px] text-text-muted",children:S("mobileInbox.collapsedCount",{count:o.length})})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:m,children:S("mobileInbox.restoreAll")})]})})})]}),e==="chats"&&f&&P&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:f,"aria-label":fs,title:fs,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"})]})}),I&&s.jsx($j,{conversation:I,onCancel:()=>R(null),onConfirm:B}),s.jsx(Xp,{section:e,onSectionChange:x})]})}function Bj(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 Qp(e){const t=[e.workspace||"Workspace unknown"],r=Js(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Bj(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function nl({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[u,m]=l.useState(r);l.useEffect(()=>{m(r)},[r]);const h=xj(r),g=u.trim();return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] 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(Nt,{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:u,onChange:k=>m(k.target.value),onKeyDown:k=>{k.key!=="Enter"||!g||a||(k.preventDefault(),d(g))},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:()=>{!g||a||d(g)},disabled:!g||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(k=>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(k.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(br,{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:k.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:k.path})]})]},k.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(g||r),disabled:!g&&!r||a,children:i})]})]})})}function Zp({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:i="Launch",busyLabel:c="Launching…",busy:d=!1,showArgsInput:p,argsValue:u,onArgsChange:m,showModelInput:h,modelValue:g,onModelChange:k,historyProviderNode:f,onConfirm:v,onCancel:w}){const x=n==null?void 0:n.find(j=>j.key===a);return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] 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:w,"aria-label":"Close launch confirmation",children:s.jsx(Nt,{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:j=>o(j.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(j=>s.jsx("option",{value:j.key,children:j.label},j.key))}),(x==null?void 0:x.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:x.description})]}),f,r.map(j=>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:j.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:j.value})]},`${j.label}:${j.value}`)),h&&k&&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:g||"",onChange:j=>k(j.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&&m&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:u||"",onChange:j=>m(j.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:w,disabled:d,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:v,disabled:d,children:[s.jsx(Xd,{size:14}),d?c:i]})]})]})})}function Oc(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function em(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?"⭐ ":""}${Oc(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:Oc(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 Fj(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Oj(e){return[Fj(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Hj(e){return e.lastLaunchedAt?Sa(e.lastLaunchedAt):""}function tm(e){return{metaText:Oj(e),updatedLabel:Hj(e)}}function xo(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function Wj({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var tt,qe,ke,ot;const i=Ar(),[c,d]=l.useState(!1),p=(((tt=e.detectedIdes)==null?void 0:tt.length)||0)>0,u=l.useMemo(()=>(e.workspaces||[]).map(Ie=>({id:Ie.id,path:Ie.path,label:Ie.label})),[e]),m=e.defaultWorkspaceId||null,[h,g]=l.useState(m||((qe=u[0])==null?void 0:qe.id)||""),[k,f]=l.useState(""),[v,w]=l.useState(""),[x,j]=l.useState([]),[C,y]=l.useState(!1),[b,N]=l.useState(""),[S,I]=l.useState(!1),[R,L]=l.useState(xo(p,t.length,r.length)),M=l.useRef(null),[P,$]=l.useState(null),Y=l.useRef("__home__"),[_,H]=l.useState("__home__"),[W,B]=l.useState(""),[T,A]=l.useState(""),[E,z]=l.useState(""),[G,re]=l.useState([]),[X,te]=l.useState(()=>Bt().textQuery),[J,F]=l.useState(()=>Bt().workspaceQuery),[K,fe]=l.useState(()=>Bt().modelQuery),[be,oe]=l.useState(()=>Bt().resumableOnly),[je,ge]=l.useState(()=>Bt().sortMode),[we,me]=l.useState(!1),[U,O]=l.useState(!1),Z=l.useRef(null),V=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const he=h==="__custom__"?k.trim():((ke=u.find(Ie=>Ie.id===h))==null?void 0:ke.path)||"",le=h==="__custom__"&&!!he&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),D=h!=="__custom__"&&((ot=u.find(Ie=>Ie.id===h))==null?void 0:ot.path)||"",de=l.useMemo(()=>(e.recentLaunches||[]).map(Ie=>Ie.workspace),[e]),Se=l.useCallback(async Ie=>{y(!0),N("");try{const it=await a(Ie);w(it.path),f(it.path),j(it.directories)}catch(it){N(it instanceof Error?it.message:"Could not load folder")}finally{y(!1)}},[a]),ue=l.useCallback(()=>{var it;g("__custom__"),I(!0);const Ie=tl(e.platform,el(k.trim(),D,de,e.defaultWorkspacePath,(it=u.find(ct=>ct.id===m))==null?void 0:it.path,u.map(ct=>ct.path)));Se(Ie)},[k,m,Se,de,D,e.platform,u]),q=l.useCallback(Ie=>{if(Ie!=null&&Ie.workspaceId){g(Ie.workspaceId),f("");return}if(Ie!=null&&Ie.workspacePath){g("__custom__"),f(Ie.workspacePath);return}g(""),f("")},[]),ve=l.useCallback(Ie=>{if(g(Ie),Ie==="__custom__"){ue();return}f("")},[ue]),Ae=l.useCallback(Ie=>{g("__custom__"),f(Ie)},[]),Ne=l.useCallback((Ie,it)=>{M.current=it,Y.current=Ie.selectedWorkspaceKey||"__home__",H(Ie.selectedWorkspaceKey||"__home__"),B(Ie.initialArgs||""),A(Ie.initialModel||""),z(""),re([]);const ct=Ie.providerType?`${e.id}:${Ie.providerType}`:null;if(X0(V.current,ct)){const Ze=Bt();te(Ze.textQuery),F(Ze.workspaceQuery),fe(Ze.modelQuery),oe(Ze.resumableOnly),ge(Ze.sortMode)}V.current=ct,$(Ie),Ie.providerType&&o&&(me(!0),o(Ie.providerType).then(Ze=>re(Ze||[])).catch(Ze=>console.warn("Failed to load saved sessions",Ze)).finally(()=>me(!1)))},[o,e.id]),Ke=l.useMemo(()=>mp(G,{textQuery:X,workspaceQuery:J,modelQuery:K,resumableOnly:be,sortMode:je}),[K,be,G,je,X,J]);l.useEffect(()=>{E&&(Ke.some(Ie=>Ie.providerSessionId===E)||z(""))},[Ke,E]);const ie=l.useCallback(()=>{M.current&&(O(!0),M.current().finally(()=>{M.current=null,O(!1),$(null)}))},[]),Fe=l.useCallback(()=>{M.current=null,$(null)},[]),$e=l.useCallback(Ie=>{Y.current=Ie,H(Ie)},[]);return l.useEffect(()=>{var Ie;Z.current!==e.id&&(Z.current=e.id,g(m||((Ie=u[0])==null?void 0:Ie.id)||"__custom__"),f(""),w(""),j([]),N(""),I(!1),te(Bt().textQuery),F(Bt().workspaceQuery),fe(Bt().modelQuery),oe(Bt().resumableOnly),ge(Bt().sortMode),V.current=null,L(xo(p,t.length,r.length)))},[r.length,t.length,m,p,e.id,u]),l.useEffect(()=>{var Ie;h!=="__custom__"&&(h&&u.some(it=>it.id===h)||g(m||((Ie=u[0])==null?void 0:Ie.id)||"__custom__"))},[m,h,u]),l.useEffect(()=>{R==="ide"&&p||R==="cli"&&t.length>0||R==="acp"&&r.length>0||L(xo(p,t.length,r.length))},[R,r.length,t.length,p]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:p,workspaceRows:u,defaultWorkspaceId:m,workspaceChoice:h,customWorkspacePath:k,browseCurrentPath:v,browseDirectories:x,browseBusy:C,browseError:b,browseDialogOpen:S,activeLauncherKind:R,launchConfirm:P,launchConfirmWorkspaceKeyRef:Y,launchConfirmWorkspaceKey:_,launchConfirmArgs:W,launchConfirmModel:T,launchConfirmResumeId:E,launchConfirmSavedSessions:G,launchConfirmTextFilter:X,launchConfirmWorkspaceFilter:J,launchConfirmModelFilter:K,launchConfirmResumableOnly:be,launchConfirmSortMode:je,filteredLaunchConfirmSavedSessions:Ke,launchConfirmSessionsLoading:we,launchConfirmBusy:U,resolvedWorkspacePath:he,canCreateMissingWorkspace:le,openBrowseDialog:ue,loadBrowsePath:Se,handleWorkspaceChoiceChange:ve,chooseCustomWorkspacePath:Ae,setCustomWorkspacePath:f,setBrowseDialogOpen:I,setActiveLauncherKind:L,openLaunchConfirm:Ne,handleConfirmLaunch:ie,closeLaunchConfirm:Fe,setWorkspaceSelectionFromOption:q,setLaunchConfirmWorkspaceKeyAndSync:$e,setLaunchConfirmArgs:B,setLaunchConfirmModel:A,setLaunchConfirmResumeId:z,setLaunchConfirmTextFilter:te,setLaunchConfirmWorkspaceFilter:F,setLaunchConfirmModelFilter:fe,setLaunchConfirmResumableOnly:oe,setLaunchConfirmSortMode:ge}}function Kj({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:d,section:p,showBottomNav:u,onBack:m,onSectionChange:h,onOpenConversation:g,onOpenRecent:k,onOpenMachineDetails:f,onMachineUpgrade:v,onLaunchDetectedIde:w,onAddWorkspace:x,onBrowseDirectory:j,onLaunchWorkspaceProvider:C,onListSavedSessions:y}){const b=_=>_==="ide"?"IDE":_==="cli"?"CLI":"ACP",N=r.slice(0,4),S=t.slice(0,3),I=Wj({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:c,onBrowseDirectory:j,onListSavedSessions:y}),R=l.useMemo(()=>N.map(_=>{const{metaText:H,updatedLabel:W}=tm(_);return{key:`recent-launch:${_.id}`,primary:_.label,secondary:H,updatedLabel:W,onClick:()=>{const{options:B,selectedKey:T}=em({machine:{workspaces:I.workspaceRows,defaultWorkspaceId:I.defaultWorkspaceId},currentWorkspacePath:_.workspace});I.openLaunchConfirm({title:_.kind==="ide"?da("restart-ide",_.label):_.providerSessionId?fp(_.label):da("start-fresh",_.label),description:_.kind==="ide"?ua("restart-ide"):_.providerSessionId?xp():ua("start-fresh"),confirmLabel:_.kind==="ide"?pa("restart-ide"):_.providerSessionId?ai(!0):pa("start-fresh"),busyLabel:_.kind==="ide"?ma("restart-ide"):_.providerSessionId?hp(!0):ma("start-fresh"),workspaceOptions:B,selectedWorkspaceKey:T,details:[{label:"Mode",value:b(_.kind)},..._.providerType?[{label:"Provider",value:_.providerType}]:[]]},async()=>{const A=B.find(E=>E.key===I.launchConfirmWorkspaceKeyRef.current);I.setWorkspaceSelectionFromOption(A),await k({..._,workspace:(A==null?void 0:A.workspacePath)??null})})}}}),[I,k,N]),L=l.useMemo(()=>S.map(_=>({key:`recent-chat:${_.conversation.tabKey}`,primary:xt(_.conversation),secondary:I0(_.conversation,{timestampLabel:_.timestamp?du(_.timestamp):null}),unread:_.unread,onClick:()=>g(_.conversation)})),[g,S]),M=I.showAllRecent?R:R.slice(0,4),P=R.length>0,$=L.length>0,Y=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 ${Y} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:s.jsx(Ni,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:es(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(_=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${_.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:_.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:_.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:_.secondary})]},_.key))})]}),P&&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:M.map(_=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:_.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:_.primary}),_.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:_.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:_.secondary})]},_.key))}),R.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>I.setShowAllRecent(_=>!_),children:I.showAllRecent?"Show fewer":`Show ${R.length-4} more`})})]}),!1,s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:v,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",i]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:f,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),I.browseDialogOpen&&s.jsx(nl,{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:_=>{I.loadBrowsePath(_)},onConfirm:_=>{I.chooseCustomWorkspacePath(_),I.setBrowseDialogOpen(!1)}}),I.launchConfirm&&s.jsx(Zp,{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?ai(!!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:zi()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:I.launchConfirmTextFilter,onChange:_=>I.setLaunchConfirmTextFilter(_.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:I.launchConfirmWorkspaceFilter,onChange:_=>I.setLaunchConfirmWorkspaceFilter(_.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:I.launchConfirmModelFilter,onChange:_=>I.setLaunchConfirmModelFilter(_.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading}),s.jsxs("select",{value:I.launchConfirmSortMode,onChange:_=>I.setLaunchConfirmSortMode(_.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled: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:_=>I.setLaunchConfirmResumableOnly(_.target.checked),disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:I.launchConfirmResumeId,onChange:_=>I.setLaunchConfirmResumeId(_.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:ev()}),I.filteredLaunchConfirmSavedSessions.map(_=>s.jsxs("option",{value:_.providerSessionId,disabled:!_.canResume,children:[_.title||_.providerSessionId," ",_.canResume?"":"(workspace missing)"]},_.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 _=I.filteredLaunchConfirmSavedSessions.find(W=>W.providerSessionId===I.launchConfirmResumeId);if(!_)return null;const H=Qp(_);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:H.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:H.providerSessionId}),s.jsx("div",{className:"mt-1",children:H.metaLine}),H.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:H.updatedLabel}),H.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:H.preview})]})})()]}),onConfirm:I.handleConfirmLaunch,onCancel:I.closeLaunchConfirm}),u&&s.jsx(Xp,{section:p,onSectionChange:h})]})}const Hc=8e3;function Uj(e){const t=e&&typeof e=="object"&&"result"in e?e.result:e,r=t&&typeof t=="object",n=r&&t.success===!1,a=r&&t.mirrorStale===!0;return!n&&!a?{confirmed:!0}:{confirmed:!1,reason:n&&typeof t.error=="string"?t.error:a?"the coordinator did not confirm the change":"command was rejected"}}function sm(e,t,r){const n=l.useRef(new Map),[,a]=l.useState(0),o=l.useCallback(()=>a(g=>g+1),[]);l.useEffect(()=>{const g=n.current;if(g.size===0)return;const k=Date.now();let f=!1;for(const[v,w]of g){const x=e.get(v),j=w.muted===void 0||(x?x.muted===w.muted:!1),C=w.hidden===void 0||(x?x.surfaceHidden===w.hidden:!1),y=k-w.at>Hc;(j&&C||y)&&(g.delete(v),f=!0)}f&&o()},[e,o]),l.useEffect(()=>{if(n.current.size===0)return;const g=setInterval(()=>{const k=n.current,f=Date.now();let v=!1;for(const[w,x]of k)f-x.at>Hc&&(k.delete(w),v=!0);v&&o(),k.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,k)=>{const f=n.current.get(g);n.current.set(g,{...f,...k,at:Date.now()}),o()},[o]),c=l.useCallback(g=>{const k=g.sessionId,f=k?n.current.get(k):void 0;return(f==null?void 0:f.muted)!==void 0?f.muted:Ls(g,e).muted},[e]),d=l.useCallback(g=>{const k=g.sessionId,f=k?n.current.get(k):void 0;return(f==null?void 0:f.hidden)!==void 0?f.hidden:Ls(g,e).surfaceHidden},[e]),p=l.useCallback((g,k)=>{const f=Rs(g),v=g.sessionId;!f||!v||(i(v,k),t(f,"set_conversation_prefs",{sessionId:v,...k,...Ta(g)}).then(w=>{const x=Uj(w);x.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",x.reason),n.current.delete(v),o(),r==null||r(`Couldn't update conversation — ${x.reason}`))}).catch(w=>{console.warn("[conversation-prefs] set_conversation_prefs failed",w),n.current.delete(v),o();const x=w instanceof Error?w.message:String(w??"the daemon is unreachable");r==null||r(`Couldn't update conversation — ${x}`)}))},[t,i,o,r]),u=l.useCallback(g=>{p(g,{muted:!c(g)})},[p,c]),m=l.useCallback((g,k)=>{p(g,{hidden:k})},[p]),h=l.useCallback(g=>{p(g,{hidden:!d(g)})},[p,d]);return{isMuted:c,isHidden:d,toggleMute:u,setHidden:m,toggleHidden:h}}function Yn(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Gj(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:Yn(e)}function zj(e){var n,a,o;const t=((n=e.p2p)==null?void 0:n.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":!(!!((a=e.p2p)!=null&&a.available)||!!((o=e.p2p)!=null&&o.state))&&e.status&&e.status!=="offline"?"Connected":"Offline"}function Vj(e,t){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:Js(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):t.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var i;const a=on(n)?"cli":pr(n)?"acp":"ide",o=Js(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((i=n.activeChat)==null?void 0:i.title)||(on(n)?n.cliName||n.type:pr(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:pr(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 qj(e,t){const r=new Map;for(const n of t){const a=Rs(n.conversation),o=r.get(a);o?o.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],o=[...a].sort((m,h)=>h.timestamp-m.timestamp)[0]||null,i=(o==null?void 0:o.conversation)||null,c=Qo(n),d=a.filter(m=>m.unread||m.requiresAction).length,p=zj(n),u=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:es(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:d,total:a.length,latestConversation:i,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:c,preview:i?A0(i,Zu(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 Yj(e){return e==="chat"}function Pn(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 Jj({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:g,setSelectedTabKey:k,setScreen:f,setSelectedMachineId:v,setSection:w,setMachineBackTarget:x,resetMachineAction:j}){const C=l.useRef(null),y=l.useCallback(b=>{if(!(b!=null&&b.sessionId))return;const N=Ls(b,i),S=Math.max(Date.now(),Vs(b),N.lastUpdated||0);Pn("mark_read:start",{tabKey:b.tabKey,sessionId:b.sessionId,displayPrimary:xt(b),inboxBucket:N.inboxBucket,unread:N.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:Vs(b),readAt:S}),c(Rs(b)||b.routeId,"mark_session_seen",{sessionId:b.sessionId,providerSessionId:b.providerSessionId,seenAt:S,completionMarker:N.completionMarker}).then(I=>{Pn("mark_read:result",{tabKey:b.tabKey,sessionId:b.sessionId,result:I})}).catch(I=>{Pn("mark_read:error",{tabKey:b.tabKey,sessionId:b.sessionId,error:I instanceof Error?I.message:String(I)})})},[i,c]);return l.useEffect(()=>{var N;if(!n){Yj(o)&&f("inbox"),k(((N=e[0])==null?void 0:N.tabKey)||null),C.current=null;return}if(o!=="chat"){C.current=null;return}const b=`${n.tabKey}:${n.sessionId||""}`;C.current!==b&&(C.current=b,y(n))},[e,y,o,n,f,k]),l.useEffect(()=>{if(!d)return;const b=e.find(N=>N.tabKey===d);b&&(k(b.tabKey),f("chat"),p==null||p())},[e,p,d,f,k]),l.useEffect(()=>{if(!u)return;const b=t.find(N=>N.id===u);b&&(v(b.id),j(),w("machines"),x("inbox"),f("machine"),m==null||m())},[t,m,u,j,x,f,w,v]),l.useEffect(()=>{h&&(w(h),f("inbox"),g==null||g())},[g,h,f,w]),l.useEffect(()=>{const b=r.filter(N=>N.inboxBucket==="task_complete"||N.unread);b.length!==0&&Pn("inbox_state",{screen:o,selectedTabKey:a,items:b.map(N=>{const S=Ls(N.conversation,i);return{liveState:S,tabKey:N.conversation.tabKey,sessionId:N.conversation.sessionId,displayPrimary:xt(N.conversation),serverBucket:S.inboxBucket,computedBucket:N.inboxBucket,serverUnread:S.unread,computedUnread:N.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:Vs(N.conversation)}})})},[r,i,o,a]),{markConversationRead:y}}function Xj(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 Qj(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Zj({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const{launchCli:a}=wa(),[o,i]=l.useState("idle"),[c,d]=l.useState(""),[p,u]=l.useState(null),m=l.useCallback(()=>{i("idle"),d(""),u(null)},[]),h=l.useCallback(async(j,C,y)=>{var b;try{i("loading"),d(`Launching ${C}…`);const N={ideType:C,enableCdp:!0};(b=y==null?void 0:y.workspacePath)!=null&&b.trim()&&(N.workspace=y.workspacePath.trim()),await e(j,"launch_ide",N),i("done"),d(`${C} launch requested`)}catch(N){i("error"),d(N instanceof Error?N.message:"Launch IDE failed"),console.error("Launch IDE failed",N)}},[e]),g=l.useCallback(async(j,C,y)=>{if(C.trim())try{i("loading"),d(y!=null&&y.createIfMissing?"Creating folder…":"Saving workspace…");const b=await e(j,"workspace_add",{path:C.trim(),createIfMissing:(y==null?void 0:y.createIfMissing)===!0});if(b!=null&&b.success){i("done"),d(y!=null&&y.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((b==null?void 0:b.error)||"Could not save workspace")}catch(b){i("error"),d(b instanceof Error?b.message:"Could not save workspace")}},[e]),k=l.useCallback(async j=>{var C,y,b,N,S,I;try{i("loading"),d("Starting daemon upgrade…");const R=await e(j,"daemon_upgrade",{});if((C=R==null?void 0:R.result)!=null&&C.alreadyLatest){i("done"),d(`Already on v${((y=R==null?void 0:R.result)==null?void 0:y.version)||"latest"}.`);return}if((b=R==null?void 0:R.result)!=null&&b.upgraded||(N=R==null?void 0:R.result)!=null&&N.success){i("done"),d(`Upgrade to v${((S=R==null?void 0:R.result)==null?void 0:S.version)||"latest"} started. Daemon is restarting…`);return}i("error"),d(((I=R==null?void 0:R.result)==null?void 0:I.error)||"Upgrade failed")}catch(R){i("error"),d(R instanceof Error?R.message:"Upgrade failed")}},[e]),f=l.useCallback(async(j,C,y,b)=>{var I,R,L;const N=Date.now(),S={machineId:j,kind:C,providerType:y,workspaceId:(b==null?void 0:b.workspaceId)||null,workspacePath:(b==null?void 0:b.workspacePath)||null,resumeSessionId:(b==null?void 0:b.resumeSessionId)||null,startedAt:N};try{i("loading"),d(`Launching ${y}…`),u(S);const M={cliType:y};(I=b==null?void 0:b.workspacePath)!=null&&I.trim()?M.dir=b.workspacePath.trim():b!=null&&b.workspaceId&&(M.workspaceId=b.workspaceId),b!=null&&b.resumeSessionId&&(M.resumeSessionId=b.resumeSessionId),(R=b==null?void 0:b.args)!=null&&R.trim()&&(M.cliArgs=b.args.trim().split(/\s+/).filter(Boolean)),(L=b==null?void 0:b.model)!=null&&L.trim()&&(M.initialModel=b.model.trim());const P=await a(j,M),$=(P==null?void 0:P.result)||P,Y=($==null?void 0:$.sessionId)||($==null?void 0:$.id);if(P!=null&&P.success&&Y){u(null),i("done"),d(`${y} launched`),t(dn(Y));return}if(P!=null&&P.success){i("loading"),d(`${y} launch requested — waiting for session…`);return}u(null),i("error"),d((P==null?void 0:P.error)||($==null?void 0:$.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(M){if(Qj(M)){i("loading"),d(`${y} launch requested — waiting for session…`);return}u(null),i("error"),d(M instanceof Error?M.message:`Could not launch ${C.toUpperCase()} workspace`)}},[t,e]),v=l.useCallback(async(j,C)=>{try{const y=await e(j,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),b=(y==null?void 0:y.result)??y;return Array.isArray(b==null?void 0:b.sessions)?b.sessions:[]}catch(y){return console.error("Failed to list saved sessions on mobile:",y),[]}},[e]),w=l.useCallback(async(j,C)=>sl(e,j,C),[e]);l.useEffect(()=>{if(!p)return;const j=Wc(p.workspacePath),C=r.find(b=>{var M,P,$,Y;if(!b||b.type==="adhdev-daemon"||Xj(b.daemonId||b.id)!==p.machineId||(b.transport==="acp"?"acp":b.transport==="pty"?"cli":null)!==p.kind||String(b.agentType||b.type||"")!==p.providerType)return!1;const R=String(b.providerSessionId||"");if(p.resumeSessionId&&R)return R===p.resumeSessionId;if(j){const _=Wc(b.workspace||b.runtimeWorkspaceLabel);return _?_===j:!1}return Number(b.lastUpdated||b._lastUpdate||b.timestamp||((Y=($=(P=(M=b.activeChat)==null?void 0:M.messages)==null?void 0:P.at)==null?void 0:$.call(P,-1))==null?void 0:Y.timestamp)||0)>=p.startedAt-5e3});if(!C)return;const y=qp({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:n});y&&(u(null),i("done"),d(`${p.providerType} launched`),t(dn(y)))},[n,r,t,p]),l.useEffect(()=>{if(!p)return;const j=window.setTimeout(()=>{u(C=>!C||C.startedAt!==p.startedAt?C:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(j)},[p]);const x=l.useCallback(async(j,C)=>{if(C.kind==="ide"&&C.providerType){await h(j,C.providerType,{workspacePath:C.workspace||null});return}(C.kind==="cli"||C.kind==="acp")&&C.providerType&&await f(j,C.kind,C.providerType,{workspacePath:C.workspace||null,resumeSessionId:C.providerSessionId||null})},[h,f]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:h,handleAddWorkspace:g,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:f,handleListSavedSessions:v,handleBrowseDirectory:w,handleOpenRecent:x}}function ek({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:d,setMachineBackTarget:p}){const u=l.useCallback(w=>{o(w.tabKey),i("chat"),n(w)},[n,i,o]),m=l.useCallback(w=>{const x=e.find(j=>j.routeId===w.routeId&&j.streamSource==="native");x&&(o(x.tabKey),i("chat"),n(x))},[e,n,i,o]),h=l.useCallback(()=>{n(t),i("inbox")},[n,t,i]),g=l.useCallback((w,x="inbox")=>{c(w),a(),d("machines"),p(x),i("machine")},[a,p,i,d,c]),k=l.useCallback(w=>{const x=Rs(w);x&&g(x,"chat")},[g]),f=l.useCallback(()=>{a(),i(r)},[r,a,i]),v=l.useCallback(w=>{d(w),i("inbox")},[i,d]);return{openConversation:u,openNativeConversation:m,backFromConversation:h,openMachine:g,openConversationMachine:k,backFromMachine:f,changeMachineSection:v}}function jr(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function tk(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function sk({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:g,onOpenHistory:k,onOpenRemote:f,onStopCli:v,wsStatus:w,isConnected:x,onShowAllHiddenConversations:j,onHideConversation:C,onOpenMeshGraph:y,onOpenNewSession:b,liveSessionInboxState:N,setCliViewModeOverrides:S}){const[I,R]=l.useState(()=>{var q;return((q=e[0])==null?void 0:q.tabKey)||null}),[L,M]=l.useState(()=>e[0]?"chat":"inbox"),[P,$]=l.useState("chats"),[Y,_]=l.useState(null),[H,W]=l.useState("inbox"),B=l.useRef([]),T=mn(),A="0.9.82",E=l.useMemo(()=>e.find(q=>q.tabKey===I)||e[0]||null,[e,I]),z=l.useMemo(()=>E?r.find(q=>q.id===E.routeId):void 0,[r,E]),G=l.useMemo(()=>!E||lt(E)||!dt(E)?null:Ir(E),[E]),re=l.useMemo(()=>r.filter(q=>q.type==="adhdev-daemon").sort(Di),[r]),X=l.useMemo(()=>re.find(q=>q.id===Y)||null,[re,Y]),te=_a({sendDaemonCommand:a,activeConv:E||void 0,setActionLogs:o,isStandalone:i}),J=Zj({sendDaemonCommand:a,navigate:T,ides:r,conversations:e}),F=r0(e),K=l.useMemo(()=>e.map(q=>{const ve=L==="chat"&&(E==null?void 0:E.tabKey)===q.tabKey,Ae=Na(q,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ve}),Ne=Vs(q),Ke=Zu(q),ie=op(q,Ke);return{conversation:q,timestamp:Ne,preview:ie,unread:Ae.unread,requiresAction:Ae.requiresAction,isWorking:Ae.isWorking,inboxBucket:Ae.inboxBucket}}),[e,N,L,E,F]),{markConversationRead:fe}=Jj({conversations:e,machineEntries:re,items:K,selectedConversation:E,selectedTabKey:I,screen:L,liveSessionInboxState:N,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:g,setSelectedTabKey:R,setScreen:M,setSelectedMachineId:_,setSection:$,setMachineBackTarget:W,resetMachineAction:J.resetMachineAction}),be=ek({conversations:e,selectedConversation:E,machineBackTarget:H,markConversationRead:fe,resetMachineAction:J.resetMachineAction,setSelectedTabKey:R,setScreen:M,setSelectedMachineId:_,setSection:$,setMachineBackTarget:W}),{isMuted:oe,toggleMute:je}=sm(N,a),ge=l.useMemo(()=>Yn(K.filter(q=>q.requiresAction&&!oe(q.conversation))),[K,oe]),we=l.useMemo(()=>Yn(K.filter(q=>q.unread&&!q.requiresAction&&!oe(q.conversation))),[K,oe]),me=l.useMemo(()=>Gj(K.filter(q=>!q.unread&&!q.requiresAction&&q.isWorking),B.current),[K]);l.useEffect(()=>{B.current=me.map(q=>q.conversation.tabKey)},[me]);const U=l.useMemo(()=>Yn(K.filter(q=>!q.unread&&!q.requiresAction&&!q.isWorking)),[K]),O=l.useMemo(()=>X?K.filter(q=>Rs(q.conversation)===X.id):[],[K,X]),Z=l.useMemo(()=>Vj(X,r),[r,X]),V=(X==null?void 0:X.version)||null,he=!!X&&!!V&&!0&&V!==A,le=l.useMemo(()=>(X==null?void 0:X.availableProviders)||[],[X]),D=l.useMemo(()=>le.filter(q=>jr(q,"cli")).map(q=>({type:q.type,displayName:q.displayName||q.type,icon:q.icon})),[le]),de=l.useMemo(()=>le.filter(q=>jr(q,"acp")).map(q=>({type:q.type,displayName:q.displayName||q.type,icon:q.icon})),[le]),Se=l.useMemo(()=>qj(re,K),[K,re]),ue=l.useCallback(async q=>{X&&await J.handleOpenRecent(X.id,q)},[J,X]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:L==="chat"&&E?s.jsx(Pj,{selectedConversation:E,isAcp:lt(E),isStandalone:i,selectedIdeEntry:z,actionLogs:n,userName:c,isSendingChat:te.isSendingChat,sendFeedbackMessage:te.sendFeedbackMessage,isFocusingAgent:te.isFocusingAgent,handleModalButton:te.handleModalButton,handleRelaunch:te.handleRelaunch,onBack:be.backFromConversation,onOpenNativeConversation:be.openNativeConversation,onOpenMachine:be.openConversationMachine,onOpenHistory:k,onOpenRemote:f,onOpenMeshGraph:y,onStopCli:v,cliViewMode:G,onSetCliViewMode:async q=>{await $p({conversation:E,mode:q,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:S})},handleSendChat:te.handleSendChat,handleForceSendChat:te.handleForceSendChat,handleFocusAgent:te.handleFocusAgent}):L==="machine"&&X?s.jsx(Kj,{selectedMachineEntry:X,selectedMachineConversations:O,selectedMachineRecentLaunches:Z,cliProviders:D,acpProviders:de,selectedMachineNeedsUpgrade:he,appVersion:A,machineAction:J.machineAction,isStandalone:i,section:P,showBottomNav:H==="inbox",onBack:be.backFromMachine,onSectionChange:be.changeMachineSection,onOpenConversation:be.openConversation,onOpenRecent:ue,onOpenMachineDetails:()=>T(`/machines/${X.id}`),onMachineUpgrade:()=>J.handleMachineUpgrade(X.id),onLaunchDetectedIde:(q,ve)=>J.handleLaunchDetectedIde(X.id,q,ve),onAddWorkspace:(q,ve)=>J.handleAddWorkspace(X.id,q,ve),onBrowseDirectory:q=>J.handleBrowseDirectory(X.id,q),onLaunchWorkspaceProvider:(q,ve,Ae)=>J.handleLaunchWorkspaceProvider(X.id,q,ve,Ae),onListSavedSessions:q=>J.handleListSavedSessions(X.id,q)}):s.jsx(Ej,{section:P,attentionItems:ge,unreadItems:we,workingItems:me,completedItems:U,hiddenConversations:t,machineCards:Se,getAvatarText:tk,actionLogs:n,sendDaemonCommand:a,onOpenConversation:be.openConversation,onShowAllHidden:j,onHideConversation:C,onOpenMeshGraph:y,onStopCli:v,onOpenNewSession:b,onOpenMachine:be.openMachine,onOpenSettings:()=>T("/settings"),onSectionChange:$,wsStatus:w,isConnected:x,isStandalone:i,isConversationMuted:oe,onToggleMuteConversation:je})})}function bo(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function rk({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const i=l.useRef(0),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useCallback(()=>{i.current=0,d(!1),u(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const h=l.useCallback(v=>{v.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,d(!0))},[]),g=l.useCallback(v=>{if(!v.dataTransfer.types.includes("text/tab-key"))return;if(v.preventDefault(),!bo(t,r)){u("merge");return}const w=v.currentTarget.getBoundingClientRect(),x=v.clientX-w.left,j=w.width/3;x<j?u("split-left"):x>j*2?u("split-right"):u("merge")},[t,r]),k=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,d(!1),u(null))},[]),f=l.useCallback(v=>{i.current=0,d(!1);const w=v.dataTransfer.getData("text/tab-key"),x=w?e.some(C=>C.tabKey===w):!1,j=p;if(u(null),o(),!!w){if(v.preventDefault(),j==="split-left"&&bo(t,r)){r==null||r(w,"split-left");return}if(j==="split-right"&&bo(t,r)){r==null||r(w,"split-right");return}if(x){a(w);return}n==null||n(w)}},[e,p,t,r,n,a,o]);return{dragOver:c,dropAction:p,resetDragState:m,handleDragEnter:h,handleDragOver:g,handleDragLeave:k,handleDrop:f}}function nk(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 ak({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,i]=l.useState(t??null),[c,d]=l.useState(r??[]),[p,u]=l.useState(null),m=l.useRef(null),h=l.useRef(null),g=l.useRef(n),k=l.useRef(a);l.useEffect(()=>{g.current=n},[n]),l.useEffect(()=>{k.current=a},[a]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{d(N=>{const S=nk(N,e);return S.length===N.length&&S.every((I,R)=>I===N[R])?N:S})},[e]);const f=l.useMemo(()=>{const N=p??c;if(N.length===0)return e;const S=new Map(N.map((I,R)=>[I,R]));return[...e].sort((I,R)=>{const L=S.get(I.tabKey)??999,M=S.get(R.tabKey)??999;return L-M})},[e,p,c]);l.useEffect(()=>{var S,I;if(f.length===0){o!==null&&(i(null),(S=g.current)==null||S.call(g,null));return}if(o&&f.some(R=>R.tabKey===o))return;const N=f[0].tabKey;N!==o&&(i(N),(I=g.current)==null||I.call(g,N))},[f,o]);const v=l.useMemo(()=>f.find(N=>N.tabKey===o),[f,o]),w=l.useCallback(N=>{var S;i(N),(S=g.current)==null||S.call(g,N)},[]),x=l.useCallback((N,S,I)=>{d(R=>{var $;const L=R.filter(Y=>Y!==N),M=L.indexOf(S);if(M<0)return R;const P=I==="left"?M:M+1;return L.splice(P,0,N),($=k.current)==null||$.call(k,L),L}),u(null)},[]),j=l.useCallback((N,S,I)=>{const L=(c.length>0?c:e.map($=>$.tabKey)).filter($=>$!==N),M=L.indexOf(S);if(M<0)return;const P=I==="left"?M:M+1;L.splice(P,0,N),m.current=L,u(L)},[c,e]),C=l.useCallback(()=>{var S;const N=m.current;N&&(d(N),(S=k.current)==null||S.call(k,N))},[]),y=l.useCallback(()=>{m.current=null,u(null)},[]),b=l.useCallback(N=>{d(S=>{var R;const I=S.filter(L=>L!==N);return I.push(N),(R=k.current)==null||R.call(k,I),I})},[]);return{activeTabId:o,activeConv:v,sortedConversations:f,previewOrderRef:m,draggingTabRef:h,selectTab:w,handleTabReorder:x,updatePreviewOrder:j,commitPreviewOrder:C,clearPreviewOrder:y,moveTabToEnd:b,setDraggingTabKey:N=>{h.current=N}}}function ok({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 al({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?pp: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:fs,"aria-label":fs,children:[s.jsx(Ti,{size:14}),s.jsx("span",{children:fs})]})}),i&&s.jsx(Jp,{}),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 rm="adhdev-tab-shortcuts";function nm(){try{return JSON.parse(localStorage.getItem(rm)||"{}")}catch{return{}}}function am({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>nm()),[c,d]=l.useState(null),p=l.useCallback(m=>{const h=[];return m.metaKey&&h.push(a?"⌘":"Meta"),m.ctrlKey&&h.push("Ctrl"),m.altKey&&h.push(a?"⌥":"Alt"),m.shiftKey&&h.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(h.push(m.key.length===1?m.key.toUpperCase():m.key),h.join("+"))},[a]),u=l.useCallback(m=>{i(m);try{localStorage.setItem(rm,JSON.stringify(m))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const m=h=>{if(h.preventDefault(),h.stopPropagation(),h.key==="Escape"){d(null);return}const g=p(h);if(!g)return;const k={...o};for(const[f,v]of Object.entries(k))v===g&&delete k[f];k[c]=g,u(k),d(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,o,u,p]),l.useEffect(()=>{if(!e)return;const m=h=>{if(!(!h.ctrlKey&&!h.metaKey&&!h.altKey)){for(const[g,k]of Object.entries(o))if(t.includes(g)&&p(h)===k){h.preventDefault(),r(),n(g);return}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,o,t,r,n,p]),{isMac:a,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const go=e=>{e.preventDefault()},ik=l.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:d,onSelectTab:p,onConversationActivated:u,onPreviewReorder:m,onReorderTab:h,onCommitPreviewOrder:g,onClearPreviewOrder:k,onDragStateReset:f,onDragTabKeyChange:v,onReceiveTab:w,onOpenContextMenu:x,longPressTimer:j,isGroupActive:C}){const y=Cr(t),b=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",N=y.isReconnecting,S=N0(t),I=C0(t),R=ap(t),L=l.useCallback(T=>{c.current=t.tabKey,v(t.tabKey),T.dataTransfer.setData("text/tab-key",t.tabKey),T.dataTransfer.effectAllowed="move"},[t.tabKey,c,v]),M=l.useCallback(()=>{c.current=null,v(null),g(),k(),f()},[c,v,g,k,f]),P=l.useCallback(T=>{const A=c.current;if(!(!A||A===t.tabKey)&&T.dataTransfer.types.includes("text/tab-key")){T.preventDefault(),T.stopPropagation();const E=T.currentTarget.getBoundingClientRect(),z=T.clientX<E.left+E.width/2?"left":"right";m(A,t.tabKey,z)}},[t.tabKey,c,m]),$=l.useCallback(T=>{T.preventDefault(),T.stopPropagation();const A=T.dataTransfer.getData("text/tab-key");if(A&&A!==t.tabKey){const E=T.currentTarget.getBoundingClientRect(),z=T.clientX<E.left+E.width/2?"left":"right";i.includes(A)?h(A,t.tabKey,z):w&&w(A)}k()},[t.tabKey,i,h,w,k]),Y=l.useCallback(T=>{T.stopPropagation(),d(),p(t.tabKey),u(t)},[t,u,d,p]),_=l.useCallback(T=>{T.preventDefault(),x(T.clientX,T.clientY,t.tabKey)},[t.tabKey,x]),H=l.useCallback(T=>{const A=T.touches[0];j.current=setTimeout(()=>{x(A.clientX,A.clientY,t.tabKey)},600)},[t.tabKey,j,x]),W=l.useCallback(()=>{j.current&&clearTimeout(j.current)},[j]),B=["adhdev-dockview-tab",b,r&&"is-active",C&&"is-group-active",N&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:B,draggable:!0,onDragStart:L,onDragEnd:M,onDragOver:P,onDrop:$,onClick:Y,onContextMenu:_,onTouchStart:H,onTouchEnd:W,onTouchMove:W,style:{position:"relative",cursor:"pointer",opacity:n?.4:void 0},children:[R&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-badge pointer-events-none absolute top-0.5 right-0.5 text-text-muted",title:"Mesh chat","aria-label":"Mesh chat",children:s.jsx(Zt,{size:11})}),a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:y.isGenerating?s.jsx("div",{className:"tab-spinner"}):y.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):y.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:xt(t),children:xt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:Us(t)}):y.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[Us(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:Us(t)}),s.jsx(ca,{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 lk({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:h,onDragTabKeyChange:g,onReceiveTab:k,onHideTab:f,isGroupActive:v,allowTabShortcuts:w=!0}){const[x,j]=l.useState(null),C=l.useRef(null),y=l.useRef(null),b=l.useMemo(()=>e.map(P=>P.tabKey),[e]);hn("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(x==null?void 0:x.tabKey)||null});const{isMac:N,tabShortcuts:S,shortcutListening:I,setShortcutListening:R,saveShortcuts:L}=am({enabled:w,sortedTabKeys:e.map(P=>P.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!x)return;const P=$=>{const Y=document.querySelector("[data-pane-context-menu]");Y&&Y.contains($.target)||j(null)};return window.addEventListener("mousedown",P,!0),()=>window.removeEventListener("mousedown",P,!0)},[x]),l.useEffect(()=>{const P=y.current;if(!P)return;const $=Y=>{Math.abs(Y.deltaY)<=Math.abs(Y.deltaX)||(Y.preventDefault(),P.scrollLeft+=Y.deltaY)};return P.addEventListener("wheel",$,{passive:!1}),()=>P.removeEventListener("wheel",$)},[]);const M=l.useCallback((P,$,Y)=>{j({x:P,y:$,tabKey:Y})},[]);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:y,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(P=>s.jsx(ik,{conv:P,isActive:t===P.tabKey,isDraggedTab:a.current===P.tabKey,isTaskCompleteUnread:n.has(P.tabKey),shortcut:w?S[P.tabKey]:void 0,conversationKeys:b,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:h,onDragTabKeyChange:g,onReceiveTab:k,onOpenContextMenu:M,longPressTimer:C,isGroupActive:v},P.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),x&&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:x.x,top:x.y},children:[w&&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:go,onClick:P=>{P.stopPropagation(),R(x.tabKey),j(null)},children:["⌨ ",S[x.tabKey]?`Change shortcut (${S[x.tabKey]})`:"Set shortcut"]}),S[x.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:go,onClick:()=>{const P={...S};delete P[x.tabKey],L(P),j(null)},children:"✕ Remove shortcut"})]}),f&&s.jsxs(s.Fragment,{children:[w&&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:go,onClick:()=>{f(x.tabKey),j(null)},children:"🚫 Hide from Dashboard"})]})]}),w&&I&&s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>R(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:P=>P.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",N?"⌘+1":"Ctrl+1",", ",N?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function ck({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,userName:d,groupIndex:p,onFocus:u,isSplitMode:m,numGroups:h,onMoveTab:g,onReceiveTab:k,style:f,onActiveTabChange:v,initialActiveTabId:w,initialTabOrder:x,onTabOrderChange:j,onHideTab:C,isFocused:y,allowTabShortcuts:b=!0,onOpenNewSession:N,liveSessionInboxState:S}){const{sendCommand:I}=bt(),R=l.useRef(null),{activeTabId:L,activeConv:M,sortedConversations:P,draggingTabRef:$,selectTab:Y,handleTabReorder:_,updatePreviewOrder:H,commitPreviewOrder:W,clearPreviewOrder:B,moveTabToEnd:T,setDraggingTabKey:A}=ak({conversations:e,initialActiveTabId:w,initialTabOrder:x,onActiveTabChange:v,onTabOrderChange:j}),E=_a({sendDaemonCommand:a,activeConv:M,setActionLogs:o,isStandalone:i}),{dragOver:z,dropAction:G,resetDragState:re,handleDragEnter:X,handleDragOver:te,handleDragLeave:J,handleDrop:F}=rk({conversations:e,numGroups:h,onMoveTab:g,onReceiveTab:k,onOwnTabDrop:T,onClearPreviewOrder:B}),K=M&&!lt(M)&&Ir(M)==="terminal",fe=l.useMemo(()=>M?t.find(ge=>ge.id===M.routeId):void 0,[t,M]),be=l.useMemo(()=>M?n.filter(ge=>ge.routeId===M.tabKey):[],[n,M]),oe=l.useMemo(()=>new Set(P.filter(ge=>Rx(ge,S,{isOpenConversation:ge.tabKey===L})).map(ge=>ge.tabKey)),[L,S,P]);hn("PaneGroup",{groupIndex:p,conversationCount:e.length,activeTabId:L,dragOver:z});const je=l.useCallback(ge=>{ge.streamSource==="agent-stream"&&ge.agentType&&I(ge.routeId,Ou(),{agentType:ge.agentType,...ge.sessionId&&{targetSessionId:ge.sessionId}}).catch(()=>{})},[I]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...f,outline:z?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(lk,{conversations:P,activeTabId:L,groupIndex:p,numGroups:h,unreadTabKeys:oe,draggingTabRef:$,onFocus:u,onSelectTab:Y,onConversationActivated:je,onPreviewReorder:H,onReorderTab:_,onCommitPreviewOrder:W,onClearPreviewOrder:B,onDragStateReset:re,onDragTabKeyChange:A,onMoveTab:g,onReceiveTab:k,onHideTab:C,isGroupActive:y??!1,allowTabShortcuts:b}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:X,onDragOver:te,onDragLeave:J,onDrop:F,children:[z&&s.jsx(ok,{dropAction:G,canSplit:!!(h<4&&g)}),M?s.jsx(rl,{activeConv:M,clearToken:r[M.tabKey]||0,isCliTerminal:!!K,ideEntry:fe,terminalRef:R,handleModalButton:E.handleModalButton,handleRelaunch:E.handleRelaunch,handleSendChat:E.handleSendChat,handleForceSendChat:E.handleForceSendChat,isSendingChat:E.isSendingChat,sendFeedbackMessage:E.sendFeedbackMessage,handleFocusAgent:E.handleFocusAgent,isFocusingAgent:E.isFocusingAgent,actionLogs:be,userName:d,isInputActive:!m||!!y}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(al,{conversationsCount:e.length,isSplitMode:m,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:N})})]})]})}function dk({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,userName:h,focusedGroup:g,focusGroup:k,moveTabToGroup:f,splitTabRelative:v,closeGroup:w,handleResizeStart:x,groupActiveTabIds:j,setGroupActiveTab:C,groupTabOrders:y,setGroupTabOrder:b,toggleHiddenTab:N,onOpenNewSession:S,allowTabShortcuts:I=!0,liveSessionInboxState:R}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((L,M)=>{const P=t&&n.length===r?`${n[M]}%`:void 0;return s.jsxs(Lt.Fragment,{children:[t&&M>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:$=>x(M-1,$),onDoubleClick:()=>w(M),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(ck,{style:t?{flexBasis:P??`${100/r}%`,flexGrow:P?0:1,flexShrink:P?0:1}:void 0,conversations:L,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,userName:h,groupIndex:M,isFocused:t&&g===M,onFocus:()=>k(M),isSplitMode:t,numGroups:r,onMoveTab:($,Y)=>{Y==="left"&&M>0?f($,M-1):Y==="right"&&M<r-1?f($,M+1):Y==="split-left"&&r<4?v($,M,"left"):Y==="split-right"&&r<4&&v($,M,"right")},onReceiveTab:$=>f($,M),onActiveTabChange:$=>C(M,$),initialActiveTabId:j[M],initialTabOrder:y[M],onTabOrderChange:$=>b(M,$),onHideTab:N,onOpenNewSession:S,allowTabShortcuts:I,liveSessionInboxState:R})]},M)})})}const om="adhdev-dashboard-action-shortcuts",uk=1200,pk=[["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 mk(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function pt(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 im(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:pt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:pt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:pt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:pt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:pt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:pt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:pt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:pt("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:pt("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:pt("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:pt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:pt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:pt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:pt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:pt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:pt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:pt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:pt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:pt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:pt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:pt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:pt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:pt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:pt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:pt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:pt("toggleCliView",e)}]}function hi(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function ga(e){const t=Object.fromEntries(im(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(om)||"{}"),n={...t,...r};for(const[a,o]of pk)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function lm(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function hk({enabled:e=!0,onTrigger:t}){const r=mk(),[n,a]=l.useState(()=>ga(r)),[o,i]=l.useState(null),[c,d]=l.useState([]),p=l.useRef({parts:[],timer:null}),u=l.useCallback(f=>{const v=[];return f.metaKey&&v.push(r?"⌘":"Meta"),f.ctrlKey&&v.push("Ctrl"),f.altKey&&v.push(r?"⌥":"Alt"),f.shiftKey&&f.key.length!==1&&v.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(v.push(lm(f.key)),v.join("+"))},[r]),m=l.useCallback(f=>{a(f);try{localStorage.setItem(om,JSON.stringify(f))}catch{}},[]);l.useEffect(()=>{const f=ga(r),v=Object.entries(n),w=Object.entries(f);v.length===w.length&&v.every(([x,j])=>f[x]===j)||m(f)},[n,r,m]);const h=l.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),g=l.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},uk))},[]);l.useEffect(()=>{if(!o)return;const f=v=>{if(v.preventDefault(),v.stopPropagation(),v.key==="Escape"){i(null),d([]);return}const w=u(v);if(!w)return;const j=!(v.metaKey||v.ctrlKey||v.altKey)&&/^[A-Z0-9]$/.test(w);if(c.length===0&&j){d([w]);return}const y=[...c,w].slice(0,2).join(" "),b={...n};for(const[N,S]of Object.entries(b))S===y&&delete b[N];b[o]=y,m(b),i(null),d([])};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[n,u,m,o,c]),l.useEffect(()=>{if(!e||o)return;const f=v=>{if(v.defaultPrevented)return;const w=u(v);if(!w)return;const x=v.metaKey||v.ctrlKey||v.altKey;if(hi(v.target))return;const j=p.current.parts,C=x?[w]:[...j.slice(-1),w].slice(-2),y=C.join(" "),b=C[C.length-1],N=Object.entries(n).filter(([,M])=>!!M),S=N.find(([,M])=>M===y);if(S){v.preventDefault(),h(),t(S[0]);return}if(N.some(([,M])=>M.startsWith(`${y} `))){v.preventDefault(),p.current.parts=C,g();return}const R=N.find(([,M])=>M===b);if(R){v.preventDefault(),h(),t(R[0]);return}if(N.some(([,M])=>M.startsWith(`${b} `))){v.preventDefault(),p.current.parts=[b],g();return}h()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[n,g,e,u,t,h,o]),l.useEffect(()=>()=>h(),[h]);const k=l.useMemo(()=>im(r),[r]);return{isMac:r,actionDefinitions:k,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:m}}function fk({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 cm(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Kc({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!cm(n):!0}function xk({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:cm(r)}const dm=1e3,bk=4;function Uc(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Gc(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function gk({detachDelayMs:e=dm,stillnessThresholdPx:t=bk,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,u=!1;const m=()=>{p!=null&&(a(p),p=null)},h=()=>{m(),c=null},g=()=>{m(),o=null,i=null,c=null,d=null,u=!1},k=()=>{!o||!c||!d||u||p!=null||(p=n(()=>{p=null,!(!o||!c||!d||u)&&Uc(d,i)&&(Gc(c,d,t)||(u=!0,r({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},f=w=>{if(!(!o||u)){if(!Uc(w,i)){d={clientX:w.clientX,clientY:w.clientY},h();return}(!c||Gc(c,w,t))&&(m(),c={clientX:w.clientX,clientY:w.clientY}),d={clientX:w.clientX,clientY:w.clientY},k()}},v=w=>{!o||u||(w&&(d={clientX:w.clientX,clientY:w.clientY}),h())};return{startDrag:w=>{m(),o=w.panelId,i=w.selfPanelBounds??null,c=null,d={clientX:w.clientX,clientY:w.clientY},u=!1},markSelfPanel:f,markNonSelfPanel:v,markNoDropTarget:v,markDockTarget:v,endDrag:g,isDragging:()=>o!=null,hasDetached:()=>u,dispose:g}}function yk(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Jn(e){return xt(e)||e.tabKey}function vk(e){return`remote:${e}`}function rs(e){return e.startsWith("remote:")}function zc(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function yo(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 vo(e,t){e.classList.remove(Fo.className,Oo.className),e.classList.add(t==="light"?Fo.className:Oo.className)}function Vc(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 wk(e,t,r){var i;const n=[t];let a;for(const c of n){let d;for(const p of c){const u=e.addPanel({id:p.tabKey,component:"conversation",title:Jn(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=u.id)}a=d??a}return r??((i=t[0])==null?void 0:i.tabKey)??null}function qc(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])rs(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!==Jn(a)&&o.api.setTitle(Jn(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:Jn(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 Yc(e,t,r){var d,p;const n=r?vk(r):null;for(const u of[...e.panels])rs(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=ls(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),i=cp(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(u=>!rs(u.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 um({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?vt.onScreenshot("ide-page",(u,m)=>{if(u!==e)return;const h=new FileReader;h.onload=()=>o(h.result),h.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{r!=="connected"&&o(null)},[r]),l.useEffect(()=>{var u;return e?((u=vt.onStatus)==null?void 0:u.call(vt,(m,h)=>{m===e&&h!=null&&h.screenshotUsage&&c(h.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const p=e?vt.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,u)=>{const m=e?vt.get(e):null;return!m||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):m.sendInput(p,u,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:i,handleRemoteAction:d}}const pm=l.createContext(null);function Pa(){const e=l.useContext(pm);if(!e)throw new Error("DashboardDockviewContext missing");return e}function jk(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 kk({params:e}){var d;const t=Pa(),r=l.useMemo(()=>ls([...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}=um({doId:a,targetSessionId:r?Fu(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(iu,{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 Sk(){const e=Pa();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(al,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function Nk(e){var x,j;jk(e);const t=Pa(),r=l.useCallback(C=>{"button"in C&&C.button!==0||e.api.setActive()},[e.api]),n=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),a=n==null?void 0:n.sessionId,o=l.useCallback(C=>i0(C),[]),i=l.useCallback(()=>o0(a),[a]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const C=ls([...t.conversationsByTabKey.values()],e.params.routeId),y=((x=e.api.group.activePanel)==null?void 0:x.id)===e.api.id,b=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${y?" is-active":""}${b?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(C==null?void 0:C.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:C!=null&&C.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:C.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const d=t.conversationsByTabKey.get(e.params.tabKey);if(!d)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const p=((j=e.api.group.activePanel)==null?void 0:j.id)===e.api.id,u=e.api.isGroupActive,m=Na(d,t.liveSessionInboxState,{isOpenConversation:p}),h=m.isReconnecting,g=m.isConnecting,k=m.isGenerating||c,f=m.isWaiting,v=m.unread,w=t.tabShortcuts[d.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${u?" is-group-active":""}${h?" is-reconnecting":""}`,title:xt(d),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:C=>{var y;C.preventDefault(),r(C),t.openTabContextMenu({x:C.clientX,y:C.clientY,tabKey:d.tabKey,sourceDocument:((y=C.target)==null?void 0:y.ownerDocument)??document})},children:[v&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:k?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:"○"}):g?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:xt(d)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:h?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Us(d)}):g?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Us(d)}):s.jsx("span",{children:Us(d)})})]}),w&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:w,children:w})]})}function Dn(e){return e.isActive}function Jc(e){return e.isVisible}function Ck(e){e.preventDefault()}function Ik({params:e,api:t}){var g;const r=Pa(),n=l.useRef(null),[a,o]=l.useState(()=>Dn(t)),[i,c]=l.useState(()=>Jc(t)),d=r.conversationsByTabKey.get(e.tabKey),p=_a({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});l.useEffect(()=>{o(Dn(t)),c(Jc(t));const k=[t.onDidActiveChange(f=>o(f.isActive)),t.onDidActiveGroupChange(f=>{if(!Dn(t)&&!f.isActive){o(!1);return}o(Dn(t))}),t.onDidVisibilityChange(f=>c(f.isVisible))];return()=>{for(const f of k)f.dispose()}},[t]);const u=l.useMemo(()=>d?r.ides.find(k=>k.id===d.routeId):void 0,[r.ides,d]),m=l.useMemo(()=>d?r.actionLogs.filter(k=>k.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(al,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const h=!lt(d)&&Ir(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(rl,{activeConv:d,clearToken:r.clearedTabs[d.tabKey]||0,isCliTerminal:h,ideEntry:u,terminalRef:n,handleModalButton:p.handleModalButton,handleRelaunch:p.handleRelaunch,handleSendChat:p.handleSendChat,handleForceSendChat:p.handleForceSendChat,isSendingChat:p.isSendingChat,handleFocusAgent:p.handleFocusAgent,isFocusingAgent:p.isFocusingAgent,actionLogs:m,userName:r.userName,scrollToBottomRequestNonce:((g=r.scrollToBottomRequest)==null?void 0:g.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:i})})}function Ak({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d,userName:p,toggleHiddenTab:u,actionShortcuts:m,registerActionHandlers:h,onActiveTabChange:g,onOpenNewSession:k,onRequestScrollToBottom:f,requestedActiveTabKey:v,requestedRemoteIdeId:w,onRequestedActiveTabConsumed:x,scrollToBottomRequest:j,liveSessionInboxState:C,layoutProfile:y}){var ct,Ze,Ot;const{theme:b}=Ps(),{sendCommand:N}=bt(),S=l.useRef(null),I=l.useRef(null),R=l.useRef(null),L=l.useRef(!1),M=l.useRef(!1),P=l.useRef(!1),$=l.useRef(null),Y=l.useRef([]),[_,H]=l.useState(null),[W,B]=l.useState(0),T=l.useRef(typeof window>"u"?{}:Vw(y)),A=l.useMemo(()=>new Map(e.map(Q=>[Q.tabKey,Q])),[e]),E=l.useMemo(()=>{const Q=S.current;return Q?Q.groups.some(ee=>{try{const ae=ee.model.location.type;return ae!=="floating"&&ae!=="popout"?!1:ee.panels.some(pe=>A.has(pe.id))}catch{return!1}}):!1},[A,W,e]),z=l.useCallback(()=>{var Q;(Q=S.current)==null||Q.focus()},[]),G=l.useCallback((Q,ee)=>{f==null||f(Q,ee)},[f]),re=l.useCallback(Q=>{const ee=document,ae=Q.document;for(const Ce of ee.querySelectorAll('link[rel="stylesheet"]')){const Ee=ae.createElement("link");Ee.rel="stylesheet",Ee.href=Ce.href,Ce.crossOrigin&&(Ee.crossOrigin=Ce.crossOrigin),ae.head.appendChild(Ee)}for(const Ce of ee.querySelectorAll("style")){const Ee=ae.createElement("style");Ee.textContent=Ce.textContent,ae.head.appendChild(Ee)}const pe=[];for(const Ce of ee.styleSheets)try{for(const Ee of Ce.cssRules)Ee instanceof CSSStyleRule&&(Ee.selectorText===":root"||Ee.selectorText==="html")&&pe.push(Ee.cssText)}catch{}if(pe.length>0){const Ce=ae.createElement("style");Ce.textContent=pe.join(`
|
|
66
|
+
`),ae.head.appendChild(Ce)}const xe=ee.documentElement.getAttribute("data-theme");xe&&ae.documentElement.setAttribute("data-theme",xe),ae.documentElement.style.colorScheme=xe==="light"?"light":"dark",ae.body.className=ee.body.className;const Me=ee.documentElement.getAttribute("style");Me&&ae.documentElement.setAttribute("style",Me);const Le=ae.getElementById("dv-popout-window");Le instanceof HTMLElement&&(Le.classList.add("adhdev-dockview"),vo(Le,b))},[b]),X=l.useCallback(()=>{var ee;const Q=S.current;if(Q)for(const ae of Q.groups)try{const pe=(ee=ae.element)==null?void 0:ee.ownerDocument;if(!pe||pe===document)continue;const xe=pe.getElementById("dv-popout-window");xe instanceof HTMLElement&&(xe.classList.add("adhdev-dockview"),vo(xe,b));const Me=document.documentElement.getAttribute("data-theme");Me&&pe.documentElement.setAttribute("data-theme",Me),pe.documentElement.style.colorScheme=Me==="light"?"light":"dark",pe.body.className=document.body.className;const Le=document.documentElement.getAttribute("style");Le?pe.documentElement.setAttribute("style",Le):pe.documentElement.removeAttribute("style")}catch{}},[b]),te=l.useCallback(Q=>{const ee=S.current;if(!ee)return;const ae=ee.getPanel(Q);ae&&ee.addPopoutGroup(ae,{popoutUrl:"/popout.html",onDidOpen:({window:pe})=>{re(pe),we();const xe=A.get(Q);pe.document.title=xe?`${xt(xe)} — ADHDev`:"ADHDev — Popout"}})},[A,re]),J=l.useCallback(Q=>{const ee=S.current,ae=ee==null?void 0:ee.getPanel(Q);if(!ee||!ae)return;const pe=ee.groups.filter(xe=>{var Me;try{return((Me=xe.element)==null?void 0:Me.ownerDocument)===document}catch{return!0}});pe.length>0?ae.api.moveTo({group:pe[0],position:"center"}):ae.api.moveTo({position:"center"}),ae.api.setActive()},[]),F=l.useCallback(Q=>{var pe;const ee=S.current;if(!ee)return!1;const ae=ee.getPanel(Q);if(!ae)return!1;try{return((pe=ae.group.element)==null?void 0:pe.ownerDocument)!==document}catch{return!1}},[]),K=l.useCallback(Q=>{F(Q)&&J(Q),u(Q)},[F,J,u]),fe=l.useCallback(Q=>{const ee=S.current,ae=ee==null?void 0:ee.getPanel(Q);!ee||!ae||ee.addFloatingGroup(ae,{width:600,height:500})},[]),be=l.useCallback(Q=>{var ae;const ee=(ae=S.current)==null?void 0:ae.getPanel(Q);if(!ee)return!1;try{return ee.group.model.location.type==="floating"}catch{return!1}},[]),oe=l.useCallback(()=>{var ee,ae;const Q=(ae=(ee=S.current)==null?void 0:ee.activePanel)==null?void 0:ae.id;return!Q||rs(Q)?null:A.has(Q)?Q:null},[A]),je=l.useCallback(Q=>{const ee=S.current,ae=ee==null?void 0:ee.getPanel(Q);if(!ee||!ae)return;const pe=ee.groups.filter(xe=>{try{return xe.model.location.type==="grid"}catch{return!0}});pe.length>0?ae.api.moveTo({group:pe[0],position:"center"}):ae.api.moveTo({position:"center"}),ae.api.setActive()},[]),ge=l.useCallback(()=>{var Me;const Q=S.current;if(!Q)return;const ae=Q.groups.filter(Le=>{var Ce;try{return((Ce=Le.element)==null?void 0:Ce.ownerDocument)===document&&Le.model.location.type==="grid"}catch{return!1}})[0]||null,pe=[...Q.panels];for(const Le of pe){const Ce=(Me=Le.group.element)==null?void 0:Me.ownerDocument,Ee=Le.group.model.location.type;Ce===document&&Ee==="grid"||(ae&&ae.id!==Le.group.id?Le.api.moveTo({group:ae,position:"center"}):Le.api.moveTo({position:"center"}))}const xe=Q.activePanel;xe&&(xe.group.model.openPanel(xe),xe.api.setActive()),yo(document)},[]),we=l.useCallback(()=>{var ee,ae;const Q=S.current;if(Q)for(const pe of Q.groups){const xe=(ee=pe.element)==null?void 0:ee.ownerDocument;if(!xe||xe===document)continue;const Me=xe.getElementById("dv-popout-window");if(!(Me instanceof HTMLElement))continue;let Le=null,Ce=xe.title||"ADHDev",Ee="Popout workspace";const Ge=pe.activePanel;if(Ge)if(Le=Ge.id,rs(Ge.id)){const ce=((ae=Ge.params)==null?void 0:ae.routeId)||Ge.id.slice(7),ye=ls([...A.values()],ce);Ce=cp(ye),Ee=ye!=null&&ye.machineName?`Remote view · ${ye.machineName}`:"Remote view"}else{const ce=A.get(Ge.id);Ce=ce?xt(ce):Ge.title||Ge.id,Ee=ce?Us(ce):"Dockview panel"}xe.title=`${Ce} — ADHDev`;const Xe=Array.from(xe.querySelectorAll("#adhdev-popout-header"));for(const ce of Xe)ce.remove();const De=xe.createElement("div");De.id="adhdev-popout-header",xe.body.appendChild(De),De.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(";")),De.innerHTML=`
|
|
67
|
+
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
68
|
+
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
69
|
+
<div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${zc(Ce)}</div>
|
|
70
|
+
<div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${zc(Ee)}</div>
|
|
71
|
+
</div>
|
|
72
|
+
<div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
|
|
73
|
+
<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>
|
|
74
|
+
<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>
|
|
75
|
+
</div>
|
|
76
|
+
`,Me.style.top="52px",Me.style.height="calc(100% - 52px)";const Oe=De.querySelector("[data-adhdev-popout-focus]");Oe&&(Oe.onclick=()=>{window.focus()});const ne=De.querySelector("[data-adhdev-popout-dock]");ne&&(ne.disabled=!Le,ne.style.opacity=Le?"1":"0.5",ne.style.cursor=Le?"pointer":"default",ne.onclick=()=>{var ce;Le&&J(Le),(ce=xe.defaultView)==null||ce.focus()})}},[A,J]),me=l.useCallback(Q=>{var pe;const ee=S.current,ae=ee==null?void 0:ee.getPanel(Q);if(!(!ee||!ae)){ae.group.model.openPanel(ae),ae.api.setActive(),G(Q,"dockview-shortcut");try{const xe=ae.group.model.location;xe.type==="popout"?xe.getWindow().focus():yo((pe=ae.group.element)==null?void 0:pe.ownerDocument)}catch{}}},[G]),U=l.useCallback(Q=>{const ee=S.current,ae=ee==null?void 0:ee.activePanel,pe=(ee==null?void 0:ee.activeGroup)||(ae==null?void 0:ae.group);if(!ee||!ae||!pe)return;const xe=pe.panels||[];if(xe.length<=1)return;const Me=xe.findIndex(Ee=>Ee.id===ae.id);if(Me<0)return;const Le=(Me+Q+xe.length)%xe.length,Ce=xe[Le];Ce&&(Ce.group.model.openPanel(Ce),Ce.api.setActive(),rs(Ce.id)||G(Ce.id,"dockview-shortcut"))},[G]),O=l.useCallback(Q=>{var Oe;const ee=S.current,ae=(ee==null?void 0:ee.activeGroup)||((Oe=ee==null?void 0:ee.activePanel)==null?void 0:Oe.group);if(!ee||!ae)return;const pe=ee.groups||[],xe=pe.find(ne=>ne.id===ae.id);if(!xe)return;const Me=xe.element.getBoundingClientRect(),Le=Me.left+Me.width/2,Ce=Me.top+Me.height/2,Ee=(ne,ce,ye,Be)=>Math.max(0,Math.min(ce,Be)-Math.max(ne,ye)),Ge=ne=>{const ce=ne.element.getBoundingClientRect(),ye=ce.left+ce.width/2,Be=ce.top+ce.height/2;let Ue=0,Qe=0,et=0,Ye=!1;if(Q==="left"?(Ye=ye<Le,Ue=Math.max(0,Me.left-ce.right),Qe=Math.abs(Be-Ce),et=Ee(Me.top,Me.bottom,ce.top,ce.bottom)):Q==="right"?(Ye=ye>Le,Ue=Math.max(0,ce.left-Me.right),Qe=Math.abs(Be-Ce),et=Ee(Me.top,Me.bottom,ce.top,ce.bottom)):Q==="above"?(Ye=Be<Ce,Ue=Math.max(0,Me.top-ce.bottom),Qe=Math.abs(ye-Le),et=Ee(Me.left,Me.right,ce.left,ce.right)):(Ye=Be>Ce,Ue=Math.max(0,ce.top-Me.bottom),Qe=Math.abs(ye-Le),et=Ee(Me.left,Me.right,ce.left,ce.right)),!Ye)return Number.POSITIVE_INFINITY;const Ve=et>0?0:120;return Ue*3+Qe+Ve};let Xe=null,De=Number.POSITIVE_INFINITY;for(const ne of pe){if(ne.id===xe.id)continue;const ce=Ge(ne);Number.isFinite(ce)&&(ce>=De||(De=ce,Xe=ne))}return Xe||void 0},[]),Z=l.useCallback(Q=>{var pe;const ee=O(Q);if(!ee)return;const ae=ee.activePanel||ee.panels[0];ae&&(ee.model.openPanel(ae),ae.api.setActive(),rs(ae.id)||G(ae.id,"dockview-focus"),yo((pe=ee.element)==null?void 0:pe.ownerDocument))},[O,G]),V=l.useCallback((Q,ee)=>{const ae=S.current,pe=ae==null?void 0:ae.activePanel,xe=(ae==null?void 0:ae.activeGroup)||(pe==null?void 0:pe.group);if(!ae||!pe||!xe)return;let Me=O(Q);!Me&&(ee!=null&&ee.createGroupIfMissing)&&(Me=ae.addGroup({referenceGroup:xe,direction:Q})),Me&&(pe.api.moveTo({group:Me,position:"center"}),pe.group.model.openPanel(pe),pe.api.setActive(),rs(pe.id)||G(pe.id,ee!=null&&ee.createGroupIfMissing?"dockview-split":"dockview-move"))},[O,G]),{isMac:he,tabShortcuts:le,shortcutListening:D,setShortcutListening:de,saveShortcuts:Se}=am({sortedTabKeys:e.map(Q=>Q.tabKey),onFocus:z,onSelectTab:me}),ue=l.useCallback(()=>{var ae;const Q=S.current;if(!Q)return;const ee=Q.activePanel;if(ee){if(rs(ee.id)){const pe=((ae=ee.params)==null?void 0:ae.routeId)||ee.id.slice(7),xe=ls(e,pe);xe!=null&&xe.tabKey&&de(xe.tabKey);return}A.has(ee.id)&&de(ee.id)}},[A,me,de,e]),q=l.useCallback(Q=>{const ee=[];return Q.metaKey&&ee.push(he?"⌘":"Meta"),Q.ctrlKey&&ee.push("Ctrl"),Q.altKey&&ee.push(he?"⌥":"Alt"),Q.shiftKey&&Q.key.length!==1&&ee.push(he?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(Q.key)?null:(ee.push(lm(Q.key)),ee.join("+"))},[he]),ve=l.useCallback(Q=>{var ee,ae;switch(Q){case"splitActiveTabRight":V("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":V("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const pe=oe();pe&&fe(pe);return}case"popoutActiveTab":{const pe=oe();pe&&te(pe);return}case"dockActiveTab":{const pe=oe();if(!pe)return;F(pe)?J(pe):be(pe)&&je(pe);return}case"focusLeftPane":Z("left");return;case"focusRightPane":Z("right");return;case"focusUpPane":Z("above");return;case"focusDownPane":Z("below");return;case"moveActiveTabToLeftPane":V("left");return;case"moveActiveTabToRightPane":V("right");return;case"moveActiveTabToUpPane":V("above");return;case"moveActiveTabToDownPane":V("below");return;case"selectPreviousGroupTab":U(-1);return;case"selectNextGroupTab":U(1);return;case"setActiveTabShortcut":ue();return;case"hideCurrentTab":{const pe=(ae=(ee=S.current)==null?void 0:ee.activePanel)==null?void 0:ae.id;pe&&!rs(pe)&&K(pe);return}default:return}},[U,je,Z,fe,oe,K,be,F,J,V,te,ue]);l.useEffect(()=>{if(!_)return;const Q=_.sourceDocument,ee=Q.defaultView??window,ae=pe=>{const xe=Q.querySelector("[data-dockview-tab-context-menu]");xe&&xe.contains(pe.target)||H(null)};return ee.addEventListener("mousedown",ae,!0),ee!==window&&window.addEventListener("mousedown",()=>H(null),!0),()=>{ee.removeEventListener("mousedown",ae,!0),ee!==window&&window.removeEventListener("mousedown",()=>H(null),!0)}},[_]);const Ae=l.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:A,hasDetachedConversationPanels:E,ides:r,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:k,liveSessionInboxState:C,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:K,userName:p,scrollToBottomRequest:j,tabShortcuts:le,openTabContextMenu:({x:Q,y:ee,tabKey:ae,sourceDocument:pe})=>H({x:Q,y:ee,tabKey:ae,sourceDocument:pe??document}),popoutTab:te,moveTabBackToMain:J,isTabInPopout:F,floatTab:fe,isTabFloating:be}),[n,t,A,E,r,i,c,k,C,a,o,K,p,j,le,te,J,F,fe,be]),Ne=_?fk({isTabInPopout:F(_.tabKey),isTabFloating:be(_.tabKey),tabShortcut:le[_.tabKey],actionShortcuts:m}):[],Ke=l.useCallback(Q=>{var pe;const ee=S.current;if((((pe=ee==null?void 0:ee.activePanel)==null?void 0:pe.id)??null)===Q.id){Q.group.model.openPanel(Q);return}Q.group.model.openPanel(Q),Q.api.setActive()},[]),ie=l.useCallback((Q,ee="requested-tab")=>{if(!Q)return!1;const ae=S.current;if(!ae)return!1;const pe=ae.getPanel(Q);return pe?(Ke(pe),G(Q,ee),x==null||x(),!0):!1},[Ke,x,G]),Fe=l.useCallback(()=>{if(P.current)return!1;const Q=ie($.current,"stored-layout-restore");return Q&&(P.current=!0),Q},[ie]),$e=l.useCallback(()=>{var ee;const Q=S.current;Q&&zw(y,{activeTabId:((ee=Q.activePanel)==null?void 0:ee.id)??null,layout:Q.toJSON()})},[y]),tt=l.useCallback(()=>{qw(y,T.current)},[y]),qe=l.useCallback(Q=>{var pe,xe,Me,Le;const ee=S.current;if(!ee)return{kind:"grid"};const ae=ee.toJSON();for(const Ce of ae.floatingGroups||[])if((xe=(pe=Ce.data)==null?void 0:pe.views)!=null&&xe.includes(Q)&&Ce.position)return{kind:"floating",position:Ce.position};for(const Ce of ae.popoutGroups||[])if((Le=(Me=Ce.data)==null?void 0:Me.views)!=null&&Le.includes(Q))return{kind:"popout",position:Ce.position,popoutUrl:Ce.url};return{kind:"grid"}},[]),ke=l.useCallback(Q=>{const ee=S.current;if(!ee)return;const ae=ee.getPanel(Q),pe=T.current[Q];if(!ae||!pe||pe.kind==="grid")return;if(ae.group.model.location.type===pe.kind){delete T.current[Q],tt();return}if(pe.kind==="floating"){ee.addFloatingGroup(ae,{x:pe.position.left??24,y:pe.position.top??24,width:pe.position.width,height:pe.position.height}),delete T.current[Q],tt();return}delete T.current[Q],tt()},[tt]);l.useEffect(()=>(h==null||h({setShortcutForActiveTab:ue,restoreHiddenTabToSavedLocation:ke,activateConversationTab:me,resetAllPanelsToMain:ge,activatePreviousTabInGroup:()=>U(-1),activateNextTabInGroup:()=>U(1),floatActiveTab:()=>{const Q=oe();Q&&fe(Q)},popoutActiveTab:()=>{const Q=oe();Q&&te(Q)},dockActiveTab:()=>{const Q=oe();Q&&(F(Q)?J(Q):be(Q)&&je(Q))},splitActiveTabRight:()=>V("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>V("below",{createGroupIfMissing:!0}),focusLeftPane:()=>Z("left"),focusRightPane:()=>Z("right"),focusUpPane:()=>Z("above"),focusDownPane:()=>Z("below"),moveActiveTabToLeftPane:()=>V("left"),moveActiveTabToRightPane:()=>V("right"),moveActiveTabToUpPane:()=>V("above"),moveActiveTabToDownPane:()=>V("below")}),()=>h==null?void 0:h(null)),[U,je,fe,Z,oe,be,F,V,J,te,h,ge,ke,me,ue]),l.useEffect(()=>()=>{var Q;(Q=R.current)==null||Q.call(R),R.current=null},[]);const ot=l.useCallback(Q=>{var ae,pe;S.current=Q.api,(ae=R.current)==null||ae.call(R),R.current=null;const ee=Gw(y);if($.current=(ee==null?void 0:ee.activeTabId)??null,ee!=null&&ee.layout&&Q.api.fromJSON(ee.layout,{reuseExistingPanels:!1}),M.current=Kc({hasStoredLayout:!!(ee!=null&&ee.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),M.current||(qc(Q.api,e),Yc(Q.api,e,w)),Q.api.totalPanels===0&&e.length>0){const xe=wk(Q.api,e,v);if(xe){const Me=Q.api.getPanel(xe);Me&&Ke(Me)}}else!M.current&&!ie(v)&&Fe();if(L.current=!0,Q.api.onDidActivePanelChange(xe=>{var Le;if($.current=(xe==null?void 0:xe.id)??null,P.current=!0,we(),xe&&rs(xe.id)){const Ce=((Le=xe.params)==null?void 0:Le.routeId)||xe.id.slice(7),Ee=ls(e,Ce);g((Ee==null?void 0:Ee.tabKey)??null),$e();return}if(g((xe==null?void 0:xe.id)??null),$e(),!xe)return;const Me=A.get(xe.id);(Me==null?void 0:Me.streamSource)==="agent-stream"&&Me.agentType&&N(Me.routeId,Ou(),{agentType:Me.agentType,...Me.sessionId&&{targetSessionId:Me.sessionId}}).catch(()=>{})}),Q.api.onDidLayoutChange(()=>{$e(),we(),B(xe=>xe+1)}),yk()){const xe=De=>({clientX:De.clientX,clientY:De.clientY}),Me=De=>{const Oe=De==null?void 0:De.getBoundingClientRect();return Oe?{left:Oe.left,right:Oe.right,top:Oe.top,bottom:Oe.bottom}:null},Le=De=>{var ne;const Oe=(ne=I.current)==null?void 0:ne.getBoundingClientRect();return Oe?De.clientX<Oe.left||De.clientX>Oe.right||De.clientY<Oe.top||De.clientY>Oe.bottom:!1},Ce=gk({detachDelayMs:dm,onDetach:({panelId:De,clientX:Oe,clientY:ne})=>{var et,Ye;const ce=Q.api.getPanel(De);if(!ce)return;try{if(ce.group.model.location.type!=="grid")return}catch{return}const ye=(et=I.current)==null?void 0:et.getBoundingClientRect(),Be=(Ye=ce.group.element)==null?void 0:Ye.getBoundingClientRect(),Ue=Math.round(Math.min(Math.max((Be==null?void 0:Be.width)??600,360),720)),Qe=Math.round(Math.min(Math.max((Be==null?void 0:Be.height)??500,260),640));Q.api.addFloatingGroup(ce,{x:ye?Math.max(0,Oe-ye.left-32):void 0,y:ye?Math.max(0,ne-ye.top-18):void 0,width:Ue,height:Qe}),ce.api.setActive(),$e(),we(),B(Ve=>Ve+1)}}),Ee=[Q.api.onWillDragPanel(De=>{if(!(De.nativeEvent.defaultPrevented||De.nativeEvent.shiftKey)){try{if(De.panel.group.model.location.type!=="grid")return}catch{return}Ce.startDrag({panelId:De.panel.id,selfPanelBounds:Me(De.panel.group.element),...xe(De.nativeEvent)})}}),Q.api.onWillShowOverlay(De=>{if(Ce.hasDetached()){De.preventDefault();return}Ce.markDockTarget(xe(De.nativeEvent))}),Q.api.onWillDrop(De=>{if(Ce.hasDetached()){De.preventDefault(),Ce.endDrag();return}Ce.markDockTarget(xe(De.nativeEvent))}),Q.api.onDidDrop(()=>Ce.endDrag()),Q.api.onUnhandledDragOverEvent(De=>{Ce.isDragging()&&Ce.markSelfPanel(xe(De.nativeEvent))})],Ge=De=>{if(!Ce.isDragging())return;const Oe=xe(De);Le(Oe)&&Ce.markNonSelfPanel(Oe)},Xe=()=>Ce.endDrag();window.addEventListener("dragover",Ge,!0),window.addEventListener("drop",Xe,!0),window.addEventListener("dragend",Xe,!0),R.current=()=>{Ce.dispose();for(const De of Ee)De.dispose();window.removeEventListener("dragover",Ge,!0),window.removeEventListener("drop",Xe,!0),window.removeEventListener("dragend",Xe,!0)}}Q.api.onDidAddGroup(xe=>{requestAnimationFrame(()=>{var Me,Le;try{const Ce=(Me=xe.element)==null?void 0:Me.ownerDocument;if(!Ce||Ce===document)return;(Le=Ce.getElementById("dv-popout-window"))==null||Le.classList.add("adhdev-dockview");const Ee=document.documentElement.getAttribute("data-theme");Ee&&Ce.documentElement.setAttribute("data-theme",Ee),Ce.body.className=document.body.className;const Ge=document.documentElement.getAttribute("style");Ge&&Ce.documentElement.setAttribute("style",Ge)}catch{}we(),B(Ce=>Ce+1)})}),g(((pe=Q.api.activePanel)==null?void 0:pe.id)??null)},[Ke,ie,A,r,d,y,g,$e,v,w,N,we,e]);l.useLayoutEffect(()=>{const Q=S.current;if(!Q||!L.current||M.current&&Kc({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;M.current&&(M.current=!1);const ee=Y.current,ae=new Set(ee),pe=e.map(Xe=>Xe.tabKey),xe=new Set(pe),Me=xk({previousVisibleConversationCount:ee.length,visibleConversationCount:e.length,ides:r});let Le=!1;for(const Xe of ee)xe.has(Xe)||Me||(T.current[Xe]=qe(Xe),Le=!0);Le&&tt(),Me||(qc(Q,e),Yc(Q,e,w));const Ce=pe.filter(Xe=>!ae.has(Xe));let Ee=!1;for(const Xe of Ce){const De=Q.getPanel(Xe),Oe=T.current[Xe];if(!De||!Oe||Oe.kind==="grid")continue;if(De.group.model.location.type===Oe.kind){delete T.current[Xe],Ee=!0;continue}if(Oe.kind==="floating"){Q.addFloatingGroup(De,{x:Oe.position.left??24,y:Oe.position.top??24,width:Oe.position.width,height:Oe.position.height}),delete T.current[Xe],Ee=!0;continue}}if(Ee&&tt(),Y.current=pe,v&&ie(v))return;!Q.activePanel&&Q.panels[0]&&Ke(Q.panels[0]),!!(Q.activePanel&&Q.getPanel(Q.activePanel.id))||Fe()},[Ke,ie,Fe,r,d,tt,qe,v,w,e]),l.useEffect(()=>{L.current&&ie(v)},[ie,v]),l.useEffect(()=>{const Q=ae=>{const pe=ae.target;if(!pe)return;const xe=pe.querySelector("[data-tab-key]")||pe.closest("[data-tab-key]");if(xe){const Me=xe.getAttribute("data-tab-key");if(Me&&ae.dataTransfer){const Le=pe.closest(".dv-tab")||xe.closest(".dv-tab")||xe;ae.dataTransfer.effectAllowed="move",ae.dataTransfer.setData("text/tab-key",Me),Le instanceof HTMLElement&&ae.dataTransfer.setDragImage(Le,Math.max(12,Math.round(Le.clientWidth/2)),Math.max(10,Math.round(Le.clientHeight/2)))}}};window.addEventListener("dragstart",Q);const ee=Vc(S.current);for(const ae of ee)ae.addEventListener("dragstart",Q);return()=>{window.removeEventListener("dragstart",Q);for(const ae of ee)ae.removeEventListener("dragstart",Q)}},[W]),l.useEffect(()=>{var ee;const Q=(ee=I.current)==null?void 0:ee.querySelector(".adhdev-dockview");Q instanceof HTMLElement&&vo(Q,b),X(),we()},[we,X,b]),l.useEffect(()=>{we()},[we]),l.useEffect(()=>{const Q=ee=>{if(ee.defaultPrevented||D)return;const ae=q(ee);if(!ae)return;const pe=ee.metaKey||ee.ctrlKey||ee.altKey;hi(ee.target)&&!pe||ga(he).setActiveTabShortcut!==ae||(ee.preventDefault(),ee.stopPropagation(),ue())};return window.addEventListener("keydown",Q,!0),()=>window.removeEventListener("keydown",Q,!0)},[q,he,D,ue]),l.useEffect(()=>{const Q=I.current;if(!Q)return;const ee=ae=>{var Ce,Ee;if(!ae.isTrusted)return;const pe=(Ee=(Ce=ae.target)==null?void 0:Ce.closest)==null?void 0:Ee.call(Ce,".dv-scrollable");if(!pe)return;ae.preventDefault(),ae.stopPropagation();const xe=Math.abs(ae.deltaX),Me=Math.abs(ae.deltaY),Le=xe>Me?ae.deltaX:ae.deltaY;pe.dispatchEvent(new WheelEvent("wheel",{deltaY:Le,deltaMode:ae.deltaMode,bubbles:!1,cancelable:!0}))};return Q.addEventListener("wheel",ee,{passive:!1,capture:!0}),()=>Q.removeEventListener("wheel",ee,{capture:!0})},[]),l.useEffect(()=>{const Q=Vc(S.current);if(Q.length===0)return;const ee=Q.map(ae=>{let pe=[],xe=null;const Me=()=>{xe!=null&&ae.clearTimeout(xe),xe=null,pe=[]},Le=()=>{xe!=null&&ae.clearTimeout(xe),xe=ae.setTimeout(()=>{xe=null,pe=[]},1200)},Ce=Ge=>{if(!Ge.ctrlKey&&!Ge.metaKey&&!Ge.altKey)return;const Xe=q(Ge);if(!Xe)return;const De=nm();for(const[Oe,ne]of Object.entries(De))if(e.some(ce=>ce.tabKey===Oe)&&ne===Xe){Ge.preventDefault(),me(Oe);return}},Ee=Ge=>{if(Ge.defaultPrevented||D)return;const Xe=q(Ge);if(!Xe)return;const De=Ge.metaKey||Ge.ctrlKey||Ge.altKey;if(hi(Ge.target))return;const Oe=ga(he),ne=Object.entries(Oe).filter(([Ve,Ct])=>!!Ct&&(Ve==="splitActiveTabRight"||Ve==="splitActiveTabDown"||Ve==="floatActiveTab"||Ve==="popoutActiveTab"||Ve==="dockActiveTab"||Ve==="focusLeftPane"||Ve==="focusRightPane"||Ve==="focusUpPane"||Ve==="focusDownPane"||Ve==="moveActiveTabToLeftPane"||Ve==="moveActiveTabToRightPane"||Ve==="moveActiveTabToUpPane"||Ve==="moveActiveTabToDownPane"||Ve==="selectPreviousGroupTab"||Ve==="selectNextGroupTab"||Ve==="setActiveTabShortcut"||Ve==="hideCurrentTab")),ce=De?[Xe]:[...pe.slice(-1),Xe].slice(-2),ye=ce.join(" "),Be=ce[ce.length-1],Ue=ne.find(([,Ve])=>Ve===ye);if(Ue){Ge.preventDefault(),Me(),ve(Ue[0]);return}if(ne.some(([,Ve])=>Ve.startsWith(`${ye} `))){Ge.preventDefault(),pe=ce,Le();return}const et=ne.find(([,Ve])=>Ve===Be);if(et){Ge.preventDefault(),Me(),ve(et[0]);return}if(ne.some(([,Ve])=>Ve.startsWith(`${Be} `))){Ge.preventDefault(),pe=[Be],Le();return}Me()};return ae.addEventListener("keydown",Ce),ae.addEventListener("keydown",Ee),()=>{Me(),ae.removeEventListener("keydown",Ce),ae.removeEventListener("keydown",Ee)}});return()=>{for(const ae of ee)ae()}},[q,he,W,me,D,ve,e]);const Ie=b==="light"?Fo:Oo,it=((Ot=(Ze=(ct=S.current)==null?void 0:ct.activePanel)==null?void 0:Ze.group.element)==null?void 0:Ot.ownerDocument)??document;return s.jsxs(pm.Provider,{value:Ae,children:[s.jsx("div",{ref:I,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(Ch,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:Ik,remote:kk},defaultTabComponent:Nk,watermarkComponent:Sk,onReady:ot,singleTabMode:"default",tabAnimation:"smooth",theme:Ie,popoutUrl:"/popout.html"})}),_&&hr.createPortal(s.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[var(--z-popover)] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:_.x,top:_.y},children:Ne.map(Q=>{if(Q.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},Q.id);let ee=s.jsx(Jf,{size:13,className:"shrink-0 opacity-70"}),ae=()=>{};switch(Q.id){case"dockInWindow":case"dockBackToGrid":ee=s.jsx(Qf,{size:13,className:"shrink-0 opacity-70"}),ae=()=>{je(_.tabKey),H(null)};break;case"moveBackToMain":ee=s.jsx(Yf,{size:13,className:"shrink-0 opacity-70"}),ae=()=>{J(_.tabKey),H(null)};break;case"floatAsPanel":ee=s.jsx(Xf,{size:13,className:"shrink-0 opacity-70"}),ae=()=>{fe(_.tabKey),H(null)};break;case"openInNewWindow":ee=s.jsx(qf,{size:13,className:"shrink-0 opacity-70"}),ae=()=>{te(_.tabKey),H(null)};break;case"setShortcut":ae=pe=>{pe.stopPropagation(),de(_.tabKey),H(null)};break;case"removeShortcut":ee=s.jsx(Nt,{size:13,className:"shrink-0 opacity-70"}),ae=()=>{const pe={...le};delete pe[_.tabKey],Se(pe),H(null)};break;case"hideTab":ee=s.jsx(Ai,{size:13,className:"shrink-0 opacity-70"}),ae=()=>{K(_.tabKey),H(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 ${Q.tone==="muted"?"text-text-muted":""}`,onMouseDown:Ck,onClick:ae,children:[ee,s.jsx("span",{className:"flex-1 min-w-0",children:Q.label}),Q.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:Q.shortcut}):null]},Q.id)})}),_.sourceDocument.body),D&&hr.createPortal(s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>de(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:Q=>Q.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. ",he?"⌘+1":"Ctrl+1",", ",he?"⌥+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"})]})}),it.body)]})}const mm="adhdev-recent-launch-args-v1",Mk=8;function Tk(e){return String(e||"").trim().replace(/\s+/g," ")}function hm(e,t){return`${e.trim()}::${t.trim()}`}function fm(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(mm)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function _k(e){if(!(typeof window>"u"))try{window.localStorage.setItem(mm,JSON.stringify(e))}catch{}}function Lk(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=fm().byKey[hm(r,n)])==null?void 0:o.items)||[]}function Rk(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=Tk(r);if(!n||!a||!o)return;const i=fm(),c=hm(n,a),d=((u=i.byKey[c])==null?void 0:u.items)||[],p=[o,...d.filter(m=>m!==o)].slice(0,Mk);i.byKey[c]={items:p},_k(i)}function Pk(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Vr({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 Dk({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 $k({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:i,onOpenHistory:c,onClearSelection:d}){const p=o?Qp(o):null,u=Dk({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Vr,{title:"Saved history",description:zi(),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:sv()})]}),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:u}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function xm({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}const wo={cli:"CLI",ide:"IDE",acp:"ACP"};function Ek({workspaceMode:e,activeKind:t,cliEnabled:r,ideEnabled:n,acpEnabled:a,busy:o,onSelect:i}){const{t:c}=Pt();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:c("newSession.category")}),s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:wo.cli,enabled:r},{id:"ide",label:wo.ide,enabled:n},{id:"acp",label:wo.acp,enabled:a}].map(d=>s.jsx("button",{type:"button",className:`btn btn-sm ${t===d.id?"btn-primary":"btn-secondary"}`,onClick:()=>i(d.id),disabled:!d.enabled||o,children:d.label},d.id))})]})}function jo(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>jr(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>jr(a,"acp"))?"acp":null}function $n(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Bk({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:i,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:p}){var kt,Ht;const{t:u}=Pt(),m=Ar(),h=l.useMemo(()=>[...e].sort(Di),[e]),[g,k]=l.useState(((kt=h[0])==null?void 0:kt.id)||""),f=l.useMemo(()=>h.find(se=>se.id===g)||h[0],[g,h]),v=l.useMemo(()=>((f==null?void 0:f.workspaces)||[]).map(se=>({id:se.id,path:se.path,label:se.label})),[f]),w=(f==null?void 0:f.defaultWorkspaceId)||null,[x,j]=l.useState("workspace"),[C,y]=l.useState(""),[b,N]=l.useState(""),[S,I]=l.useState([]),[R,L]=l.useState(""),[M,P]=l.useState(!1),[$,Y]=l.useState(null),[_,H]=l.useState(""),[W,B]=l.useState(jo(h[0])),[T,A]=l.useState(""),[E,z]=l.useState(""),[G,re]=l.useState(""),[X,te]=l.useState(""),[J,F]=l.useState(!1),[K,fe]=l.useState([]),[be,oe]=l.useState(""),[je,ge]=l.useState([]),[we,me]=l.useState(!1),[U,O]=l.useState(!1),[Z,V]=l.useState(""),[he,le]=l.useState(!1),[D,de]=l.useState(()=>Bt()),[Se,ue]=l.useState(null),[q,ve]=l.useState(!1),[Ae,Ne]=l.useState(""),[Ke,ie]=l.useState("error"),[Fe,$e]=l.useState(null),[tt,qe]=l.useState(!1),[ke,ot]=l.useState(""),[Ie,it]=l.useState([]),[ct,Ze]=l.useState(!1),[Ot,Q]=l.useState(""),[ee,ae]=l.useState(!1),pe=l.useRef(null),xe=l.useRef(0);l.useEffect(()=>{var se;!g&&((se=h[0])!=null&&se.id)&&k(h[0].id)},[g,h]),l.useEffect(()=>{!f||!(!f.workspaces||!f.availableProviders||!f.detectedIdes||!f.recentLaunches)||m(f.id,{minFreshMs:3e4}).catch(()=>{})},[m,f]);const Me=l.useCallback(se=>{se&&m(se,{minFreshMs:3e4}).catch(()=>{})},[m]),Le=l.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(se=>jr(se,"cli")),[f]),Ce=l.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(se=>jr(se,"acp")),[f]),Ee=l.useMemo(()=>((f==null?void 0:f.detectedIdes)||[]).map(se=>({id:se.type,label:se.name||se.type,meta:se.running?u("newSession.detectedLocally"):u("newSession.availableToOpen")})),[f,u]),Ge=l.useMemo(()=>W==="cli"?Le.map(se=>({id:se.type,label:se.displayName||se.type,meta:""})):W==="acp"?Ce.map(se=>({id:se.type,label:se.displayName||se.type,meta:""})):Ee,[Ce,W,Le,Ee]),Xe=l.useMemo(()=>S.find(se=>se.id===R)||null,[S,R]),De=l.useMemo(()=>Le.find(se=>se.type===T)||null,[Le,T]),Oe=l.useMemo(()=>[...Le,...Ce].find(se=>se.type===T),[Le,Ce,T]),ne=l.useMemo(()=>hv(Oe?[Oe]:[],Oe==null?void 0:Oe.type),[Oe]),ce=l.useMemo(()=>{const se=fv(Oe?[Oe]:[],Oe==null?void 0:Oe.type);return se.length?se:["low","medium","high"]},[Oe]),ye=l.useMemo(()=>zp(De==null?void 0:De.meshCoordinator,{meshId:(Xe==null?void 0:Xe.id)||"",workspace:(Xe==null?void 0:Xe.workspace)||""}),[De,Xe]),Be=Fe||ye,Ue=l.useCallback(async se=>{P(!0),H("");try{const He=await c(se);I(He),L(Pe=>{var gt;return He.some(Yt=>Yt.id===Pe)?Pe:((gt=He[0])==null?void 0:gt.id)||""}),Y(se)}catch(He){I([]),L(""),Y(se),H(He instanceof Error?He.message:u("newSession.errorLoadMeshes"))}finally{P(!1)}},[c,u]);l.useEffect(()=>{var He;if(!f)return;if(pe.current!==f.id){pe.current=f.id,j("workspace"),y(w||((He=v[0])==null?void 0:He.id)||"__home__"),N(""),I([]),L(""),Y(null),H(""),B(jo(f)),A(""),z(""),re(""),te(""),F(!1),oe(""),ge([]),O(!1),V(""),de(Bt()),Ne(""),$e(null);return}y(Pe=>{var gt;return Pe==="__custom__"||Pe==="__home__"||v.some(Yt=>Yt.id===Pe)?Pe:w||((gt=v[0])==null?void 0:gt.id)||"__home__"}),B(Pe=>Pe==="ide"&&Ee.length>0||Pe==="cli"&&Le.length>0||Pe==="acp"&&Ce.length>0?Pe:jo(f))},[Ce.length,Le.length,w,Ee.length,f,v]),l.useEffect(()=>{!f||x!=="mesh"||$===f.id||M||Ue(f.id)},[Ue,$,M,f,x]),l.useEffect(()=>{x==="mesh"&&W!=="cli"&&Le.length>0&&B("cli")},[W,Le.length,x]),l.useEffect(()=>{var se;W&&(Ge.some(He=>He.id===T)||A(((se=Ge[0])==null?void 0:se.id)||""))},[W,Ge,T]),l.useEffect(()=>{$e(null)},[f==null?void 0:f.id,R,T,x]),l.useEffect(()=>{re(""),te(""),F(!1)},[T]);const Qe=l.useCallback(async(se,He)=>{const Pe=xe.current+1;return xe.current=Pe,me(!0),V(""),p(se,He).then(gt=>{xe.current===Pe&&ge(gt)}).catch(gt=>{xe.current===Pe&&(ge([]),V(gt instanceof Error?gt.message:u("newSession.errorLoadSavedSessions")))}).finally(()=>{xe.current===Pe&&(me(!1),O(!0))})},[p,u]),et=l.useCallback((se,He)=>{fe(Lk(se,He))},[]);l.useEffect(()=>{xe.current+=1,oe(""),de(Bt()),!f||!T||W==="ide"?fe([]):et(f.id,T),O(!1),ge([]),V(""),me(!1)},[W,et,Qe,f,T]),l.useEffect(()=>{if(!be)return;const se=je.find(He=>He.providerSessionId===be);se!=null&&se.canResume||oe("")},[je,be]);const Ye=C==="__custom__"?b.trim():C==="__home__"?"":((Ht=v.find(se=>se.id===C))==null?void 0:Ht.path)||"",Ve=l.useMemo(()=>f?t.filter(se=>se.id!==f.id&&se.daemonId===f.id).map(se=>se.workspace):[],[t,f]),Ct=l.useMemo(()=>((f==null?void 0:f.recentLaunches)||[]).map(se=>se.workspace),[f]),us=l.useCallback(se=>{const He=String(se.workspace||"").trim();if(!He)return;const Pe=v.find(gt=>$n(gt.path)===$n(He));if(Pe){y(Pe.id),N("");return}y("__custom__"),N(He)},[v]),ts=l.useCallback(se=>{const He=String(se.workspace||"").trim();if(!He)return{workspaceId:null,workspacePath:null};const Pe=v.find(gt=>$n(gt.path)===$n(He));return Pe?{workspaceId:Pe.id,workspacePath:null}:{workspaceId:null,workspacePath:He}},[v]),_e=l.useMemo(()=>je.find(se=>se.providerSessionId===be)||null,[je,be]),Je=l.useMemo(()=>{var He;if(W!=="cli"||!f||!T)return null;const se=((He=Le.find(Pe=>Pe.type===T))==null?void 0:He.displayName)||T;return{routeId:f.id,daemonId:f.id,providerSessionId:be||void 0,transport:"pty",mode:"chat",agentName:se,agentType:T,status:"idle",title:se,messages:[],ideType:T,workspaceName:Ye,workspacePath:Ye,displayPrimary:se,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${f.id}:${T}`,machineName:es(f,{fallbackId:f.id})}},[W,Le,Ye,f,be,T]),Mt=l.useCallback(()=>{var He;if(!f)return;y("__custom__"),qe(!0),Q("");const se=tl(f.platform,el(b.trim(),Ye,Ve,Ct,f.defaultWorkspacePath,(He=v.find(Pe=>Pe.id===w))==null?void 0:He.path,v.map(Pe=>Pe.path)));Ze(!0),n(f.id,se).then(Pe=>{ot(Pe.path),N(Pe.path),it(Pe.directories)}).catch(Pe=>{Q(Pe instanceof Error?Pe.message:u("newSession.errorLoadFolder"))}).finally(()=>Ze(!1))},[b,w,Ct,Ve,n,Ye,f,v]),It=l.useCallback(se=>{f&&(Ze(!0),Q(""),n(f.id,se).then(He=>{ot(He.path),N(He.path),it(He.directories)}).catch(He=>{Q(He instanceof Error?He.message:u("newSession.errorLoadFolder"))}).finally(()=>Ze(!1)))},[n,f]),zt=l.useCallback(async()=>{if(!f||!Ye)return;ae(!0),Ne("");const se=await a(f.id,Ye);if(ae(!1),!se.ok){ie("error"),Ne(se.error||u("newSession.errorSaveWorkspace"));return}ie("info"),Ne(u("newSession.workspaceSaved"))},[a,Ye,f,u]),Vt=l.useCallback(async()=>{if(!f)return;if(x==="mesh"){if(!R||!T)return;ve(!0),Ne(""),$e(null);const Pe=await d(f.id,R,T,{initialModel:G.trim()?G.trim():null,initialThinkingLevel:X.trim()?X.trim():null});if(ve(!1),!Pe.ok){if(Pe.code==="mesh_coordinator_manual_mcp_setup_required"&&Pe.manualSetup){$e(Pe.manualSetup),ie("info"),Ne(u("newSession.errorManualMcpSetup"));return}ie("error"),Ne(Pe.error||u("newSession.errorStartMeshCoordinator"));return}r();return}if(!W||!T)return;ve(!0),Ne("");const se=E.trim()?E.trim().split(/\s+/).filter(Boolean):[],He=W==="ide"?await o(f.id,T,{workspacePath:Ye||null}):await i(f.id,W,T,{workspaceId:C!=="__home__"&&C!=="__custom__"?C:null,workspacePath:C==="__custom__"&&Ye||null,resumeSessionId:W==="cli"&&be?be:null,cliArgs:se,initialModel:G.trim()?G.trim():null,initialThinkingLevel:X.trim()?X.trim():null});if(ve(!1),!He.ok){ie("error"),Ne(He.error||u("newSession.errorStartSession"));return}W!=="ide"&&E.trim()&&(Rk(f.id,T,E),et(f.id,T)),r()},[W,E,G,X,et,r,o,d,i,Ye,f,R,be,T,C,x,u]),qt=W==="cli"&&!!be,ys=u(x==="mesh"?"newSession.startMeshCoordinator":W==="cli"?qt?"newSession.resumeSavedHistory":"newSession.startFresh":W==="ide"?"newSession.startIde":W==="acp"?"newSession.startAcpSession":"newSession.start"),Re=u(x==="mesh"?"newSession.startingCoordinator":W==="cli"?qt?"newSession.resumingSavedHistory":"newSession.startingFresh":W==="ide"?"newSession.startingIde":W==="acp"?"newSession.startingAcpSession":"newSession.starting"),nt=h.length>5;return f?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] 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.jsx("div",{className:"min-w-0",children:s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:u("newSession.title")})}),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":u("newSession.close"),children:s.jsx(Nt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[h.length>1&&s.jsx(Vr,{title:u("newSession.machine"),children:nt?s.jsx("select",{"aria-label":u("newSession.machine"),value:f.id,onChange:se=>k(se.target.value),onFocus:()=>h.forEach(se=>Me(se.id)),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:q,children:h.map(se=>s.jsx("option",{value:se.id,children:es(se,{fallbackId:se.id})},se.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":u("newSession.machine"),children:h.map(se=>{const He=es(se,{fallbackId:se.id}),Pe=f.id===se.id;return s.jsxs("button",{type:"button","aria-label":u("newSession.selectMachine",{name:He}),"aria-pressed":Pe,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${Pe?"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:()=>k(se.id),onMouseEnter:()=>Me(se.id),onFocus:()=>Me(se.id),disabled:q,title:He,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${se.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:He})]},se.id)})})}),s.jsxs(Vr,{title:u("newSession.workspace"),action:x==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Mt,disabled:q,children:u("newSession.browse")}):void 0,children:[s.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2",role:"radiogroup","aria-label":u("newSession.launchTargetType"),children:[{id:"workspace",label:u("newSession.modeWorkspace"),desc:u("newSession.modeWorkspaceDesc")},{id:"mesh",label:u("newSession.modeMesh"),desc:u("newSession.modeMeshDesc")}].map(se=>s.jsxs("button",{type:"button",role:"radio","aria-checked":x===se.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${x===se.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{j(se.id),Ne(""),se.id==="mesh"&&f&&$!==f.id&&!M&&Ue(f.id)},disabled:q,children:[s.jsx("div",{className:"text-sm font-semibold",children:se.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:se.desc})]},se.id))}),x==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:C,onChange:se=>{const He=se.target.value;y(He),He==="__custom__"?Mt():Ne("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:q,children:[s.jsx("option",{value:"__home__",children:u("newSession.homeDirectory")}),v.map(se=>s.jsxs("option",{value:se.id,children:[se.id===w?"⭐ ":"",gu(se.path,se.label)||se.path]},se.id)),s.jsx("option",{value:"__custom__",children:u("newSession.customFolder")})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:C==="__home__"?u("newSession.launchWithoutWorkspace"):Ye||u("newSession.selectWorkspaceFolder")}),C==="__custom__"&&Ye&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Mt,disabled:q,children:[s.jsx(br,{size:14}),u("newSession.selectFolder")]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:zt,disabled:q||ee,children:u(ee?"newSession.saving":"newSession.saveWorkspace")})]})]}):s.jsxs("div",{className:"space-y-3",children:[M&&s.jsx("div",{className:"text-sm text-text-muted",children:u("newSession.loadingMeshes")}),!M&&_&&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:_}),!M&&!_&&S.length===0&&s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2 text-sm text-text-muted",children:u("newSession.noMeshes")}),S.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":u("newSession.mesh"),children:S.map(se=>s.jsxs("button",{type:"button",role:"radio","aria-checked":R===se.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${R===se.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>L(se.id),disabled:q,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:se.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[se.repoIdentity||u("newSession.repoMesh"),typeof se.nodesCount=="number"?` · ${u("newSession.nodeCount",{count:se.nodesCount})}`:""]}),se.workspace&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:u("newSession.coordinatorWorkspace",{path:se.workspace})})]},se.id))})]})]}),s.jsx(Ek,{workspaceMode:x,activeKind:W,cliEnabled:Le.length>0,ideEnabled:Ee.length>0,acpEnabled:Ce.length>0,busy:q,onSelect:B}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:u(W==="ide"?"newSession.chooseIde":W==="cli"?"newSession.chooseCliProvider":"newSession.chooseAcpProvider")}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Ge.map(se=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${T===se.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>A(se.id),disabled:q,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:se.label}),se.meta&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:se.meta})]},se.id)),Ge.length===0&&s.jsx("div",{className:"text-sm text-text-muted",children:u("newSession.noProviders")})]})]}),x==="mesh"&&Be&&s.jsx(xm,{setup:Be,providerName:(De==null?void 0:De.displayName)||(De==null?void 0:De.name)||T}),x!=="mesh"&&W!=="ide"&&s.jsxs(Vr,{title:u("newSession.startupArguments"),children:[s.jsx("input",{type:"text",value:E,onChange:se=>z(se.target.value),placeholder:u("newSession.optionalFlags"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:q}),K.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:K.map(se=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>z(se),disabled:q,title:se,children:se},se))})]}),(x==="mesh"&&!!T||x!=="mesh"&&W!=="ide")&&s.jsx(Vr,{title:u("newSession.modelAndThinking"),children:s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:u("newSession.model")}),ne.length>0&&!J?s.jsxs("select",{value:ne.includes(G)?G:"",onChange:se=>{se.target.value==="__custom__"?(F(!0),re("")):re(se.target.value)},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:q,children:[s.jsx("option",{value:"",children:u("newSession.providerDefault")}),ne.map(se=>s.jsx("option",{value:se,children:se},se)),s.jsx("option",{value:"__custom__",children:u("newSession.custom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:G,onChange:se=>re(se.target.value),placeholder:u("newSession.typeModelName"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:q,autoFocus:J}),ne.length>0&&s.jsx("button",{type:"button",className:"self-start text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{F(!1),re("")},disabled:q,children:u("newSession.backToModelList")})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:u("newSession.thinkingLevel")}),s.jsxs("select",{value:X,onChange:se=>te(se.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:q,children:[s.jsx("option",{value:"",children:u("newSession.providerDefault")}),ce.map(se=>s.jsx("option",{value:se,children:se},se))]})]})]})}),x!=="mesh"&&W==="cli"&&s.jsx($k,{busy:q,savedSessionsLoading:we,savedSessionsError:Z,selectedSession:_e,onRefresh:()=>{!f||!T||Qe(f.id,T)},onOpenHistory:()=>{!f||!T||(le(!0),Pk({hasLoadedInitialResults:U,isLoading:we})&&Qe(f.id,T))},onClearSelection:()=>oe("")}),Ae&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${Ke==="info"?"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:q,children:u("common.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:Vt,disabled:q||(x==="mesh"?!R||!T||W!=="cli"||M:!W||!T||C==="__custom__"&&!Ye),children:[s.jsx(Xd,{size:14}),q?Re:ys]})]})]})}),tt&&s.jsx(nl,{title:u("newSession.selectWorkspaceTitle"),description:u("newSession.selectWorkspaceDescription"),currentPath:ke,directories:Ie,busy:ct,error:Ot,onClose:()=>qe(!1),onNavigate:It,onConfirm:se=>{N(se),ot(se),y("__custom__"),qe(!1)}}),he&&Je&&s.jsx(bp,{activeConv:Je,ides:[],isCreatingChat:!1,isRefreshingHistory:we,savedSessions:je,isSavedSessionsLoading:we,isResumingSavedSessionId:Se,savedHistoryFilters:D,missingWorkspaceResumePath:Ye||null,onSavedHistoryFiltersChange:de,onClose:()=>le(!1),onNewChat:()=>{oe(""),le(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!f||!T||Qe(f.id,T)},onResumeSavedSession:se=>{if(!f||!T||Se||!se.canResume)return;const He=ts(se);oe(se.providerSessionId),us(se),ue(se.providerSessionId),le(!1),ve(!0),Ne(""),i(f.id,"cli",T,{workspaceId:He.workspaceId,workspacePath:He.workspacePath,resumeSessionId:se.providerSessionId}).then(Pe=>{if(!Pe.ok){ie("error"),Ne(Pe.error||u("newSession.errorResumeSession"));return}r()}).finally(()=>{ve(!1),ue(Pe=>Pe===se.providerSessionId?null:Pe)})}})]}):null}function bm(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 ol(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=bm(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 il(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function gm(e){var t;return!il(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 En(e){return[...new Set(e.filter(t=>!!t))]}function Fk(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?En([t==null?void 0:t.id,...n.map(i=>i.id)]):a.length>0?En(a.map(i=>i.id)):o.length>0?En(o.map(i=>i.id)):En(e.nodes.map(i=>i.id))}function ym(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 Ok(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${ym(e)}::${n}x${a}`}const Hk={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"},Wk={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"},Kk={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"},Uk={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 Ds(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-[var(--z-modal-backdrop)] 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=>Wk[t],actionButton:t=>Uk[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-[var(--z-modal-backdrop)] 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=>Hk[t],actionButton:t=>Kk[t]}}const kr={worktreeCardWidth:256,submoduleCardWidth:228,minWorktreeCardHeight:174,minSubmoduleCardHeight:146,maxEstimatedCardHeight:304,layerGap:220,nodeGap:82,edgeLabelBuffer:180,placeholderTopOffset:0},gn={worktreeCardWidth:188,submoduleCardWidth:188,minWorktreeCardHeight:88,minSubmoduleCardHeight:88,maxEstimatedCardHeight:178,layerGap:160,nodeGap:52,edgeLabelBuffer:120},Gk={maxWidth:180};function zk(e){return e==="TB"?"DOWN":"RIGHT"}function ll(e,t){return{"elk.algorithm":"layered","elk.direction":zk(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 Vk=ll(kr,"LR");ll(gn,"LR");function qk(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 Yk=new Ih;function un(e,t=!1){const r=t?gn:kr;return e.type==="submoduleNode"?r.submoduleCardWidth:r.worktreeCardWidth}function Xn(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=bm(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 vm(e,t=!1){const r=t?gn:kr,n=un(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(Jk(e)/o),c=Bn(e.label,a,2),d=Bn(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,a,2),p=Bn(Xn(e),a+(t?1:4),t?2:3),u=ol(e),m=gm(e)?il(e):null,h=t?0:Bn(m,Math.max(24,Math.floor(n/8)),4),g=t?40+c*16+d*12+(u?22:0)+Math.max(0,i-1)*18+Math.max(18,p*16):52+c*18+d*14+(u?30:0)+i*24+Math.max(22,p*18)+(h>0?22+h*16:0),k=e.type==="submoduleNode"?r.minSubmoduleCardHeight:r.minWorktreeCardHeight;return Math.min(r.maxEstimatedCardHeight,Math.max(k,Math.ceil(g)))}function Bn(e,t,r){const n=(e||"").trim();return n?Math.max(1,Math.min(r,Math.ceil(n.length/t))):0}function Jk(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 Xk(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 Qk(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.id.localeCompare(t.id)}function Zk(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 e1(e,t,r){return{id:e.id,x:t,y:r,width:un(e),height:vm(e)}}function t1(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 wm(e){const t=[...e.nodes].sort(Xk),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,t1(r,e)]}function s1(e,t=Vk,r=!1,n="LR"){const a=wm(e),o=new Set(a.map(d=>d.id)),i=a.map(d=>({id:d.id,width:un(d,r),height:vm(d,r)})),c=e.edges.filter(d=>o.has(d.source)&&o.has(d.target)).sort(Qk).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 r1(e,t=!1){const r=[...new Set(e.map(a=>Math.round(a.x)))].sort((a,o)=>a-o),n=t?gn.layerGap:kr.layerGap;return r.length<2?n:Math.min(...r.slice(1).map((a,o)=>a-r[o]))}async function jm(e,t=!1,r="LR",n){var k,f;const o=ll(t?gn:kr,r),i=wm(e),c=new Map(i.map(v=>[v.id,v])),d=s1(e,o,t,r);if(n&&n.size>0)for(const v of d.children??[]){const w=n.get(v.id);w&&w>0&&(v.height=w)}const p=await Yk.layout(d),u=(p.children??[]).map(v=>{const w=c.get(v.id);return w?Zk(w,Math.round(v.x??0),Math.round(v.y??kr.placeholderTopOffset),!v.id.endsWith("__placeholder")):null}).filter(Boolean),m=new Map(i.map((v,w)=>[v.id,w]));u.sort((v,w)=>(m.get(v.id)??0)-(m.get(w.id)??0));const h=u.map(v=>e1(v.graphNode,v.position.x,v.position.y)),g=new Map;for(const v of p.edges??[]){const w=v.sections;if(!w||w.length===0)continue;const x=w[0],j=(k=v.sources)==null?void 0:k[0],C=(f=v.targets)==null?void 0:f[0];if(!j||!C)continue;const y=[];y.push({x:Math.round(x.startPoint.x),y:Math.round(x.startPoint.y)});for(const b of x.bendPoints??[])y.push({x:Math.round(b.x),y:Math.round(b.y)});y.push({x:Math.round(x.endPoint.x),y:Math.round(x.endPoint.y)}),g.set(v.id,{id:v.id,source:j,target:C,points:y})}return{nodes:u,bounds:h,edgeRoutes:g,columnGap:r1(h,t),layoutOptions:{...o}}}function n1(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 km(e){return[e.id,e.source,e.target,e.type,e.label??"",e.direction].join("|")}function a1(e){return[e.meshId,e.refreshedAt,e.nodes.length,e.edges.length,...e.nodes.map(n1),...e.edges.map(km)].join("::")}function o1(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(km)].join("::")}const i1=5*60*1e3;function Sm(e){return typeof e.daemonId=="string"&&e.daemonId.trim()?e.daemonId.trim():null}function Nm(e){return typeof e.machineId=="string"&&e.machineId.trim()?e.machineId.trim():null}function l1(e){var t,r,n;return((t=e.connection)==null?void 0:t.state)==="self"||e.isLocalWorktree===!0?"local":((r=e.connection)==null?void 0:r.transport)==="direct"||((n=e.connection)==null?void 0:n.transport)==="relay"||Sm(e)||Nm(e)?"remote":"unknown"}function c1(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 Cm(e){const t=e.connectionTransport;if(t==="direct"||t==="relay"||t==="local")return t;const r=e.connectionState;return r==="connecting"?"connecting":r==="disconnected"?"disconnected":r==="failed"?"failed":r==="closed"?"closed":null}function d1(e){if(e.connectionTransport==="local"||e.connectionState==="self")return null;const t=Cm(e);return!t||t==="local"||typeof e.connectionRttMs!="number"||!Number.isFinite(e.connectionRttMs)?null:`${Math.round(e.connectionRttMs)}ms`}function u1(e){return Fi(e)}function Im(e){var t;return u1(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function Am(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function p1(e){return e.activeSessionDetails&&e.activeSessionDetails.length>0?e.activeSessionDetails:(e.activeSessions??[]).map(t=>({sessionId:t,workspace:e.workspace,isCached:!0}))}function Mm(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function Tm(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function cl(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function m1(e){return cl(e)?"degraded":Tm(e)?"dirty":"online"}function h1(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function Xc(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 ko(e){return e.length===0?"unknown":e.reduce((t,r)=>Xc(r)>Xc(t)?r:t)}function f1(e){var o,i,c,d,p;const t=new Map,r=new Map;for(const u of e){const m=(i=(o=u.git)==null?void 0:o.branch)==null?void 0:i.trim();m&&(r.set(m,(r.get(m)??0)+1),(c=u.git)!=null&&c.upstream&&t.set(m,(t.get(m)??0)+1))}const n=[...t.entries()].sort((u,m)=>{if(m[1]!==u[1])return m[1]-u[1];const h=["main","master","develop","dev"],g=h.indexOf(u[0]),k=h.indexOf(m[0]);return g!==-1||k!==-1?g===-1?1:k===-1?-1:g-k:u[0].localeCompare(m[0])});return(d=n[0])!=null&&d[0]?n[0][0]:((p=[...r.entries()].sort((u,m)=>m[1]-u[1])[0])==null?void 0:p[0])??null}function x1(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 Qc(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 b1(e){return e.reduce((t,r)=>Qc(r.status)>Qc(t.status)?r:t)}function g1(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 y1(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 v1(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 Zc(e){switch(e){case"running":case"accepted":return 0;case"failed":return 1;case"completed":default:return 2}}function ed(e){const t=e.lastUpdatedAt||e.completedAt||e.startedAt||"";return Am(t)??0}function w1(e){return e.length===0?null:e.reduce((t,r)=>{const n=Zc(t.status),a=Zc(r.status);return a!==n?a<n?r:t:ed(r)>ed(t)?r:t})}function j1(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 k1(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 S1(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 N1(e,t){if(Im(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=Mm(a)||Tm(a),i=!!(a!=null&&a.hasConflicts)||cl(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,u=(a==null?void 0:a.upstream)??null,m=(a==null?void 0:a.upstreamStatus)??null,h=r.defaultBranch??t??null;return{status:n,needsConvergence:r.needsConvergence??n!=="merged_to_main",reason:r.reason??"provided_by_coordinator",nextStep:r.nextStep??null,branch:r.branch??p,defaultBranch:h,upstream:r.upstream??u,upstreamStatus:r.upstreamStatus??m,ahead:r.ahead??c,behind:r.behind??d,dirty:r.dirty??o,hasConflicts:r.hasConflicts??i}}function C1(e,t){const r=N1(e,t);return r?{...r,defaultBranch:r.defaultBranch??t}:null}function I1(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function A1(e){var d,p,u;const{nodeStatus:t,expectedSubmodulePaths:r,refreshedAtMs:n}=e,a=[],o=t.machineLabel||t.nodeId,i=t.git;if(!i){if(Im(t))return a.push(`${o} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:a};const m=t.health==="online"||t.machineStatus==="online"||((d=t.connection)==null?void 0:d.state)==="connected"||((p=t.connection)==null?void 0:p.state)==="self";return a.push(m?`${o} is online but no peer git snapshot is visible yet.`:`${o} has no peer git snapshot visible yet.`),{snapshotCompleteness:"missing_git",snapshotWarnings:a}}const c=new Set((i.submodules??[]).map(m=>m.path));if(r.size>0){const m=[...r].filter(h=>!c.has(h));m.length>0&&a.push(`${o} is missing submodule visibility for ${m.join(", ")} even though another peer reported it.`)}return((u=t.connection)==null?void 0:u.state)!=="self"&&n!==null&&typeof i.lastCheckedAt=="number"&&n-i.lastCheckedAt>i1&&a.push(`${o} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),a.some(m=>m.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:a}:a.some(m=>m.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:a}:{snapshotCompleteness:"complete",snapshotWarnings:a}}function _m(e){const t=Tu(e),n=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??f1(t.nodes),a=Am(t.refreshedAt),o=new Set(t.nodes.flatMap(_=>{var H;return(((H=_.git)==null?void 0:H.submodules)??[]).map(W=>W.path)})),i=[],c=[],d=y1(t),p=new Map,u=j1(v1(t));for(const _ of t.nodes){const H=_.git,W=(H==null?void 0:H.branch)??null,B=m1(H),T=Mm(H)||B==="dirty",A=x1(_,n),E=C1(_,n),z=A1({nodeStatus:_,expectedSubmodulePaths:o,refreshedAtMs:a}),G=typeof _.clonedFromNodeId=="string"?_.clonedFromNodeId:null,re=p1(_),X=w1(u.get(_.nodeId)??[]),te=c1(_),J={id:_.nodeId,type:A.length>0?"orphanNode":"worktreeNode",label:_.machineLabel||_.nodeId.slice(0,8),workspace:_.workspace,branch:W,upstream:(H==null?void 0:H.upstream)??null,upstreamStatus:(H==null?void 0:H.upstreamStatus)??null,daemonId:Sm(_),machineId:Nm(_),machineLabel:_.machineLabel||null,locality:l1(_),connectionTransport:te.connectionTransport,connectionState:te.connectionState,connectionReason:te.connectionReason,connectionReported:te.connectionReported,connectionRttMs:te.connectionRttMs,health:ko([_.health,B]),ahead:(H==null?void 0:H.ahead)??0,behind:(H==null?void 0:H.behind)??0,dirty:T,dirtyFiles:h1(H),hasConflicts:(H==null?void 0:H.hasConflicts)??!1,activeSessionCount:re.length,activeSessions:re.map(F=>F.sessionId),sessionDetails:re,providers:_.providers??[],isOrphan:A.length>0,orphanReasons:A,error:_.error,nextStepHint:z.snapshotWarnings[0]??A[0]??(E==null?void 0:E.nextStep)??void 0,parentNodeId:null,clonedFromNodeId:G,worktreeBranch:_.worktreeBranch??null,submodulePath:null,submoduleCommit:(H==null?void 0:H.headCommit)??null,outOfSync:cl(H),snapshotCompleteness:z.snapshotCompleteness,snapshotWarnings:z.snapshotWarnings,branchConvergence:E,refineJobStatus:(X==null?void 0:X.status)??null,refineJobId:(X==null?void 0:X.jobId)??null,refineJobBranch:(X==null?void 0:X.branch)??null,refineJobInto:(X==null?void 0:X.into)??null,source:_};if(i.push(J),W){const F=p.get(W)??[];F.push(J.id),p.set(W,F)}for(const F of(H==null?void 0:H.submodules)??[]){const K=`${J.id}::submodule::${F.path}`,fe=F.path.split("/").filter(Boolean).pop()||F.path;i.push({id:K,type:"submoduleNode",label:fe,workspace:F.repoPath,branch:null,upstream:null,upstreamStatus:null,daemonId:J.daemonId,machineId:J.machineId,machineLabel:J.machineLabel,locality:J.locality,connectionTransport:J.connectionTransport,connectionState:J.connectionState,connectionReason:J.connectionReason,connectionReported:J.connectionReported,connectionRttMs:J.connectionRttMs,health:I1(F),ahead:0,behind:0,dirty:F.dirty,dirtyFiles:F.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],error:F.error,nextStepHint:F.error||(F.outOfSync?`${F.path} is out of sync with the parent checkout`:F.dirty?`${F.path} has local changes`:`${F.path} is in sync with the parent checkout`),parentNodeId:J.id,submodulePath:F.path,submoduleCommit:F.commit,outOfSync:F.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:J.id,parentWorkspace:_.workspace,submodule:F}}),c.push({id:`${J.id}--${K}`,source:J.id,target:K,type:"submoduleLink",label:F.outOfSync?"submodule out of sync":"submodule",direction:"directed"})}}const m=n?`__branch_${n}`:null;if(m&&n){const H=(p.get(n)??[]).map(G=>i.find(re=>re.id===G)).filter(Boolean),W=H.map(G=>G.branchConvergence).filter(Boolean),B=g1(t),T=H.length>0&&H.every(G=>k1(G,n)),A=(B==null?void 0:B.length)===0&&T?S1(n,H):W.length>0?b1(W):null,E=(B==null?void 0:B.length)===0&&T?0:W.filter(G=>G.needsConvergence).length,z={id:m,type:"defaultBranchNode",label:n,workspace:t.repoIdentity,branch:n,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:"default branch",locality:"unknown",connectionTransport:null,connectionState:null,connectionReason:null,connectionReported:!1,connectionRttMs:null,health:ko(H.map(G=>G.health)),ahead:0,behind:0,dirty:H.some(G=>G.dirty),dirtyFiles:H.reduce((G,re)=>G+re.dirtyFiles,0),hasConflicts:H.some(G=>G.hasConflicts),activeSessionCount:H.reduce((G,re)=>G+re.activeSessionCount,0),activeSessions:H.flatMap(G=>G.activeSessions),sessionDetails:H.flatMap(G=>G.sessionDetails),providers:[...new Set(H.flatMap(G=>G.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:E>0?`${E} workspace(s) on ${n} still need follow-up`:H.length>0?`${H.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:A,source:{nodeId:m,machineLabel:n,workspace:t.repoIdentity,health:ko(H.map(G=>G.health)),providers:[],activeSessions:[],activeSessionDetails:[]}};i.push(z);for(const G of i)if(!(G.id===m||G.type==="submoduleNode")){if(G.branch===n){c.push({id:`${m}--${G.id}`,source:m,target:G.id,type:"parentBranch",label:"checked out",direction:"undirected"});continue}if(G.branch){c.push({id:`${m}--${G.id}`,source:m,target:G.id,type:G.isOrphan?"orphanLink":"parentBranch",label:G.branch,direction:"undirected"});continue}G.isOrphan&&c.push({id:`${m}--${G.id}`,source:m,target:G.id,type:"orphanLink",label:"detached",direction:"undirected"})}}const h=new Set(i.map(_=>_.id)),g=new Set;for(const _ of i){if(!_.clonedFromNodeId||_.type==="submoduleNode"||!h.has(_.clonedFromNodeId))continue;const H=`clone_${_.clonedFromNodeId}--${_.id}`;if(g.has(H))continue;g.add(H);const W=_.worktreeBranch??_.branch??void 0;c.push({id:H,source:_.clonedFromNodeId,target:_.id,type:"cloneLink",label:W?`cloned · ${W}`:"cloned",direction:"directed"})}const k=i.filter(_=>_.type!=="defaultBranchNode"),f=k.filter(_=>_.isOrphan).length,v=k.filter(_=>_.hasConflicts).length,w=k.filter(_=>_.health==="offline").length,x=k.filter(_=>_.type==="submoduleNode"&&_.outOfSync).length,j=k.filter(_=>{var H;return _.type!=="submoduleNode"&&((H=_.branchConvergence)==null?void 0:H.needsConvergence)}).length,C=k.filter(_=>{var H;return((H=_.branchConvergence)==null?void 0:H.status)==="blocked_review"}).length,y=k.filter(_=>{var H;return((H=_.branchConvergence)==null?void 0:H.status)==="pushed_feature_branch_needs_merge"}).length,b=k.filter(_=>{var H;return((H=_.branchConvergence)==null?void 0:H.status)==="cleanup_candidate"}).length,N=k.filter(_=>{var H;return((H=_.branchConvergence)==null?void 0:H.status)==="not_mergeable"}).length,S=k.filter(_=>_.snapshotWarnings.length>0).length,I=k.filter(_=>_.snapshotCompleteness==="pending_git").length,R=k.filter(_=>_.snapshotCompleteness==="missing_git").length,L=k.filter(_=>_.snapshotCompleteness==="missing_submodule_report").length,M=k.filter(_=>_.snapshotCompleteness==="stale").length,P=k.filter(_=>_.refineJobStatus==="running"||_.refineJobStatus==="accepted").length,$=k.filter(_=>_.refineJobStatus==="failed").length,Y=[I>0?`${I} node(s) are still waiting for a live peer git snapshot`:null,R>0?`${R} node(s) have no visible peer git snapshot`:null,L>0?`${L} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,M>0?`${M} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return j>0&&d.push(`${j} workspace(s) still need follow-up before the mesh is converged`),f>0&&d.push(`${f} workspace(s) need attention before safe coordination`),C>0&&d.push(`${C} workspace(s) are blocked on branch convergence or upstream sync`),y>0&&d.push(`${y} clean feature branch workspace(s) still need merge follow-up`),b>0&&d.push(`${b} worktree workspace(s) are ready for refine / cleanup`),N>0&&d.push(`${N} workspace(s) have local changes or conflicts blocking convergence`),v>0&&d.push(`${v} workspace(s) report merge conflicts`),w>0&&d.push(`${w} node(s) are currently offline`),x>0&&d.push(`${x} submodule(s) are out of sync with their parent checkout`),d.push(...Y),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:k.length,onlineNodes:k.filter(_=>_.health==="online").length,dirtyNodes:k.filter(_=>_.dirty).length,orphanNodes:f,errorNodes:k.filter(_=>!!_.error||_.outOfSync).length,offlineNodes:w,followUpNodes:j,blockedReviewNodes:C,mergeReadyNodes:y,cleanupCandidateNodes:b,notMergeableNodes:N,incompleteSnapshotNodes:S,pendingGitSnapshotNodes:I,missingGitSnapshotNodes:R,missingSubmoduleSnapshotNodes:L,staleGitSnapshotNodes:M,activeRefineNodes:P,failedRefineNodes:$,totalActiveSessions:k.reduce((_,H)=>_+H.activeSessionCount,0)},warnings:d,snapshotWarnings:Y}}function M1(e){return!e.nodes.some(t=>t.snapshotCompleteness==="pending_git"||t.snapshotCompleteness==="missing_git"||t.snapshotCompleteness==="missing_submodule_report")}const T1=7,_1=640,dl=l.createContext(Ds("dark")),Lm=l.createContext(!1),Rm=l.createContext("LR"),Pm={overflowWrap:"anywhere",wordBreak:"break-word"},L1={...Pm,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:3,overflow:"hidden"},R1={...Pm,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:4,overflow:"hidden"};function Dm(e){return e.activeSessionCount>0}function P1(e){return e.health==="offline"||e.snapshotCompleteness==="stale"&&e.activeSessionCount===0}function td(e,t,r){const n=Dm(e),a=P1(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=ol(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 _t(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 sd(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 rd(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 D1(e){return e.replace(/_/g," ")}function ps(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 $1(e){var t;return((t=e.sessionDetails)==null?void 0:t.some(r=>ps(r)==="generating"))??!1}function So(e,t){const r=ps(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":_t("health",t)}function E1(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function nd(e){const t=E1(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 No(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function Hr(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function B1(e){if(e.sessionDetails.length===0)return null;const t=e.sessionDetails.filter(o=>ps(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 ad(e){return e==="local"?"local":e==="remote"?"remote":"machine unknown"}function F1(e){return e.locality==="remote"?"meta":"health"}function O1({data:e,selected:t}){const r=l.useContext(dl),n=l.useContext(Lm),a=l.useContext(Rm),o=e.graphNode,i=o.type==="defaultBranchNode",c=o.type==="submoduleNode",d=gm(o),p=i?"default branch anchor":c?o.submodulePath||"submodule checkout":[o.machineLabel,ad(o.locality)].filter(Boolean).join(" · ")||o.workspace,u=o.submoduleCommit?o.submoduleCommit.slice(0,7):null,m=!c&&!i&&o.connectionState!=="self",h=m?Cm(o):null,g=h==="local"?null:h,k=m?d1(o):null,f=ol(o),v=il(o),w=Dm(o),x=o.sessionDetails,j=o.sessionDetails,C=B1(o),y=o.sessionDetails.map(N=>{const S=ps(N),I=N.providerType||"provider unknown",R=Hr(N),L=N.startedAt||N.createdAt||null,M=N.statusNote?` · ${N.statusNote}`:"";return`Session: ${N.sessionId} · ${I} · ${S} · ${R} · ${nd(L)}${M}`});if(n)return s.jsxs("div",{className:`rounded-xl border px-3 py-2.5 backdrop-blur-sm transition-all ${td(o,t,r.isDark)}`,style:{width:un(o,!0)},title:[o.label,o.branch?`Branch: ${o.branch}`:null,o.machineLabel?`Machine: ${o.machineLabel}`:null,o.workspace?`Workspace: ${o.workspace}`:null,f?`Status: ${f.label}`:null,Xn(o),...y].filter(Boolean).join(`
|
|
77
|
+
`),children:[s.jsx(vn,{type:"target",position:a==="TB"?Ns.Top:Ns.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:[w&&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:rd(o.health)},"aria-hidden":!0})]})]}),o.health==="unknown"&&!f&&s.jsx("div",{className:`mt-1.5 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[9px] italic ${_t("health",r.isDark)}`,children:s.jsx("span",{className:"truncate",children:"Connecting..."})}),f&&s.jsx("div",{className:`mt-1.5 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[9px] font-semibold uppercase tracking-[0.14em] ${sd(f.tone,r.isDark)}`,title:f.label,children:s.jsx("span",{className:"truncate",children:f.label})}),!f&&o.branch&&!c&&o.health!=="unknown"&&s.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[10px] ${_t("meta",r.isDark)} rounded-full border px-2 py-0.5 inline-block`,title:o.branch,children:o.branch}),C&&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:y.join(`
|
|
78
|
+
`),children:C}),j.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:j.map(N=>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: ${N.sessionId}`,N.providerType?`Provider: ${N.providerType}`:null,`Status: ${ps(N)}`,`Role: ${Hr(N)}`].filter(Boolean).join(`
|
|
79
|
+
`),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:N.providerType||"provider unknown"}),s.jsx("span",{className:`shrink-0 rounded-full border px-1 py-0 text-[8px] font-semibold uppercase tracking-[0.1em] ${So(N,r.isDark)}`,children:ps(N)})]}),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:No(N.sessionId)}),s.jsx("span",{className:"shrink-0",children:Hr(N)})]})]},N.sessionId))}),s.jsx(vn,{type:"source",position:a==="TB"?Ns.Bottom:Ns.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]});const b=[o.label,p,f?`Status: ${f.label}`:null,Xn(o),o.branch?`Branch: ${o.branch}`:null,o.dirty?c?"Local changes":`${o.dirtyFiles} dirty`:null,o.hasConflicts?"Has conflicts":null,o.outOfSync?"Out of sync":null,!c&&o.upstream&&o.upstreamStatus!=="fresh"?"Upstream unverified":null,o.isOrphan?"Needs follow-up":null,d&&v?`Note: ${v}`:null,...y].filter(Boolean).join(`
|
|
80
|
+
`);return s.jsxs("div",{className:`rounded-2xl border px-4 py-3 backdrop-blur-sm transition-all ${td(o,t,r.isDark)}${$1(o)?" mesh-node-generating":""}`,style:{width:un(o)},title:b,children:[s.jsx(vn,{type:"target",position:a==="TB"?Ns.Top:Ns.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:[w&&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:rd(o.health)},"aria-hidden":!0})]})]}),f?s.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${sd(f.tone,r.isDark)}`,title:f.label,children:s.jsx("span",{className:"truncate",children:f.label})}):o.branch&&!c?s.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[10px] ${_t("meta",r.isDark)}`,title:o.branch,children:s.jsx("span",{className:"truncate",children:o.branch})}):null,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] 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:y.join(`
|
|
81
|
+
`),children:s.jsx("span",{className:"truncate",children:C})}),j.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:j.map(N=>{const S=Hr(N);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: ${N.sessionId}`,N.providerType?`Provider: ${N.providerType}`:null,`Status: ${ps(N)}`,`Role: ${S}`].filter(Boolean).join(`
|
|
82
|
+
`),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:N.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] ${So(N,r.isDark)}`,children:ps(N)})]}),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:No(N.sessionId)}),s.jsx("span",{children:S})]})]},N.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 ${_t("health",r.isDark)}`,children:"connecting..."}):s.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${_t("health",r.isDark)}`,children:D1(o.health)}),c&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${_t("submodule",r.isDark)}`,children:"submodule"}),!i&&o.health==="unknown"&&!o.locality&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 italic ${_t("health",r.isDark)}`,children:"..."}),!i&&(o.health!=="unknown"||o.locality)&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${_t(F1(o),r.isDark)}`,children:ad(o.locality)}),g&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${_t("meta",r.isDark)}`,title:g==="relay"?"P2P link relayed through TURN (slower path)":`P2P transport: ${g}`,children:g}),k&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${_t("meta",r.isDark)}`,title:"P2P round-trip latency",children:k}),u&&c&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${_t("meta",r.isDark)}`,children:u}),o.dirty&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${_t("dirty",r.isDark)}`,children:c?"local changes":`${o.dirtyFiles} dirty`}),o.outOfSync&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${_t("conflict",r.isDark)}`,children:"out of sync"}),o.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${_t("conflict",r.isDark)}`,children:"conflicts"}),!c&&o.upstream&&o.upstreamStatus!=="fresh"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${_t("orphan",r.isDark)}`,children:"upstream unverified"}),o.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${_t("orphan",r.isDark)}`,children:"needs follow-up"}),!c&&o.refineJobStatus==="completed"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${_t("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:L1,children:Xn(o)}),x.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:x.map(N=>{const S=N.startedAt||N.createdAt||null,I=Hr(N);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: ${N.sessionId}`,N.providerType?`Provider: ${N.providerType}`:null,`Status: ${ps(N)}`,`Role: ${I}`,S?`Started: ${S}`:"Started: not reported",N.statusNote?`Note: ${N.statusNote}`:null].filter(Boolean).join(`
|
|
83
|
+
`),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:No(N.sessionId)}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${So(N,r.isDark)}`,children:ps(N)})]}),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:N.providerType||"provider unknown"}),s.jsx("span",{children:I}),s.jsx("span",{children:nd(S)})]}),N.statusNote&&s.jsx("div",{className:`mt-1 text-[9px] leading-4 ${r.textMuted}`,children:N.statusNote})]},N.sessionId)})})]}),d&&v&&s.jsx("div",{className:`mt-3 rounded-xl border px-3 py-2 text-[10px] leading-4 ${r.isDark?"border-cyan-400/15 bg-cyan-500/8 text-cyan-50/90":"border-sky-300 bg-sky-50 text-sky-700"}`,style:R1,children:v})]}),s.jsx(vn,{type:"source",position:a==="TB"?Ns.Bottom:Ns.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const H1={meshNode:O1},W1=8;function K1(e){if(e.length<2)return null;if(e.length===2){const[p,u]=e;return{d:`M ${p.x},${p.y} L ${u.x},${u.y}`,labelX:(p.x+u.x)/2,labelY:(p.y+u.y)/2}}const t=W1,r=[`M ${e[0].x},${e[0].y}`];for(let p=1;p<e.length-1;p+=1){const u=e[p-1],m=e[p],h=e[p+1],g=Math.sign(m.x-u.x),k=Math.sign(m.y-u.y),f=Math.sign(h.x-m.x),v=Math.sign(h.y-m.y),w=Math.hypot(m.x-u.x,m.y-u.y),x=Math.hypot(h.x-m.x,h.y-m.y),j=Math.min(t,w/2,x/2);if(j<1||g===f&&k===v){r.push(`L ${m.x},${m.y}`);continue}const C=m.x-g*j,y=m.y-k*j,b=m.x+f*j,N=m.y+v*j;r.push(`L ${C},${y}`),r.push(`Q ${m.x},${m.y} ${b},${N}`)}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 u=o[p]-o[p-1],m=u===0?0:(i-o[p-1])/u;c=e[p-1].x+(e[p].x-e[p-1].x)*m,d=e[p-1].y+(e[p].y-e[p-1].y)*m;break}return{d:r.join(" "),labelX:c,labelY:d}}function U1(e){const t=e.data.routePoints;if(t&&t.length>=2){const o=K1(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=Bh(r):a=Fh(r),[a[0],a[1],a[2]]}function G1(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 z1(e){const t=l.useContext(dl),r=e.data.graphEdge,[n,a,o]=U1(e),i=typeof e.label=="string"?e.label:void 0;return s.jsxs(s.Fragment,{children:[s.jsx(Rh,{id:e.id,path:n,markerEnd:e.markerEnd,style:e.style,interactionWidth:24}),e.label&&s.jsx(Ph,{children:s.jsx("div",{className:G1(r,t.isDark),title:i,style:{position:"absolute",transform:`translate(-50%, -50%) translate(${a}px, ${o}px)`,pointerEvents:"none",maxWidth:Gk.maxWidth},children:s.jsx("span",{className:"block truncate",children:e.label})})})]})}const V1={meshEdge:z1};async function q1(e,t,r,n,a){const o=await jm(e,r,n,a);return $m(e,o,t,r)}async function Y1(e,t=Ds("dark"),r=!1,n="LR"){const a=await jm(e,r,n);return $m(e,a,t,r)}function $m(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=Q1(i),d=i.map(p=>{var u;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:(u=t.edgeRoutes.get(p.id))==null?void 0:u.points},animated:p.type==="orphanLink",markerEnd:p.direction==="directed"?{type:Eh.ArrowClosed,width:p.type==="submoduleLink"?16:18,height:p.type==="submoduleLink"?16:18,color:id(p)}:void 0,style:{stroke:id(p),strokeWidth:p.type==="orphanLink"?2.25:p.type==="submoduleLink"?1.7:p.type==="worktreeLink"?1.8:p.type==="cloneLink"?1.6: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 J1=3,X1=2;function od(e){switch(e.type){case"orphanLink":return 5;case"parentBranch":return 4;case"submoduleLink":return 3;case"cloneLink":return 2;case"worktreeLink":return 1;case"sessionLink":return 0;default:return 0}}function Q1(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<J1){for(const o of n)t.add(o.id);continue}const a=[...n].sort((o,i)=>{const c=od(i)-od(o);return c!==0?c:o.id.localeCompare(i.id)});for(const o of a.slice(0,X1))t.add(o.id)}return t}function id(e){switch(e.type){case"parentBranch":return"#38bdf8";case"worktreeLink":return"#a78bfa";case"sessionLink":return"#34d399";case"orphanLink":return"#f97316";case"submoduleLink":return"#c084fc";case"cloneLink":return"#2dd4bf";default:return"#64748b"}}function Z1(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 eS(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 tS({data:e,viewportKey:t}){const r=Dh(),n=$h(),a=l.useRef(null),o=l.useMemo(()=>ym(e),[e]),i=l.useMemo(()=>Fk(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(u=>({id:u})):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 sS=12;function rS(e){return e>=16?"min-h-[720px]":e>=10?"min-h-[580px]":"min-h-[460px]"}function nS({data:e,selectedNodeId:t=null,directionPref:r,onNodeClick:n,onEdgeClick:a,onNodeHoverChange:o,onEdgeHoverChange:i}){const{theme:c}=Ps(),d=l.useMemo(()=>Ds(c),[c]),p=l.useMemo(()=>a1(e),[e]),u=l.useMemo(()=>o1(e),[e]),m=l.useRef(null),[h,g]=l.useState({width:0,height:0}),k=h.width>0&&h.width<_1,f=e.nodes.length>=T1||k,[v]=l.useState("LR"),w=r??v,x=l.useMemo(()=>r==="LR"||r==="TB"?r:k?"TB":w==="auto"?qk(e):w,[w,r,p,e,k]),j=e.nodes.length>=sS,[C,y]=l.useState({nodes:[],edges:[]}),b=l.useMemo(()=>`${Ok(e,h.width,h.height)}::${x}`,[p,e,h.height,h.width,x]);l.useEffect(()=>{let S=!1;return Y1(e,d,f,x).then(I=>{if(S)return;y(I);const R=requestAnimationFrame(()=>{if(S)return;const L=m.current;if(!L)return;const M=new Map;for(const P of I.nodes){const $=L.querySelector(`.react-flow__node[data-id="${CSS.escape(P.id)}"]`);$&&$.offsetHeight>0&&M.set(P.id,$.offsetHeight)}M.size!==0&&q1(e,d,f,x,M).then(P=>{S||y(P)})});return()=>cancelAnimationFrame(R)}),()=>{S=!0}},[e,u,d,f,x]);const N=l.useMemo(()=>C.nodes.map(S=>({...S,selected:S.id===t})),[C.nodes,t]);return l.useEffect(()=>{const S=m.current;if(!S)return;const I=()=>{const L=Math.max(0,Math.round(S.clientWidth)),M=Math.max(0,Math.round(S.clientHeight));g(P=>P.width===L&&P.height===M?P:{width:L,height:M})};I();const R=typeof ResizeObserver=="function"?new ResizeObserver(()=>I()):null;return R==null||R.observe(S),window.addEventListener("resize",I),()=>{R==null||R.disconnect(),window.removeEventListener("resize",I)}},[]),s.jsx(dl.Provider,{value:d,children:s.jsx(Lm.Provider,{value:f,children:s.jsx(Rm.Provider,{value:x,children:s.jsxs("div",{ref:m,className:`${d.graphShellClass} ${rS(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(Ah,{nodes:N,edges:C.edges,nodeTypes:H1,edgeTypes:V1,minZoom:k?.3:.18,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(S,I)=>n==null?void 0:n(I.data.graphNode),onEdgeClick:(S,I)=>{var L;const R=(L=I.data)==null?void 0:L.graphEdge;R&&(a==null||a(R))},onNodeMouseEnter:(S,I)=>o==null?void 0:o(I.data.graphNode),onNodeMouseLeave:()=>o==null?void 0:o(null),onEdgeMouseEnter:(S,I)=>{var R;return i==null?void 0:i(((R=I.data)==null?void 0:R.graphEdge)??null)},onEdgeMouseLeave:()=>i==null?void 0:i(null),className:"h-full w-full",colorMode:d.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(tS,{data:e,viewportKey:b}),s.jsx(Mh,{className:d.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),j&&s.jsx(Th,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:Z1,nodeClassName:eS,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(_h,{variant:Lh.Dots,gap:18,size:1.2,color:d.graphBackgroundDotColor})]})})]})})})})}const aS="You are one independent member of a multi-agent cross-verification quorum";function oS(e){var n,a;const t=(e??"").trim();if(!t)return"";if(!t.startsWith(aS))return t;const r=(a=(n=t.match(/\n## Question\n([\s\S]*?)(?:\n## |$)/))==null?void 0:n[1])==null?void 0:a.trim().replace(/\s+/g," ");return r?`MAGI cross-verify — ${r}`:"MAGI cross-verification task"}function iS(e){return`${e.state??""} ${e.chatStatus??""} ${e.lifecycle??""}`.toLowerCase()}function lS(e){if(!Array.isArray(e))return[];const t=[];for(const r of e){const n=r.activeSessionDetails;if(Array.isArray(n))for(const a of n)a!=null&&a.sessionId&&iS(a).includes("approval")&&t.push({nodeId:r.nodeId,sessionId:a.sessionId,providerType:a.providerType,machineLabel:r.machineLabel||r.nodeId,detail:a.statusNote??a.title??null})}return t}function cS({approvals:e,nodes:t,onResolve:r,hideWhenEmpty:n=!0}){const{t:a}=Pt(),o=l.useMemo(()=>e??lS(t),[e,t]),[i,c]=l.useState({});if(n&&o.length===0)return null;const d=(p,u)=>{i[p.sessionId]||(c(m=>({...m,[p.sessionId]:u})),Promise.resolve(r(p.nodeId,p.sessionId,u)).finally(()=>{c(m=>{const h={...m};return delete h[p.sessionId],h})}))};return s.jsxs("div",{className:"rounded-lg border p-3",style:{borderColor:"color-mix(in srgb, var(--status-warning) 40%, transparent)",background:"color-mix(in srgb, var(--status-warning) 8%, transparent)"},children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2 font-black text-xs",style:{color:"var(--status-warning)"},children:[s.jsx(Ys,{size:14}),a("meshGraph.approvals.title"),s.jsxs("span",{className:"opacity-70 font-semibold",children:["(",o.length,")"]})]}),o.length===0?s.jsx("div",{className:"text-[11px] opacity-70",children:a("meshGraph.approvals.empty")}):s.jsx("ul",{className:"flex flex-col gap-2",children:o.map(p=>{const u=i[p.sessionId]??null,m=u!==null;return s.jsxs("li",{className:"flex items-center justify-between gap-3 rounded-md px-2.5 py-2",style:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)"},children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"text-xs font-semibold truncate",children:[p.machineLabel||p.nodeId,p.providerType&&s.jsx("span",{className:"ml-2 opacity-60 font-normal",children:p.providerType})]}),s.jsx("div",{className:"text-[10px] opacity-60 truncate",children:p.detail?p.detail.replace(/[\n\r]+/g," ").slice(0,120):a("meshGraph.approvals.sessionFallback",{id:p.sessionId})})]}),s.jsxs("div",{className:"flex gap-2 shrink-0",children:[s.jsx("button",{onClick:()=>d(p,"approve"),disabled:m,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 font-extrabold ${m?"cursor-not-allowed opacity-60":"cursor-pointer"}`,style:{color:"var(--status-warning)",background:"var(--surface-primary)"},children:u==="approve"?"⏳ ...":a("meshGraph.approvals.approve")}),s.jsx("button",{onClick:()=>d(p,"reject"),disabled:m,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 font-semibold text-white bg-red-500/30 ${m?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:u==="reject"?"⏳ ...":a("meshGraph.approvals.reject")})]})]},`${p.nodeId}:${p.sessionId}`)})})]})}const dS=5,uS=40,pS={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};function Da(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function Em(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 Bm(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 mS(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 Fm(e){switch(e){case"active":return"emerald";case"paused":return"amber";case"completed":return"sky";case"abandoned":return"rose";default:return"muted"}}function hS(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 Om(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 ld(e){switch(e){case"assigned":return 0;case"pending":return 1;case"completed":case"failed":case"cancelled":return 2;default:return 3}}function cs(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 cd(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 ul(e){return e.replace(/[_-]+/g," ")}function Hm(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 Wm(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 fS({status:e,daemonId:t=null,meshId:r=null,sendDaemonCommand:n=null}){var C,y,b,N;const{theme:a}=Ps(),o=l.useMemo(()=>Ds(a),[a]),i=((C=e.queue)==null?void 0:C.summary)??null,c=((y=e.queue)==null?void 0:y.tasks)??[],d=((b=e.ledger)==null?void 0:b.summary)??pS,p=((N=e.ledger)==null?void 0:N.entries)??[],u=e.missions??[],m=u.filter(S=>S.status==="active"||S.status==="paused"),h=u.filter(S=>S.status==="completed"||S.status==="abandoned"),g=e.asyncRefineJobs??[],[k,f]=l.useState(null),v=l.useCallback(()=>f(null),[]),w=l.useCallback(async(S,I,R)=>{!t||!n||await n(t,"mesh_approve",{meshId:r??void 0,node_id:S,session_id:I,action:R})},[t,r,n]),x=l.useCallback(S=>{if(!S)return"";const I=e.nodes.find(R=>R.nodeId===S);return(I==null?void 0:I.machineLabel)||S},[e.nodes]),j=l.useMemo(()=>{const S=[];for(const I of e.nodes){const R=I.activeSessionDetails&&I.activeSessionDetails.length>0?I.activeSessionDetails:(I.activeSessions??[]).map(L=>({sessionId:L,workspace:I.workspace,isCached:!0}));for(const L of R)S.push({node:I,session:L})}return S},[e.nodes]);return s.jsxs("div",{className:"flex flex-col gap-3 pb-2",children:[s.jsx(cS,{nodes:e.nodes,onResolve:w}),s.jsx(SS,{meshTheme:o,liveMissions:m,historyMissions:h,hasMissionField:Array.isArray(e.missions),onSelect:S=>f({kind:"mission",mission:S})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(NS,{meshTheme:o,ledgerSummary:d,entries:p,resolveNodeLabel:x,onSelect:S=>f({kind:"ledger",entry:S})}),s.jsx(CS,{meshTheme:o,queueSummary:i,tasks:c,onSelect:S=>f({kind:"queue",task:S})})]}),s.jsx(AS,{meshTheme:o,nodes:e.nodes}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(MS,{meshTheme:o,entries:j,onSelect:(S,I)=>f({kind:"session",node:S,session:I})}),s.jsx(TS,{meshTheme:o,jobs:g})]}),k&&s.jsx(bS,{meshTheme:o,detail:k,onClose:v,daemonId:t,meshId:r??e.meshId??null,sendDaemonCommand:n,resolveNodeLabel:x})]})}function Xs({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 Ut({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 wt({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 yn({meshTheme:e,children:t}){return s.jsx("div",{className:`text-xs ${e.textMuted}`,children:t})}function $a({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 Ea({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 Ba(e,t=dS){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 ft({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 xS(e){switch(e.kind){case"mission":return{kicker:"Mission",title:e.mission.title};case"ledger":return{kicker:"Ledger entry",title:ul(e.entry.kind)};case"queue":return{kicker:"Queue task",title:e.task.id};case"session":return{kicker:"Session",title:Da(e.session.sessionId)}}}function bS({meshTheme:e,detail:t,onClose:r,daemonId:n,meshId:a,sendDaemonCommand:o,resolveNodeLabel:i}){l.useEffect(()=>{const h=g=>{g.key==="Escape"&&r()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[r]);const c=e.isDark,{kicker:d,title:p}=xS(t),u=c?"bg-[#030617]/[0.92]":"bg-[rgba(15,23,42,0.82)]",m=c?"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-[var(--z-modal)] flex items-stretch justify-center p-0 md:items-center md:p-4 ${u}`,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 ${m} md:h-auto md:max-h-[88dvh] md:max-w-[min(640px,calc(100vw-32px))] md:rounded-2xl`,onClick:h=>h.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 ${c?"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:d}),s.jsx("div",{className:`mt-0.5 break-all text-sm font-semibold ${e.textPrimary}`,children:p})]}),s.jsx("button",{type:"button",onClick:r,"aria-label":"Close detail",className:c?"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(vS,{meshTheme:e,mission:t.mission,daemonId:n,meshId:a,sendDaemonCommand:o}),t.kind==="ledger"&&s.jsx(wS,{meshTheme:e,entry:t.entry,resolveNodeLabel:i}),t.kind==="queue"&&s.jsx(jS,{meshTheme:e,task:t.task}),t.kind==="session"&&s.jsx(kS,{meshTheme:e,node:t.node,session:t.session})]})]})})}const gS=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function yS(e){const t=gS(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function vS({meshTheme:e,mission:t,daemonId:r,meshId:n,sendDaemonCommand:a}){var C;const o=t.tasks,i="goal"in t&&typeof t.goal=="string"&&t.goal?t.goal:"goalPreview"in t?t.goalPreview:"",c="goalTruncated"in t?t.goalTruncated===!0:!1,[d,p]=l.useState(null),[u,m]=l.useState(!1),[h,g]=l.useState(null),k=c&&!d&&!!r&&!!a,f=l.useCallback(async()=>{if(!(!r||!a)){m(!0),g(null);try{const y=await a(r,"mesh_status",{meshId:n??void 0,verbose:!0}),b=yS(y),S=(Array.isArray(b==null?void 0:b.missions)?b.missions:[]).find(R=>(R==null?void 0:R.id)===t.id),I=typeof(S==null?void 0:S.goal)=="string"&&S.goal?S.goal:null;I?p(I):g("Full goal unavailable")}catch(y){g(y instanceof Error?y.message:"Failed to fetch full mission goal")}finally{m(!1)}}},[r,n,a,t.id]),v=d??i,w=c&&!d,x=t.stats??null,j=((C=x==null?void 0:x.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(Ut,{meshTheme:e,label:t.status,tone:Fm(t.status)}),s.jsx(Ut,{meshTheme:e,label:`${o.total} tasks`,tone:"muted"})]}),v&&s.jsxs("div",{className:`max-h-64 overflow-y-auto whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:[v,w&&!k&&s.jsx("span",{className:e.textMuted,children:" … (truncated)"})]}),h&&s.jsx("div",{className:"text-[11px] text-amber-400",children:h}),k&&s.jsx("button",{type:"button",className:"self-start text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:f,disabled:u,children:u?"Loading…":"Show full goal"}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5 sm:grid-cols-6",children:[s.jsx(wt,{meshTheme:e,label:"Completed",value:o.completed,tone:"emerald"}),s.jsx(wt,{meshTheme:e,label:"Assigned",value:o.assigned,tone:o.assigned>0?"sky":void 0}),s.jsx(wt,{meshTheme:e,label:"Pending",value:o.pending}),s.jsx(wt,{meshTheme:e,label:"Failed",value:o.failed,tone:o.failed>0?"rose":void 0}),s.jsx(wt,{meshTheme:e,label:"Blocked",value:o.blocked,tone:o.blocked>0?"amber":void 0}),s.jsx(wt,{meshTheme:e,label:"Cancelled",value:o.cancelled,tone:"muted"})]}),x&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(wt,{meshTheme:e,label:"Wall clock",value:cd(x.wallClockMs)??"—"}),s.jsx(wt,{meshTheme:e,label:"Total runtime",value:cd(x.totalDurationMs)??"—"}),s.jsx(wt,{meshTheme:e,label:"Retries",value:x.retries,tone:x.retries>0?"amber":void 0})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(ft,{meshTheme:e,label:"Mission id",value:t.id}),s.jsx(ft,{meshTheme:e,label:"Created",value:cs(t.createdAt)??t.createdAt}),s.jsx(ft,{meshTheme:e,label:"Updated",value:cs(t.updatedAt)??t.updatedAt}),o.lastActivityAt&&s.jsx(ft,{meshTheme:e,label:"Last task activity",value:cs(o.lastActivityAt)??o.lastActivityAt}),j>0&&x&&s.jsx(ft,{meshTheme:e,label:"Incomplete evidence",value:s.jsxs("details",{children:[s.jsxs("summary",{className:"cursor-pointer select-none",children:[j," task",j===1?"":"s"]}),s.jsx("div",{className:"mt-1 flex flex-col gap-0.5 break-all",children:x.incompleteTaskIds.map(y=>s.jsx("span",{className:`font-mono text-[10px] ${e.textMuted}`,children:y},y))})]})})]})]})}function wS({meshTheme:e,entry:t,resolveNodeLabel:r}){const n=Wm(t.payload);let a="";try{a=JSON.stringify(t.payload??{},null,2)}catch{a=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(Ut,{meshTheme:e,label:ul(t.kind),tone:Hm(t.kind)})}),n&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:n}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(ft,{meshTheme:e,label:"Entry id",value:t.id}),s.jsx(ft,{meshTheme:e,label:"When",value:cs(t.timestamp)??t.timestamp}),t.nodeId&&s.jsx(ft,{meshTheme:e,label:"Node",value:r(t.nodeId)}),t.sessionId&&s.jsx(ft,{meshTheme:e,label:"Session",value:Da(t.sessionId)}),t.providerType&&s.jsx(ft,{meshTheme:e,label:"Provider",value:t.providerType})]}),a&&a!=="{}"&&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:a})]})]})}function jS({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(Ut,{meshTheme:e,label:t.status,tone:Om(t.status)}),(t.requeueCount??0)>0&&s.jsx(Ut,{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(ft,{meshTheme:e,label:"Task id",value:t.id}),s.jsx(ft,{meshTheme:e,label:"Created",value:cs(t.createdAt)??t.createdAt}),s.jsx(ft,{meshTheme:e,label:"Updated",value:cs(t.updatedAt)??t.updatedAt}),(t.assignedNodeId||t.targetNodeId)&&s.jsx(ft,{meshTheme:e,label:"Node",value:t.assignedNodeId||t.targetNodeId}),(t.assignedSessionId||t.targetSessionId)&&s.jsx(ft,{meshTheme:e,label:"Session",value:Da(t.assignedSessionId||t.targetSessionId)}),t.cancelReason&&s.jsx(ft,{meshTheme:e,label:"Cancel reason",value:t.cancelReason}),t.requeueReason&&s.jsx(ft,{meshTheme:e,label:"Requeue reason",value:t.requeueReason}),t.autoLaunch&&s.jsx(ft,{meshTheme:e,label:"Auto launch",value:`${t.autoLaunch.status}${t.autoLaunch.reason?` · ${t.autoLaunch.reason}`:""}`})]})]})}function kS({meshTheme:e,node:t,session:r}){var a,o;const n=Em(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(Ut,{meshTheme:e,label:n,tone:Bm(n)}),s.jsx(Ut,{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(ft,{meshTheme:e,label:"Session id",value:r.sessionId}),s.jsx(ft,{meshTheme:e,label:"Node",value:t.machineLabel}),s.jsx(ft,{meshTheme:e,label:"Workspace",value:r.workspace||t.workspace}),(((a=t.git)==null?void 0:a.branch)??t.worktreeBranch)&&s.jsx(ft,{meshTheme:e,label:"Branch",value:((o=t.git)==null?void 0:o.branch)??t.worktreeBranch}),typeof r.role=="string"&&r.role&&s.jsx(ft,{meshTheme:e,label:"Role",value:r.role}),(r.startedAt||r.createdAt)&&s.jsx(ft,{meshTheme:e,label:"Started",value:cs(r.startedAt||r.createdAt)??(r.startedAt||r.createdAt)})]})]})}function dd({meshTheme:e,mission:t,onSelect:r}){const n=t.tasks,a=cs(n.lastActivityAt);return s.jsxs($a,{meshTheme:e,onClick:r,children:[s.jsx(Ut,{meshTheme:e,label:t.status,tone:Fm(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 SS({meshTheme:e,liveMissions:t,historyMissions:r,hasMissionField:n,onSelect:a}){const[o,i]=l.useState(!1),c=e.isDark,d=Ba(t);return s.jsxs(Xs,{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(dd,{meshTheme:e,mission:p,onSelect:()=>a(p)},p.id)),s.jsx(Ea,{meshTheme:e,expanded:d.expanded,hiddenCount:d.hiddenCount,onToggle:d.toggle})]}):s.jsx(yn,{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(dd,{meshTheme:e,mission:p,onSelect:()=>a(p)},p.id))})]})]})}function NS({meshTheme:e,ledgerSummary:t,entries:r,resolveNodeLabel:n,onSelect:a}){const o=cs(t.lastActivityAt),i=l.useMemo(()=>[...r].reverse(),[r]),c=Ba(i);return s.jsxs(Xs,{meshTheme:e,title:"Ledger",children:[s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(wt,{meshTheme:e,label:"Dispatched",value:t.taskDispatched}),s.jsx(wt,{meshTheme:e,label:"Completed",value:t.taskCompleted,tone:"emerald"}),s.jsx(wt,{meshTheme:e,label:"Failed",value:t.taskFailed,tone:t.taskFailed>0?"rose":void 0}),s.jsx(wt,{meshTheme:e,label:"Stalled",value:t.taskStalled,tone:t.taskStalled>0?"amber":void 0}),s.jsx(wt,{meshTheme:e,label:"Sessions",value:t.sessionLaunched}),s.jsx(wt,{meshTheme:e,label:"Checkpoints",value:t.checkpointCreated})]}),i.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:[c.visible.map(d=>{const p=Wm(d.payload);return s.jsxs($a,{meshTheme:e,onClick:()=>a(d),children:[s.jsx(Ut,{meshTheme:e,label:ul(d.kind),tone:Hm(d.kind)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:d.nodeId||void 0,children:p||n(d.nodeId)||d.sessionId||"—"}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:cs(d.timestamp)??""})]},d.id)}),s.jsx(Ea,{meshTheme:e,expanded:c.expanded,hiddenCount:c.hiddenCount,onToggle:c.toggle})]})]}),(t.recentFailures>0||o&&i.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",{}),o&&i.length===0&&s.jsx("span",{children:o})]})]})}function CS({meshTheme:e,queueSummary:t,tasks:r,onSelect:n}){const a=l.useMemo(()=>[...r].sort((i,c)=>{const d=ld(i.status)-ld(c.status);return d!==0?d:(c.updatedAt||"").localeCompare(i.updatedAt||"")}).slice(0,uS),[r]),o=Ba(a);return t?s.jsxs(Xs,{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(wt,{meshTheme:e,label:"Pending",value:t.pending}),s.jsx(wt,{meshTheme:e,label:"Assigned",value:t.assigned,tone:t.assigned>0?"sky":void 0}),s.jsx(wt,{meshTheme:e,label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(wt,{meshTheme:e,label:"Completed",value:t.completed,tone:"emerald"}),s.jsx(wt,{meshTheme:e,label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0}),s.jsx(wt,{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($a,{meshTheme:e,onClick:()=>n(i),children:[s.jsx(Ut,{meshTheme:e,label:i.status,tone:Om(i.status)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:i.message||void 0,children:oS(i.message)||i.id}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:cs(i.updatedAt)??""})]},i.id)),s.jsx(Ea,{meshTheme:e,expanded:o.expanded,hiddenCount:o.hiddenCount,onToggle:o.toggle})]})]})]}):s.jsx(Xs,{meshTheme:e,title:"Queue",children:s.jsx(yn,{meshTheme:e,children:"No queue activity."})})}function IS(e){return e.autoFastForwardEligible||e.suggestedAction==="auto_fast_forward"?{label:"fast-forward",tone:"sky"}:e.launchBlockedReason?{label:"blocked",tone:"rose"}:null}function AS({meshTheme:e,nodes:t}){const r=e.isDark;return s.jsx(Xs,{meshTheme:e,title:"Nodes",count:t.length,children:t.length===0?s.jsx(yn,{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=IS(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(Ut,{meshTheme:e,label:n.health,tone:hS(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:mS(n)}),a>0&&s.jsxs("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:[a," session",a>1?"s":""]}),typeof n.daemonBuildVersion=="string"&&n.daemonBuildVersion&&s.jsxs("span",{className:`shrink-0 font-mono text-[10px] ${e.textMuted}`,title:"Daemon build version reported by this node",children:["v",n.daemonBuildVersion]}),o&&s.jsx(Ut,{meshTheme:e,label:o.label,tone:o.tone})]},n.nodeId)})})})}function MS({meshTheme:e,entries:t,onSelect:r}){const n=Ba(t);return s.jsx(Xs,{meshTheme:e,title:"Active sessions",count:t.length||void 0,children:t.length===0?s.jsx(yn,{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=Em(o);return s.jsxs($a,{meshTheme:e,onClick:()=>r(a,o),children:[s.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${e.textMuted}`,children:Da(o.sessionId)}),s.jsx("span",{className:`shrink-0 ${e.textMuted}`,children:o.providerType||"?"}),s.jsx(Ut,{meshTheme:e,label:i,tone:Bm(i)})]},o.sessionId)}),s.jsx(Ea,{meshTheme:e,expanded:n.expanded,hiddenCount:n.hiddenCount,onToggle:n.toggle})]})})}function TS({meshTheme:e,jobs:t}){const r=e.isDark,n=t.filter(a=>a.status==="failed").length;return s.jsx(Xs,{meshTheme:e,title:"Refine jobs",count:t.length||void 0,action:n>0?s.jsx(Ut,{meshTheme:e,label:`${n} failed`,tone:"rose"}):void 0,children:t.length===0?s.jsx(yn,{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 _S=["node","p2p","session","task","mission","refinery","completion","magi","magiPanel","convergence"];function LS({meshTheme:e,open:t,onToggle:r}){const{t:n}=Pt(),a=e.isDark,o="inline-flex h-7 w-7 items-center justify-center rounded-lg border transition",i=t?a?"border-sky-400/40 bg-sky-500/15 text-sky-100":"border-sky-400 bg-sky-100 text-sky-800":a?"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":n("meshGraph.help.toggleAria"),"aria-expanded":t,title:n("meshGraph.help.toggleTitle"),className:`${o} ${i}`,children:s.jsx(Rf,{size:15})})}function RS({meshTheme:e,onClose:t}){const{t:r}=Pt(),n=e.isDark,a=l.useMemo(()=>_S.map(o=>({term:r(`meshGraph.help.sections.${o}.term`),summary:r(`meshGraph.help.sections.${o}.summary`),details:r(`meshGraph.help.sections.${o}.details`,{returnObjects:!0})})),[r]);return l.useEffect(()=>{const o=i=>{i.key==="Escape"&&t()};return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[t]),s.jsxs("div",{className:`shrink-0 rounded-2xl border p-4 ${n?"border-white/10 bg-white/[0.03]":"border-slate-200 bg-white/80"}`,role:"region","aria-label":r("meshGraph.help.regionAria"),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:r("meshGraph.help.kicker")}),s.jsx("div",{className:`mt-0.5 text-sm font-semibold ${e.textPrimary}`,children:r("meshGraph.help.title")})]}),s.jsx("button",{type:"button",onClick:t,"aria-label":r("meshGraph.help.close"),className:n?"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(Nt,{size:14})})]}),s.jsx("dl",{className:"grid gap-3 sm:grid-cols-2",children:a.map(o=>s.jsxs("div",{className:`rounded-xl border p-3 ${n?"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:o.term}),s.jsx("dd",{className:`mt-1 text-[11px] leading-5 ${e.textSecondary}`,children:o.summary}),o.details&&o.details.length>0&&s.jsx("ul",{className:`mt-1.5 flex flex-col gap-1 text-[11px] leading-5 ${e.textMuted}`,children:o.details.map((i,c)=>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:i})]},c))})]},o.term))})]})}const tr=l.createContext(Ds("dark"));function We({label:e,tone:t="default",className:r,title:n}){const a=l.useContext(tr);return s.jsx("span",{title:n,className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${a.badge(t)}${r?` ${r}`:""}`,children:e})}function Tt({label:e,value:t}){const r=l.useContext(tr);return s.jsxs("div",{className:r.rowClass,children:[s.jsx("span",{className:r.rowLabelClass,children:e}),s.jsx("span",{className:r.rowValueClass,children:t})]})}const PS={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};function Km(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 Co(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 Qn(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 DS(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function $S(e){return e.startedAt||e.createdAt||null}function ES(e){const t=$S(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 Um(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function BS(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 FS(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 OS(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=[];t.branch&&n.push(t.branch),t.upstream&&t.upstreamStatus!=="fresh"&&n.push("upstream unverified"),t.upstreamStatus==="fresh"&&((t.ahead??0)>0||(t.behind??0)>0)&&n.push(`↑${t.ahead??0}/↓${t.behind??0}`),r>0&&n.push(`${r} dirty`);const a=(t.submodules??[]).filter(i=>i.dirty),o=(t.submodules??[]).filter(i=>i.outOfSync||i.error);return a.length>0&&n.push(`${a.length} submodule dirty`),o.length>0&&n.push(`${o.length} submodule drift`),t.hasConflicts&&n.push("conflicts"),n.join(" · ")||"Clean"}const HS={first_eligible:"In order",least_loaded:"Spread",round_robin:"Spread (round-robin)",priority_only:"Spread (priority)"};function WS(e){if(e.startsWith("max_provider_parallel_reached:"))return`provider cap reached (${e.slice(30)})`;switch(e){case"global_max_parallel_tasks_reached":return"global parallel cap reached";case"node_has_active_assignment":return"already running a write task";default:return e.replace(/_/g," ")}}function KS(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 US(e){return e.assignedNodeId||e.targetNodeId||null}function fi(e){return e?e.slice(0,7):null}function GS(e,t){var o,i,c;const r=fi((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?[fi(a.commit),a.message].filter(Boolean).join(" · "):null}function zS(e,t){const r=GS(e,t);return r||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function VS(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 qS(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 YS(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":FS(e.connection)}function JS(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 ud(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 XS(e){return e.direction==="directed"?"directed":"undirected"}function QS(e,t){return t?e.nodes.find(r=>r.id===t)??null:null}function ZS(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,u,m,h,g,k,f,v,w,x,j,C,y,b,N,S,I,R,L;return[o.nodeId,o.daemonId??"",o.machineId??"",o.machineLabel,o.machineStatus??"",((i=o.connection)==null?void 0:i.state)??"",((c=o.connection)==null?void 0:c.transport)??"",((d=o.connection)==null?void 0:d.source)??"",o.health,o.gitProbePending?1:0,((p=o.git)==null?void 0:p.branch)??"",((u=o.git)==null?void 0:u.upstream)??"",((m=o.git)==null?void 0:m.upstreamStatus)??"",((h=o.git)==null?void 0:h.ahead)??"",((g=o.git)==null?void 0:g.behind)??"",((k=o.git)==null?void 0:k.headCommit)??"",((f=o.git)==null?void 0:f.staged)??"",((v=o.git)==null?void 0:v.modified)??"",((w=o.git)==null?void 0:w.untracked)??"",((x=o.git)==null?void 0:x.deleted)??"",((j=o.git)==null?void 0:j.renamed)??"",(C=o.git)!=null&&C.hasConflicts?1:0,((y=o.git)==null?void 0:y.lastCheckedAt)??"",((b=o.activeSessions)==null?void 0:b.join(","))??"",((N=o.activeSessionDetails)==null?void 0:N.length)??"",((S=o.activeSessionDetails)==null?void 0:S.map(M=>[M.sessionId,M.providerType??"",M.state??"",M.chatStatus??"",M.lifecycle??"",M.role??"",M.isSelfCoordinator?1:0,M.statusNote??"",M.startedAt??"",M.createdAt??""].join("/")).join(","))??"",((I=o.providers)==null?void 0:I.join(","))??"",((R=o.providerPriority)==null?void 0:R.join(","))??"",o.error??"",(((L=o.git)==null?void 0:L.submodules)??[]).map(M=>[M.path,M.commit,M.dirty?1:0,M.outOfSync?1:0,M.error??""].join("/")).join(",")].join("|")})].join("::")}function eN(e){return e.nodes.length===0?!1:e.nodes.every(t=>t.health==="unknown"&&(!t.connection||t.connection.state==="unknown"))}function tN({scheduling:e}){const t=l.useContext(tr);if(!e)return s.jsx("div",{className:`${t.cardClass} rounded-2xl p-4 text-[12px] ${t.textSecondary}`,children:"Scheduling runtime not reported by this daemon (older build). Update the coordinator daemon to surface distribution, parallel caps, and per-node load."});const r=e.globalWriteCapReached?"warn":"good";return s.jsxs("div",{className:`${t.cardClass} rounded-2xl p-4`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${t.textPrimary}`,children:"Scheduling"}),s.jsx(We,{label:HS[e.strategy]??e.strategy,tone:"info"}),s.jsx(We,{label:`write ${e.activeWriteAssigned}/${e.maxParallelTasks}`,tone:r,title:"Active write (non-readonly) assigned tasks vs the global parallel cap"}),s.jsx(We,{label:`readonly ${e.activeReadonlyAssigned}/${e.maxReadonlyParallelTasks}`,tone:e.globalReadonlyCapReached?"warn":"default",title:"Active read-only diagnosis tasks vs their (2× write) cap"})]}),s.jsx("p",{className:`mt-2 text-[11px] ${t.textSecondary}`,children:"Distribution only governs how untargeted work is spread across eligible nodes. Per-node load, priority, and provider caps are below."})]})}function sN({scheduling:e}){return e?s.jsxs(s.Fragment,{children:[s.jsx(We,{label:`load ${e.load}`,tone:e.load>0?"info":"default",title:"Active assigned tasks on this node"}),typeof e.schedulingPriority=="number"&&e.schedulingPriority!==0&&s.jsx(We,{label:`priority ${e.schedulingPriority}`,tone:"default",title:"Soft scheduling priority (higher = preferred)"}),(e.providerRoles??[]).map(t=>s.jsx(We,{label:`${t.providerType} ${t.activeAssigned}${typeof t.maxParallel=="number"?`/${t.maxParallel}`:""}`,tone:t.capReached?"warn":"default",title:"Per-(node, provider) active assignments vs declared maxParallel cap"},t.providerType)),e.capReached&&(e.capReasons??[]).map(t=>s.jsx(We,{label:WS(t),tone:"warn",title:"Why this node cannot currently claim a new write task"},t))]}):null}function rN({node:e}){var u,m,h,g;const t=l.useContext(tr),r=((u=e.activeSessionDetails)==null?void 0:u.length)??((m=e.activeSessions)==null?void 0:m.length)??0,n=fi((h=e.git)==null?void 0:h.headCommit),a=e.isLocalWorktree===!0,o=e.worktreeBootstrap,i=e.staleDaemonBuild,c=e.providerVersions&&typeof e.providerVersions=="object"?e.providerVersions:void 0,d=c?Object.entries(c).filter(([,k])=>typeof k=="string"&&k):[],p=typeof e.daemonBuildVersion=="string"&&e.daemonBuildVersion?e.daemonBuildVersion:void 0;return s.jsxs("div",{className:`rounded-xl border p-3 ${t.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${t.textPrimary}`,children:e.machineLabel||e.nodeId}),s.jsx(We,{label:e.health,tone:Km(e.health)}),a&&s.jsx(We,{label:"worktree",tone:"info",title:e.worktreeBranch?`Worktree branch ${e.worktreeBranch}`:"Local worktree node"}),(o==null?void 0:o.status)&&o.status!=="ready"&&s.jsx(We,{label:`bootstrap ${o.status}`,tone:"warn",title:"Worktree bootstrap is still in progress"}),((g=e.connection)==null?void 0:g.state)&&e.connection.state!=="self"&&s.jsx(We,{label:e.connection.state,tone:e.connection.state==="connected"?"good":"warn",title:"Mesh peer connection state"}),r>0&&s.jsx(We,{label:`${r} session${r===1?"":"s"}`,tone:"default"}),e.autoFastForwardEligible&&s.jsx(We,{label:"fast-forward ready",tone:"info",title:"Clean, behind upstream — safe for fast-forward"}),!!i&&s.jsx(We,{label:"stale build",tone:"warn",title:"Live daemon was built behind workspace HEAD — merged fixes may not be live"}),p&&s.jsx(We,{label:`build ${p}`,tone:"default",title:"Daemon build version reported by this node"}),s.jsx(sN,{scheduling:e.scheduling})]}),d.length>0&&s.jsx("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:d.map(([k,f])=>s.jsx(We,{label:`${k}@${f}`,tone:"info",title:"Detected provider version on this node"},k))}),s.jsxs("div",{className:`mt-1.5 text-[11px] ${t.textSecondary}`,children:[OS(e),n?s.jsxs("span",{className:"ml-2 font-mono opacity-70",children:["@",n]}):null]})]})}function nN({status:e}){const t=l.useContext(tr),r=e.meshProtocolMetrics,n=Array.isArray(e.providerVersionSkew)?e.providerVersionSkew:[];return!r&&n.length===0?null:s.jsxs("div",{className:`${t.cardClass} rounded-2xl p-4`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${t.textPrimary}`,children:"Protocol & provider versions"}),r&&s.jsx(We,{label:`v2 ${Math.round(r.v2Ratio*100)}% (${r.v2}/${r.total})`,tone:r.total>0&&r.v2===r.total?"good":"info",title:"Share of pending coordinator events carrying a mesh-protocol-v2 envelope in this drain"}),n.length>0&&s.jsx(We,{label:`${n.length} provider skew`,tone:"warn",title:"Providers running different versions across nodes"})]}),r&&Object.keys(r.scopes).length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:Object.entries(r.scopes).map(([a,o])=>s.jsx(We,{label:`${a}: ${o}`,tone:"default",title:"v2 event scope breakdown"},a))}),n.length>0&&s.jsx("div",{className:"mt-2 flex flex-col gap-1.5",children:n.map(a=>s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx("span",{className:`text-[11px] font-semibold ${t.textPrimary}`,children:a.provider}),a.versions.map(o=>s.jsx(We,{label:`${o.version} · ${o.nodeIds.length} node${o.nodeIds.length===1?"":"s"}`,tone:"default",title:o.nodeIds.join(", ")},o.version))]},a.provider))}),e.providerVersionSkewWarning&&s.jsx("p",{className:`mt-2 text-[11px] ${t.textSecondary}`,children:e.providerVersionSkewWarning})]})}function aN({canonicalStatus:e}){const t=l.useContext(tr);return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsx(tN,{scheduling:e.scheduling}),s.jsx(nN,{status:e}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("span",{className:`px-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${t.textSecondary}`,children:"Nodes — runtime"}),e.nodes.length===0?s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${t.textSecondary} ${t.isDark?"border-white/10":"border-slate-200"}`,children:"No nodes reporting runtime yet."}):e.nodes.map(r=>s.jsx(rN,{node:r},r.nodeId))]})]})}function oN({canonicalStatus:e,queueSummary:t,ledgerSummary:r,isBootstrapMode:n,meshTheme:a,sessionEntries:o,inlineMode:i=!1}){var y;const c=t&&(t.active>0||t.historical>0),d=r.recentFailures>0||r.taskFailed>0,p=(y=e.queue)!=null&&y.tasks?e.queue.tasks.filter(b=>b.status==="failed"||b.status==="cancelled").slice(0,5):[],u=e.asyncRefineJobs,m=(u==null?void 0:u.filter(b=>b.status==="running"||b.status==="accepted"))??[],h=(u==null?void 0:u.filter(b=>b.status==="failed"))??[],g=e.staleDirectWorkSummary,k=g&&g.count>0;if(!c&&!d&&e.nodes.length===0&&!n&&m.length===0&&h.length===0&&!k&&o.length===0)return null;const f=a.isDark,v=`border-t ${f?"border-white/8":"border-slate-200"}`,w=`group w-full rounded-lg border text-xs ${f?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,x=`flex cursor-pointer list-none items-center gap-1.5 px-2.5 py-1.5 [&::-webkit-details-marker]:hidden ${a.textSecondary}`;function j({label:b,value:N,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:N}),s.jsx("span",{className:`mt-0.5 text-[9px] uppercase tracking-wide ${a.textMuted}`,children:b})]})}const C=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(j,{label:"Pending",value:t.pending}),s.jsx(j,{label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(j,{label:"Done",value:t.completed,tone:"emerald"}),s.jsx(j,{label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0})]}):s.jsxs(s.Fragment,{children:[s.jsx(j,{label:"Done",value:r.taskCompleted,tone:"emerald"}),s.jsx(j,{label:"Failed",value:r.taskFailed,tone:r.taskFailed>0?"rose":void 0}),s.jsx(j,{label:"Sessions",value:r.sessionLaunched}),s.jsx(j,{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(j,{label:"Ledger done",value:r.taskCompleted,tone:"emerald"}),s.jsx(j,{label:"Sessions",value:r.sessionLaunched}),s.jsx(j,{label:"Recent↯",value:r.recentFailures,tone:r.recentFailures>0?"amber":"muted"})]}),r.lastActivityAt&&s.jsxs("div",{className:`flex items-center justify-between ${a.textMuted}`,children:[s.jsx("span",{children:"Last activity"}),s.jsx("span",{className:"font-mono text-[10px]",children:r.lastActivityAt.slice(5,16)})]}),e.nodes.length>0&&s.jsx("div",{className:`pt-2.5 ${v}`,children:s.jsx("div",{className:"flex flex-col gap-1",children:e.nodes.map(b=>{var M;const N=((M=b.connection)==null?void 0:M.state)??"unknown",S=N==="unknown"||N==="connecting",L=S?"bg-amber-400":N==="failed"||N==="closed"||N==="disconnected"?f?"bg-rose-400":"bg-rose-500":N==="connected"||N==="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:b.workspace,children:b.machineLabel}),s.jsx("span",{className:`shrink-0 font-mono text-[10px] ${a.textMuted}`,children:S?"…":N})]},b.nodeId)})})}),u&&u.length>0&&s.jsx("div",{className:`pt-2.5 ${v}`,children:s.jsxs("details",{className:w,children:[s.jsxs("summary",{className:x,children:[s.jsx("span",{className:"flex-1",children:"Refine jobs"}),s.jsx("span",{className:`tabular-nums ${f?"text-slate-400":"text-slate-500"}`,children:u.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:u.slice(0,8).map(b=>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:[b.branch??b.jobId.slice(0,14),b.into?` → ${b.into}`:""]}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${b.status==="failed"?f?"text-rose-300":"text-rose-600":b.status==="running"||b.status==="accepted"?f?"text-sky-300":"text-sky-600":f?"text-emerald-300":"text-emerald-600"}`,children:b.status})]},b.jobId))})]})}),p.length>0&&s.jsx("div",{className:u&&u.length>0?"":`pt-2.5 ${v}`,children:s.jsxs("details",{className:w,children:[s.jsxs("summary",{className:x,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(b=>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:b.id.slice(0,10)}),b.message&&s.jsx("span",{className:`flex-1 truncate ${f?"text-slate-300":"text-slate-700"}`,children:b.message.slice(0,55)})]}),b.cancelReason&&s.jsx("div",{className:`truncate text-[10px] ${a.textMuted}`,children:b.cancelReason.slice(0,55)})]},b.id))})]})}),k&&s.jsxs("div",{className:`flex items-center justify-between pt-2.5 ${v}`,children:[s.jsx("span",{className:a.textMuted,children:"Stale work"}),s.jsx("span",{className:`tabular-nums ${f?"text-amber-300":"text-amber-600"}`,children:g.count})]}),o.length>0&&s.jsx("div",{className:`pt-2.5 ${v}`,children:s.jsxs("details",{className:w,children:[s.jsxs("summary",{className:x,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(b=>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:b.session.sessionId,children:Um(b.session.sessionId)}),s.jsx("span",{className:`shrink-0 ${a.textMuted}`,children:b.session.providerType||"?"}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${a.textMuted}`,children:Qn(b.session)})]},b.session.sessionId))})]})})]});return i?C:s.jsxs("details",{className:`rounded-2xl border text-xs ${a.isDark?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsxs("summary",{className:`flex cursor-pointer list-none items-center gap-2 px-4 py-3 font-medium [&::-webkit-details-marker]:hidden ${a.textSecondary}`,children:[s.jsx("span",{className:"flex-1",children:"Mesh Health Panel"}),m.length>0&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700"}`,children:[m.length," refining"]}),h.length>0&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[h.length," refine failed"]}),d&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[r.recentFailures," recent failures"]}),n&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-amber-400/20 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:"awaiting live data"})]}),C]})}const iN={merged_to_main:"Merged to main",pushed_feature_branch_needs_merge:"Needs merge",blocked_review:"Blocked — needs review",cleanup_candidate:"Ready to clean up",not_mergeable:"Not mergeable"};function Gm({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==="status",className:o(t==="status"),onClick:()=>r("status"),children:"Status"}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="graph",className:o(t==="graph"),onClick:()=>r("graph"),children:"Graph"})]}),s.jsx(LS,{meshTheme:e,open:n,onToggle:()=>a(!n)})]})}function lN({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 Ae,Ne,Ke;const{theme:u}=Ps(),m=l.useMemo(()=>Ds(u),[u]),h=l.useMemo(()=>Tu(e),[e]),g=a??eN(h),k=l.useMemo(()=>ZS(h),[h]),f=l.useMemo(()=>_m(h),[k]),[v,w]=l.useState("overview"),[x,j]=l.useState(!1),C=o??v,y=c??x,b=l.useCallback(ie=>{i?i(ie):w(ie)},[i]),N=l.useCallback(ie=>{d?d(ie):j(ie)},[d]),[S,I]=l.useState(!1);l.useEffect(()=>{C==="graph"&&I(!0)},[C]);const[R,L]=l.useState(null),[M,P]=l.useState(null),[$,Y]=l.useState(null),[_,H]=l.useState({}),[W,B]=l.useState(null),[T,A]=l.useState(null),E=l.useMemo(()=>new Map(h.nodes.map(ie=>[ie.nodeId,ie])),[h.nodes]),z=l.useMemo(()=>new Map(f.nodes.map(ie=>[ie.id,ie])),[f.nodes]),G=((Ae=h.queue)==null?void 0:Ae.summary)??null,re=((Ne=h.ledger)==null?void 0:Ne.summary)??PS,X=l.useMemo(()=>KS(h),[h]),te=l.useMemo(()=>{const ie=new Map;for(const Fe of X){const $e=Qn(Fe.session);ie.set($e,(ie.get($e)??0)+1)}return[...ie.entries()].sort((Fe,$e)=>$e[1]-Fe[1])},[X]);l.useEffect(()=>{R&&(z.has(R)||(L(null),Y(ie=>!ie||"nodeId"in ie&&ie.nodeId===R?null:ie)))},[z,R]);const J=R?E.get(R)??null:null,F=QS(f,R),K=($==null?void 0:$.kind)==="edge"&&M?f.edges.find(ie=>ie.id===M)??null:null,fe=K?f.nodes.find(ie=>ie.id===K.source)??null:null,be=K?f.nodes.find(ie=>ie.id===K.target)??null:null;l.useEffect(()=>{var ie,Fe,$e;if(R)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:h.meshId,selectedNodeId:R,canonicalNode:Bg(J),graphNode:F?{id:F.id,branch:F.branch,upstream:F.upstream,headCommit:F.submoduleCommit,submoduleCount:((Fe=(ie=J==null?void 0:J.git)==null?void 0:ie.submodules)==null?void 0:Fe.length)??0,snapshotCompleteness:F.snapshotCompleteness,snapshotWarnings:F.snapshotWarnings,branchConvergence:(($e=F.branchConvergence)==null?void 0:$e.status)??null}:null})}catch{}},[h.meshId,F,R,J]);const oe=($==null?void 0:$.kind)==="session"?X.find(ie=>ie.nodeId===$.nodeId&&ie.session.sessionId===$.sessionId)??null:null,je=l.useMemo(()=>X.filter(ie=>ie.nodeId===R),[R,X]),ge=qS({coordinatorDaemonId:r,selectedNodeStatus:J,selectedSessionEntry:oe}),we=(ge==null?void 0:ge.workspace)??null,me=we?_[we]??null:null,U=zS(J,(me==null?void 0:me.entries)??[]),O=(F==null?void 0:F.daemonId)??(J==null?void 0:J.daemonId)??r??null,Z=!!(F&&n&&O&&F.type!=="submoduleNode"&&F.behind>0&&F.ahead===0&&F.dirtyFiles===0&&!F.dirty&&!F.hasConflicts&&F.upstreamStatus==="fresh"),V=l.useCallback(()=>{L(null),P(null),Y(null),B(null)},[]);l.useEffect(()=>{B(null)},[R]);const he=l.useCallback(async()=>{if(!F||!O||!n||!Z)return;A(F.id),B(null);const ie=(J==null?void 0:J.workspace)??F.workspace??"";try{const Fe=await n(O,"fast_forward_mesh_node",{meshId:h.meshId,nodeId:F.id,workspace:ie,updateSubmodules:!0,dryRun:!0,execute:!1}),$e=(Fe==null?void 0:Fe.result)??Fe;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 ${F.label}?`))return;const qe=await n(O,"fast_forward_mesh_node",{meshId:h.meshId,nodeId:F.id,workspace:ie,updateSubmodules:!0,dryRun:!1,execute:!0}),ke=(qe==null?void 0:qe.result)??qe;B({phase:"execute",code:typeof(ke==null?void 0:ke.code)=="string"?ke.code:void 0,error:typeof(ke==null?void 0:ke.operationError)=="string"?ke.operationError:null,executed:(ke==null?void 0:ke.executed)===!0})}catch(Fe){B({phase:"dry_run",error:Fe instanceof Error?Fe.message:"fast-forward failed"})}finally{A(null)}},[Z,h.meshId,F,O,n]);l.useEffect(()=>{if(!F&&!K)return;const ie=Fe=>{Fe.key==="Escape"&&V()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[V,K,F]),l.useEffect(()=>{if(!ge||!n)return;const{daemonId:ie,workspace:Fe}=ge,$e=_[Fe];if($e!=null&&$e.loading||$e&&($e.entries.length>0||$e.error))return;let tt=!1;return H(qe=>{var ke;return{...qe,[Fe]:{loading:!0,error:null,entries:((ke=qe[Fe])==null?void 0:ke.entries)??[]}}}),n(ie,"git_log",{workspace:Fe,limit:5}).then(qe=>{tt||H(ke=>({...ke,[Fe]:{loading:!1,error:null,entries:VS(qe)}}))}).catch(qe=>{tt||H(ke=>({...ke,[Fe]:{loading:!1,error:qe instanceof Error?qe.message:"git_log failed",entries:[]}}))}),()=>{tt=!0}},[_,ge,n]);const le=[...f.warnings??[],...h.nodes.filter(ie=>ie.machineStatus&&ie.machineStatus!=="online").map(ie=>`${ie.machineLabel}: ${ie.machineStatus}`)],D=f.stats.incompleteSnapshotNodes>0,de=f.stats.followUpNodes>0?`${f.stats.followUpNodes} need follow-up`:D?"mesh visibility incomplete":"mesh converged",Se=f.stats.followUpNodes>0?"danger":D?"warn":"good",[ue,q]=l.useState("LR"),ve=ie=>ie?m.isDark?"rounded-md border border-cyan-400/40 bg-cyan-500/15 px-2 py-0.5 text-cyan-100":"rounded-md border border-sky-400 bg-sky-100 px-2 py-0.5 text-sky-800":m.isDark?"rounded-md border border-white/10 bg-white/[0.03] px-2 py-0.5 text-slate-400 hover:text-slate-200":"rounded-md border border-slate-300 bg-white/80 px-2 py-0.5 text-slate-500 hover:text-slate-800";return s.jsx(tr.Provider,{value:m,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(Gm,{meshTheme:m,activeTab:C,onActiveTabChange:b,helpOpen:y,onHelpOpenChange:N})}),y&&s.jsx(RS,{meshTheme:m,onClose:()=>N(!1)}),s.jsx("div",{className:`${C==="overview"?"flex":"hidden"} min-h-0 flex-1 flex-col gap-3 overflow-y-auto`,children:C==="overview"&&s.jsx(fS,{status:h,daemonId:r,meshId:h.meshId,sendDaemonCommand:n})}),s.jsx("div",{className:`${C==="status"?"flex":"hidden"} min-h-0 flex-1 flex-col overflow-y-auto`,children:C==="status"&&s.jsx(aN,{canonicalStatus:h})}),s.jsx("div",{className:`${C==="graph"?"flex":"hidden"} min-h-0 flex-1 flex-col gap-4`,children:s.jsxs("div",{className:`${m.cardClass} relative flex min-h-0 flex-1 flex-col rounded-[28px]`,style:{minHeight:480},children:[s.jsxs("div",{className:`relative z-30 max-h-[42dvh] overflow-y-auto sm:max-h-none sm:mb-3 sm:overflow-visible shrink-0 flex flex-wrap items-start justify-between gap-2 px-4 pt-3 pb-2.5 border-b ${m.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-nowrap overflow-x-auto sm:flex-wrap sm:overflow-visible gap-2 text-xs ${m.textSecondary}`,children:[s.jsx(We,{label:de,tone:Se,className:"shrink-0"}),f.stats.blockedReviewNodes>0&&s.jsx(We,{label:`${f.stats.blockedReviewNodes} blocked`,title:`${f.stats.blockedReviewNodes} blocked review`,tone:"danger",className:"shrink-0"}),f.stats.notMergeableNodes>0&&s.jsx(We,{label:`${f.stats.notMergeableNodes} not mergeable`,tone:"danger",className:"shrink-0"}),f.stats.mergeReadyNodes>0&&s.jsx(We,{label:`${f.stats.mergeReadyNodes} need merge`,tone:"warn",className:"shrink-0"}),f.stats.cleanupCandidateNodes>0&&s.jsx(We,{label:`${f.stats.cleanupCandidateNodes} cleanup`,title:`${f.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info",className:"shrink-0"}),f.stats.offlineNodes>0&&s.jsx(We,{label:`${f.stats.offlineNodes} offline`,tone:"danger",className:"shrink-0"}),f.stats.incompleteSnapshotNodes>0&&s.jsx(We,{label:`${f.stats.incompleteSnapshotNodes} incomplete`,title:`${f.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn",className:"shrink-0"}),f.stats.missingGitSnapshotNodes>0&&s.jsx(We,{label:`${f.stats.missingGitSnapshotNodes} no-git`,title:`${f.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn",className:"shrink-0"}),f.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(We,{label:`${f.stats.missingSubmoduleSnapshotNodes} no-submod`,title:`${f.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn",className:"shrink-0"}),f.stats.staleGitSnapshotNodes>0&&s.jsx(We,{label:`${f.stats.staleGitSnapshotNodes} stale`,title:`${f.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn",className:"shrink-0"}),((G==null?void 0:G.active)??0)>0&&s.jsx(We,{label:`${(G==null?void 0:G.active)??0} active queue`,tone:"info",className:"shrink-0 hidden sm:inline-flex"}),s.jsx(We,{label:`${f.stats.totalNodes} nodes`,tone:"default",className:"shrink-0 hidden sm:inline-flex"}),f.stats.totalActiveSessions>0&&s.jsx(We,{label:`${f.stats.totalActiveSessions} attached chats`,tone:"info",className:"shrink-0 hidden sm:inline-flex"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[s.jsxs("div",{className:m.isDark?"flex items-center gap-0.5 rounded-md border border-white/10 bg-slate-950/40 p-0.5 text-[10px]":"flex items-center gap-0.5 rounded-md border border-slate-300 bg-white/70 p-0.5 text-[10px]",role:"group","aria-label":"Graph layout direction",children:[s.jsx("button",{type:"button",onClick:()=>q("auto"),className:ve(ue==="auto"),title:"Auto-detect direction",children:"Auto"}),s.jsx("button",{type:"button",onClick:()=>q("LR"),className:ve(ue==="LR"),title:"Left to right",children:"LR"}),s.jsx("button",{type:"button",onClick:()=>q("TB"),className:ve(ue==="TB"),title:"Top to bottom",children:"TB"})]}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${m.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${m.textSecondary} [&::-webkit-details-marker]:hidden`,children:(()=>{var $e;const ie=(($e=h.asyncRefineJobs)==null?void 0:$e.filter(tt=>tt.status==="failed").length)??0,Fe=re.recentFailures;return ie>0?s.jsxs("span",{className:m.isDark?"text-rose-300":"text-rose-600",children:[ie," refine failed"]}):Fe>0?s.jsxs("span",{className:m.isDark?"text-amber-300":"text-amber-600",children:[Fe," failures"]}):"Health"})()}),s.jsx("div",{className:`absolute right-0 z-40 mt-2 w-72 max-h-[70vh] overflow-y-auto rounded-xl border p-4 shadow-xl backdrop-blur-xl ${m.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsx(oN,{canonicalStatus:h,queueSummary:G,ledgerSummary:re,isBootstrapMode:g,meshTheme:m,sessionEntries:X,inlineMode:!0})})]})}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${m.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${m.textSecondary} [&::-webkit-details-marker]:hidden`,children:"Legend"}),s.jsx("div",{className:`absolute right-0 z-40 mt-2 w-72 rounded-xl border p-3 shadow-xl backdrop-blur-xl ${m.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(We,{label:`${f.stats.dirtyNodes} dirty`,tone:f.stats.dirtyNodes>0?"warn":"good"}),s.jsx(We,{label:`${f.stats.orphanNodes} orphan`,tone:f.stats.orphanNodes>0?"warn":"good"}),s.jsx(We,{label:`${re.recentFailures} recent failures`,tone:re.recentFailures>0?"danger":"good"}),te.length===0?s.jsx(We,{label:"no session metadata"}):te.slice(0,2).map(([ie,Fe])=>s.jsx(We,{label:`${Fe} ${ie}`,tone:Co(ie)},ie))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(We,{label:"Anchor = default branch",tone:"info"}),s.jsx(We,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(We,{label:"Submodule link = child checkout",tone:"warn"})]}),le.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:le.map(ie=>s.jsx("span",{className:m.isDark?"rounded-full border border-amber-400/20 bg-amber-500/10 px-3 py-1 text-xs text-amber-100":"rounded-full border border-amber-300 bg-amber-50 px-3 py-1 text-xs text-amber-700",children:ie},ie))}),s.jsx("div",{className:`text-xs ${m.textMuted}`,children:"Click a node or edge to pin its drill-down details in the side panel. Click it again to close."})]})})]})})]})]}),g&&f.nodes.length>0&&s.jsxs("div",{className:`shrink-0 mx-4 mt-2 flex items-center gap-2 rounded-xl border px-3.5 py-2 text-xs ${m.isDark?"border-amber-400/20 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full animate-pulse ${m.isDark?"bg-amber-400":"bg-amber-500"}`,"aria-hidden":!0}),s.jsx("span",{children:"Awaiting live data — showing setup inventory until peer mesh_status probes succeed."})]}),s.jsxs("div",{className:"relative flex flex-1 min-w-0",style:{minHeight:360},children:[s.jsx("div",{className:"flex-1 min-w-0",children:S?f.nodes.length>0?s.jsx(nS,{data:f,selectedNodeId:R,directionPref:ue,onNodeClick:ie=>{if(($==null?void 0:$.kind)==="node"&&R===ie.id){V();return}P(null),L(ie.id),Y({kind:"node",nodeId:ie.id})},onEdgeClick:ie=>{if(($==null?void 0:$.kind)==="edge"&&M===ie.id){V();return}L(null),P(ie.id),Y({kind:"edge",edgeId:ie.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…"})}),F&&($==null?void 0:$.kind)==="node"&&s.jsxs("div",{role:"dialog",className:`absolute inset-x-3 bottom-3 top-20 z-20 rounded-2xl border shadow-2xl sm:relative sm:inset-auto sm:z-auto sm:w-72 sm:shrink-0 sm:rounded-none sm:border-0 sm:border-l sm:shadow-none overflow-y-auto p-4 ${m.isDark?"border-white/10 bg-slate-950 sm:bg-transparent":"border-slate-200 bg-white sm:bg-transparent"}`,children:[s.jsx("div",{className:`mb-2 text-[10px] font-semibold uppercase tracking-wide ${m.textMuted}`,children:"Selected node"}),s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${m.textPrimary}`,children:F.label}),s.jsx("div",{className:`mt-0.5 font-mono text-[11px] ${m.textMuted}`,children:F.id.slice(0,16)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[F.behind>0&&s.jsx("button",{type:"button",onClick:()=>{he()},disabled:!Z||T===F.id,className:m.isDark?"rounded-full border border-emerald-400/25 bg-emerald-500/10 px-2 py-0.5 text-xs font-semibold text-emerald-100 transition hover:bg-emerald-500/18 disabled:cursor-not-allowed disabled:opacity-45":"rounded-full border border-emerald-300 bg-emerald-50 px-2 py-0.5 text-xs font-semibold text-emerald-700 transition hover:bg-emerald-100 disabled:cursor-not-allowed disabled:opacity-45",children:T===F.id?"Checking":"Heal"}),s.jsx("button",{type:"button",onClick:V,"aria-label":"Close detail panel",className:m.isDark?"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-xs text-slate-200 transition hover:bg-white/[0.08]":"rounded-full border border-slate-200 bg-white px-2 py-0.5 text-xs text-slate-600 transition hover:bg-slate-50",children:"✕"})]})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-1.5",children:[(()=>{const ie=(J==null?void 0:J.health)??F.health;return ie==="unknown"?s.jsx(We,{label:"connecting...",tone:"default"}):s.jsx(We,{label:ie,tone:Km(ie)})})(),F.branch&&s.jsx(We,{label:F.branch,tone:"default"}),F.ahead>0&&s.jsx(We,{label:`ahead ${F.ahead}`,tone:"warn"}),F.behind>0&&s.jsx(We,{label:`behind ${F.behind}`,tone:"warn"}),F.dirtyFiles>0&&s.jsx(We,{label:`${F.dirtyFiles} dirty`,tone:"warn"}),(J==null?void 0:J.connection)&&J.connection.state!=="unknown"&&s.jsx(We,{label:YS(J),tone:BS(J.connection)}),((Ke=J==null?void 0:J.connection)==null?void 0:Ke.state)==="unknown"&&s.jsx(We,{label:"mesh connecting...",tone:"warn"}),je.length>0&&s.jsx(We,{label:`${je.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[F.machineLabel&&s.jsx(Tt,{label:"Machine",value:F.machineLabel}),F.locality&&F.locality!=="unknown"&&s.jsx(Tt,{label:"Locality",value:F.locality}),s.jsx(Tt,{label:"Workspace",value:(J==null?void 0:J.workspace)??F.workspace}),U&&s.jsx(Tt,{label:"HEAD",value:U}),(F.dirtyFiles>0||F.ahead>0||F.behind>0)&&s.jsx(Tt,{label:"Dirty/ahead/behind",value:`${F.dirtyFiles}/${F.ahead}/${F.behind}`}),je.length>0&&s.jsx(Tt,{label:"Sessions",value:String(je.length)}),F.upstream&&s.jsx(Tt,{label:"Upstream",value:F.upstream}),(()=>{var Fe;const ie=((Fe=J==null?void 0:J.connection)==null?void 0:Fe.source)??JS(F);return ie&&ie!=="unknown"?s.jsx(Tt,{label:"Source",value:String(ie)}):null})(),(()=>{var Fe;const ie=(Fe=J==null?void 0:J.connection)==null?void 0:Fe.transport;return ie&&ie!=="unknown"?s.jsx(Tt,{label:"Transport",value:ie}):null})(),(()=>{const ie=F.machineId??(J==null?void 0:J.machineId);return ie?s.jsx(Tt,{label:"Machine id",value:ie}):null})(),(()=>{const ie=F.daemonId??(J==null?void 0:J.daemonId);return ie?s.jsx(Tt,{label:"Daemon id",value:ie}):null})()]}),je.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${m.textMuted}`,children:"Active Sessions"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:je.map(ie=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${m.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate font-mono select-text ${m.textMuted}`,title:ie.session.sessionId,children:Um(ie.session.sessionId)}),s.jsx(We,{label:Qn(ie.session),tone:Co(Qn(ie.session))})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 ${m.textMuted}`,children:[s.jsx("span",{className:"truncate",children:ie.session.providerType||"provider unknown"}),s.jsx("span",{children:DS(ie.session)}),s.jsx("span",{children:ES(ie.session)})]}),ie.session.statusNote&&s.jsx("div",{className:`mt-1 text-[10px] leading-4 ${m.textMuted}`,children:ie.session.statusNote}),s.jsxs("div",{className:`mt-0.5 truncate ${m.textMuted}`,title:ie.session.workspace||ie.workspace,children:[(ie.session.workspace||ie.workspace).slice(0,38),ie.branch?` · ${ie.branch}`:""]})]},ie.session.sessionId))})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${m.textMuted}`,children:"Ledger (mesh-wide)"}),s.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[s.jsx(Tt,{label:"Completed",value:String(re.taskCompleted)}),s.jsx(Tt,{label:"Failed",value:s.jsx("span",{className:re.taskFailed>0?m.isDark?"text-rose-300":"text-rose-600":"",children:re.taskFailed})}),s.jsx(Tt,{label:"Launched",value:String(re.sessionLaunched)}),s.jsx(Tt,{label:"Recent failures",value:s.jsx("span",{className:re.recentFailures>0?m.isDark?"text-amber-300":"text-amber-600":"",children:re.recentFailures})})]})]}),(()=>{var $e,tt;const ie=(($e=h.queue)==null?void 0:$e.tasks)??((tt=h.queue)==null?void 0:tt.items)??null;if(!Array.isArray(ie)||ie.length===0)return null;const Fe=ie.filter(qe=>US(qe)===R).slice(0,3);return Fe.length===0?null:s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${m.textMuted}`,children:"Queue tasks"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:Fe.map(qe=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${m.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`font-mono ${m.textMuted}`,children:qe.id.slice(0,12)}),s.jsx(We,{label:qe.status??"unknown",tone:Co(qe.status)})]}),qe.message&&s.jsx("div",{className:`mt-0.5 truncate ${m.textMuted}`,children:qe.message.slice(0,48)})]},qe.id))})]})})(),F.snapshotWarnings.length>0&&s.jsxs("div",{className:m.isDark?"mt-3 rounded-xl border border-amber-400/20 bg-amber-500/10 p-3 text-xs text-amber-100":"mt-3 rounded-xl border border-amber-300 bg-amber-50 p-3 text-xs text-amber-800",children:[s.jsx("div",{className:"font-medium",children:"Key warning"}),s.jsx("div",{className:"mt-1",children:F.snapshotWarnings[0]})]}),F.branchConvergence&&(F.branchConvergence.reason||F.branchConvergence.nextStep)&&s.jsxs("div",{className:m.isDark?"mt-3 rounded-xl border border-sky-400/20 bg-sky-500/10 p-3 text-xs text-sky-100":"mt-3 rounded-xl border border-sky-300 bg-sky-50 p-3 text-xs text-sky-800",children:[s.jsxs("div",{className:"font-medium",children:["Follow-up — ",iN[F.branchConvergence.status]??F.branchConvergence.status]}),F.branchConvergence.reason&&s.jsx("div",{className:"mt-1",children:F.branchConvergence.reason}),F.branchConvergence.nextStep&&s.jsx("div",{className:`${F.branchConvergence.reason?"mt-1.5 pt-1.5 border-t border-sky-400/20":"mt-1"}`,children:F.branchConvergence.nextStep})]}),W&&s.jsxs("div",{className:m.isDark?"mt-3 rounded-xl border border-emerald-400/20 bg-emerald-500/10 p-3 text-xs text-emerald-100":"mt-3 rounded-xl border border-emerald-300 bg-emerald-50 p-3 text-xs text-emerald-800",children:[s.jsx("div",{className:"font-medium",children:W.phase==="execute"?"Heal result":"Heal preview"}),s.jsx("div",{className:"mt-1",children:W.code??W.error??"No result code returned."})]})]}),K&&($==null?void 0:$.kind)==="edge"&&s.jsxs("div",{role:"dialog",className:`absolute inset-x-3 bottom-3 top-20 z-20 rounded-2xl border shadow-2xl sm:relative sm:inset-auto sm:z-auto sm:w-72 sm:shrink-0 sm:rounded-none sm:border-0 sm:border-l sm:shadow-none overflow-y-auto p-4 ${m.isDark?"border-white/10 bg-slate-950 sm:bg-transparent":"border-slate-200 bg-white sm:bg-transparent"}`,children:[s.jsx("div",{className:`mb-2 text-[10px] font-semibold uppercase tracking-wide ${m.textMuted}`,children:"Selected edge"}),s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${m.textPrimary}`,children:K.label||ud(K)}),s.jsx("div",{className:`mt-0.5 break-all font-mono text-[11px] ${m.textMuted}`,children:K.id})]}),s.jsx("button",{type:"button",onClick:V,"aria-label":"Close detail panel",className:m.isDark?"shrink-0 rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-xs text-slate-200 transition hover:bg-white/[0.08]":"shrink-0 rounded-full border border-slate-200 bg-white px-2 py-0.5 text-xs text-slate-600 transition hover:bg-slate-50",children:"✕"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-1.5",children:[s.jsx(We,{label:ud(K),tone:"default"}),s.jsx(We,{label:XS(K),tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(Tt,{label:"From",value:(fe==null?void 0:fe.label)??K.source}),s.jsx(Tt,{label:"To",value:(be==null?void 0:be.label)??K.target}),s.jsx(Tt,{label:"Label",value:K.label??"none"})]})]})]})]})})]})})}function St(e){return typeof e=="string"?e.trim():""}function xi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function pl(...e){const t=new Set;for(const r of e){const n=St(r);n&&t.add(n)}return[...t]}function cN(e,t){var m,h;const r=xi(e==null?void 0:e.settings),n=St((m=e==null?void 0:e.coordinator)==null?void 0:m.meshId)||St(r.meshCoordinatorFor),a=St(r.meshNodeFor),o=!!n||!!a,i=n===t||a===t;if(o&&!i)return null;const c=xi(e==null?void 0:e.activeChat),d=pl(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 u=n===t?St((h=e==null?void 0:e.coordinator)==null?void 0:h.role)||"coordinator":a===t?St(r.meshNodeRole)||"worker":St(e==null?void 0:e.role)||St(r.meshNodeRole)||void 0;return{sessionId:p,aliases:d,meshId:t,nodeId:i&&St(r.meshNodeId)||null,providerType:St(e==null?void 0:e.providerType)||void 0,state:St(e==null?void 0:e.status)||void 0,chatStatus:St(c.status)||void 0,lifecycle:St(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:St(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:St(e==null?void 0:e.runtimeRecoveryState)||void 0,...u?{role:u}:{},...i?{isSelfCoordinator:n===t}:{},workspace:St(e==null?void 0:e.workspace)||null}}function zm(e,t){var n;return t?(Array.isArray((n=e.status)==null?void 0:n.sessions)?e.status.sessions:[]).map(a=>cN(a,t)).filter(a=>a!==null):[]}function ya(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function dN(e,t){const r=new Set(ya(t));return ya(e).some(n=>r.has(n))}function uN(e,t){const r=t.filter(a=>!!a);return r.length===0?e:[...e.filter(a=>!r.some(o=>dN(a,o))),...r]}function pN(e,t){if(t.length===0)return e;const r=new Map;for(const i of t)for(const c of ya(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 g=pl(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),k=g[0]||"";if(!k)continue;const f=g.map(v=>r.get(v)).find(Boolean);f&&(n=!0),p.set(k,f?{...h,sessionId:k,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:k})}for(const h of i.activeSessions??[])p.has(h)||p.set(h,{sessionId:h,workspace:i.workspace,isCached:!0});const u=c===0;for(const h of t){if(ya(h).some(v=>p.has(v)))continue;const k=h.nodeId!=null&&h.nodeId===i.nodeId,f=h.isSelfCoordinator&&!h.nodeId&&u;!k&&!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 m=[...p.values()];return m.length===0?i:{...i,activeSessionDetails:m,activeSessions:m.map(h=>h.sessionId)}});return n?{...e,nodes:o}:e}function mN(e,t){const n=zm(e,t).map(a=>{var d;const o=(Array.isArray((d=e.status)==null?void 0:d.sessions)?e.status.sessions:[]).find(p=>St(p==null?void 0:p.id)===a.sessionId),i=xi(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??"",St(i.status)||St(i.kind)||St(i.type),a.nodeId??"",a.isSelfCoordinator?"coordinator":"worker",c].join("|")}).filter(a=>!!a).sort();return n.length>0?n.join(`
|
|
84
|
+
`):null}function Vm({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 g=new Set;if(t&&g.add(t),r)for(const k of r)k&&g.add(k);return[...g].sort()},[t,r]),u=p.join(",");l.useEffect(()=>{d.current=new Map,c(new Map)},[t,n]),l.useEffect(()=>{if(!n||!a||p.length===0)return;const g=p.map(k=>is.subscribe({sendData:a},k,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${k}`,params:{includeSessions:!0}},f=>{if(f.topic!=="daemon.metadata")return;const v=mN(f,n);if(v===(d.current.get(k)??null))return;d.current.set(k,v);const w=zm(f,n);c(x=>{const j=new Map(x);return j.set(k,w),j})}));return()=>{for(const k of g)k()}},[u,n,a]);const m=l.useMemo(()=>{const g=[];for(const k of i.values())g.push(...k);return g},[i]),h=l.useMemo(()=>uN(m,o),[o,m]);return l.useMemo(()=>e?pN(e,h):null,[h,e])}const pd=[1500,4e3,9e3];function hN(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 fN(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>{var r;return hN(t)?!1:t.gitProbePending||((r=t.connection)==null?void 0:r.state)==="connecting"?!0:t.machineStatus==="online"||t.launchReady===!0})}function xN(e){return!Number.isInteger(e)||e<0?pd[0]:pd[e]??null}const Io=new Map;function bN(e,t){return!e||!t?null:`${e}::${t}`}function gN(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:pl(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 qm({activeConv:e,sendDaemonCommand:t,onClose:r}){var re,X,te,J,F,K;const n=((re=e.coordinator)==null?void 0:re.meshId)??(typeof((X=e.settings)==null?void 0:X.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),a=e.daemonId??null,o=bN(a,n),i=o?Io.get(o)??null:null,c=Bi(),{sendData:d}=bt(),{theme:p}=Ps(),u=l.useMemo(()=>Ds(p),[p]),[m,h]=l.useState("overview"),[g,k]=l.useState(!1),f=l.useMemo(()=>gN(e,n),[e.agentType,(te=e.coordinator)==null?void 0:te.meshId,e.sessionId,(J=e.settings)==null?void 0:J.meshCoordinatorFor,(F=e.settings)==null?void 0:F.meshNodeFor,(K=e.settings)==null?void 0:K.meshNodeId,e.status,e.workspacePath,n]),[v,w]=l.useState(i),[x,j]=l.useState(!1),[C,y]=l.useState(!1),[b,N]=l.useState(!1),[S,I]=l.useState(null),[R,L]=l.useState((i==null?void 0:i.refreshedAt)??null),M=l.useRef(i!==null),P=l.useRef(!1),$=l.useRef(!1),Y=l.useRef(!0),_=l.useRef(0),H=l.useRef(null);l.useEffect(()=>{M.current=v!==null},[v]);const W=l.useCallback(()=>{H.current!==null&&(clearTimeout(H.current),H.current=null)},[]);l.useEffect(()=>{W(),_.current=0;const fe=o?Io.get(o)??null:null;w(fe),L((fe==null?void 0:fe.refreshedAt)??null),M.current=fe!==null,$.current=!1,y(!1),I(null)},[o,W]);const B=l.useCallback(async(fe=!1,be=!1)=>{if(!a||!n){I("This coordinator does not expose a live mesh id."),w(null);return}if(P.current){fe&&($.current=!0);return}be||(W(),_.current=0),P.current=!0;const oe=!M.current;j(oe),y(fe&&M.current),I(null);try{const je=c!=null&&c.loadMeshStatus?await c.loadMeshStatus(a,n,{refresh:fe,retryProfile:be?"interactive":"settled"}):await t(a,"mesh_status",{meshId:n,refresh:fe}),ge=Oi(je);if(!ge){I("mesh_status returned an unexpected payload.");return}if(o&&Io.set(o,ge),w(ge),M.current=!0,L(ge.refreshedAt||new Date().toISOString()),fN(ge.nodes)){const we=xN(_.current);we!==null&&Y.current&&(_.current+=1,H.current=setTimeout(()=>{Y.current&&B(!0,!0)},we))}else _.current=0}catch(je){I(je instanceof Error?je.message:"Failed to load live mesh status")}finally{P.current=!1,j(!1),y(!1),$.current&&Y.current&&($.current=!1,window.setTimeout(()=>{Y.current&&B(!0)},0))}},[o,W,a,n,c,t]);l.useEffect(()=>(Y.current=!0,_.current=0,(async()=>(await B(!1,!0),Y.current&&H.current===null&&!P.current&&B(!0,!0)))(),()=>{Y.current=!1,W()}),[B,W]),l.useEffect(()=>{const fe=be=>{be.key==="Escape"&&r()};return window.addEventListener("keydown",fe),()=>window.removeEventListener("keydown",fe)},[r]);const T=(v==null?void 0:v.meshName)||n||"Repo Mesh",A=l.useMemo(()=>f?[f]:[],[f]),E=Vm({status:v,daemonId:a,meshId:n,sendData:d,extraLiveSessions:A}),z=R?new Date(R).toLocaleTimeString():null,G=l.useMemo(()=>x?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[x]);return s.jsx("div",{className:u.dialogOverlayClass,onClick:r,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:u.dialogShellClass,onClick:fe=>fe.stopPropagation(),children:[s.jsxs("div",{className:`relative ${u.dialogHeaderClass}`,children:[s.jsx("button",{type:"button",onClick:r,className:`absolute right-4 top-[calc(16px+env(safe-area-inset-top,0px))] z-10 md:right-5 md:top-1/2 md:-translate-y-1/2 ${u.dialogCloseButtonClass}`,"aria-label":"Close mesh graph",children:s.jsx(Nt,{size:16})}),s.jsx("div",{className:"min-w-0 flex-1 pr-12 md:pr-0",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-sky-400/20 bg-sky-500/12 text-sky-200 shadow-[0_12px_30px_rgba(14,165,233,0.18)]",children:s.jsx(Zt,{size:18})}),s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("h2",{className:u.dialogTitleClass,children:T}),s.jsx("span",{className:u.dialogKickerClass,children:"Mesh observability"}),s.jsx("button",{type:"button",onClick:()=>N(fe=>!fe),"aria-expanded":b,"aria-label":b?"Hide mesh details":"Show mesh details",className:"btn btn-secondary btn-sm rounded-lg px-1.5 py-1 md:hidden",title:b?"Hide mesh details":"Show mesh details",children:s.jsx(Ci,{size:14})})]}),s.jsxs("p",{className:`${u.dialogSubtitleClass} ${b?"block":"hidden"} md:block`,children:[xt(e),e.workspaceName?` · ${e.workspaceName}`:"",v!=null&&v.repoIdentity?` · ${v.repoIdentity}`:""]})]})]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end md:pr-12",children:[s.jsx(Gm,{meshTheme:u,activeTab:m,onActiveTabChange:h,helpOpen:g,onHelpOpenChange:k}),z&&s.jsx("span",{className:`${u.dialogRefreshedChipClass} ${b?"inline-flex":"hidden"} md:inline-flex`,children:`Refreshed ${z}`}),!C&&v&&s.jsx("span",{className:`${u.dialogRefreshedChipClass} ${b?"inline-flex":"hidden"} md:inline-flex`,children:d&&!S?"Live daemon metadata":"Metadata subscription unavailable"}),s.jsx("button",{type:"button",onClick:()=>{B(!0)},disabled:x||C,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:x||C?"Refreshing…":"Refresh"})]})]}),S&&s.jsx("div",{className:u.isDark?"shrink-0 border-b border-rose-400/20 bg-rose-500/12 px-4 py-2 text-sm text-rose-200 md:px-5":"shrink-0 border-b border-rose-300 bg-rose-50 px-4 py-2 text-sm text-rose-700 md:px-5",children:S}),s.jsx("div",{className:u.dialogBodyClass,children:E?s.jsx(lN,{status:E,emptyMessage:G,daemonId:a,sendDaemonCommand:t,activeTab:m,onActiveTabChange:h,helpOpen:g,onHelpOpenChange:k,hideControls:!0}):s.jsx("div",{className:u.dialogEmptyClass,children:G})})]})})}function yN(e,t){const{sendCommand:r}=bt(),[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=vN(n);return{remoteUrl:n,githubUrl:c,loading:o}}function vN(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 Ym=5e3;function wN(e){return`git:${e}`}function jN({workspace:e,includeDiffSummary:t=!1,intervalMs:r=Ym}){return{type:"subscribe",topic:"workspace.git",key:wN(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function ml(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Qs(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 kN(e){const t=ml(e);return(t==null?void 0:t.success)===!1?{status:null,error:Qs(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:Qs(t,"Git status response did not include status")}}function SN(e){const t=ml(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:Qs(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:Qs(t,"Git diff summary response did not include diffSummary")}}function Ao(e){return e===void 0||typeof e=="boolean"}function NN(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Ao(t.binary)&&Ao(t.truncated)&&Ao(t.staged)}function CN(e){const t=ml(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Qs(t,"Git file diff request failed")}:NN(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:Qs(t,"Git file diff response did not include a valid diff object")}}function IN({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=Ym}){const{sendCommand:o,sendData:i}=bt(),c=typeof t=="string"?t.trim():"",d=!!(r&&e&&c),[p,u]=l.useState(null),[m,h]=l.useState(null),[g,k]=l.useState(!1),[f,v]=l.useState(null),w=l.useCallback(async()=>{if(!(!d||!e||!c)){k(!0),v(null);try{const j=kN(await o(e,"git_status",{workspace:c}));if(j.error){u(null),h(null),v(j.error);return}if(u(j.status),!n){h(null);return}const C=SN(await o(e,"git_diff_summary",{workspace:c}));if(C.error){h(null),v(C.error);return}h(C.diffSummary)}catch(j){v(Qs(j,"Git status request failed"))}finally{k(!1)}}},[d,e,n,o,c]),x=l.useMemo(()=>c?jN({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return l.useEffect(()=>{if(!d||!e||!c||!x){u(null),h(null),k(!1),v(null);return}const j=i?is.subscribe({sendData:i},e,x,C=>{var y,b;C.workspace===c&&(u(C.status),h(C.diffSummary??null),v(((y=C.status)==null?void 0:y.error)||((b=C.diffSummary)==null?void 0:b.error)||null),k(!1))},{retryIntervalMs:1e3}):null;return w(),()=>{j==null||j()}},[d,e,w,x,i,c]),{status:p,diffSummary:m,loading:g,error:f,refresh:w}}const AN={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},MN={added:"text-status-online",modified:"text-orange-400",deleted:"text-status-error",renamed:"text-accent-primary",copied:"text-accent-primary",untracked:"text-text-muted",conflict:"text-status-error font-bold"};function md(e){return e.split("/").pop()??e}function TN(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function _N({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=AN[o.status]??"?",d=MN[o.status]??"text-text-muted",p=TN(o.path),u=md(o.path),m=o.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-status-online 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:u}),o.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",md(o.oldPath)]}),m]}),!o.binary&&(o.insertions>0||o.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[o.insertions>0&&s.jsxs("span",{className:"text-status-online",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-status-error",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 LN(e,t){let r="text-text-secondary";return e.startsWith("+")&&!e.startsWith("+++")?r="bg-status-online/10 text-status-online":e.startsWith("-")&&!e.startsWith("---")?r="bg-status-error/10 text-status-error":e.startsWith("@@")?r="text-accent-primary":(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 RN({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-status-error ${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(`
|
|
85
|
+
`);return s.jsxs("div",{ref:i,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:c.map((d,p)=>LN(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 PN(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(`
|
|
86
|
+
`)}function Jm({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=bt(),{status:a,diffSummary:o,loading:i,error:c,refresh:d}=IN({daemonId:e,workspace:t,includeDiffSummary:!0}),[p,u]=l.useState(null),[m,h]=l.useState(null),[g,k]=l.useState(""),[f,v]=l.useState(!1),[w,x]=l.useState(!1),[j,C]=l.useState(null),[y,b]=l.useState(null),{githubUrl:N}=yN(e,t),S=l.useCallback(async $=>{if(!((p==null?void 0:p.path)===$.path&&!p.loading)){u({path:$.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const Y=await n(e,"git_diff_file",{workspace:t,path:$.path,staged:$.staged}),_=CN(Y);if(_.error||!_.diff){u({path:$.path,diff:"",binary:!1,truncated:!1,loading:!1,error:_.error??"Failed to load diff"});return}u({path:$.path,diff:_.diff.diff,binary:_.diff.binary??!1,truncated:_.diff.truncated??!1,loading:!1,error:null})}catch(Y){const _=Y instanceof Error?Y.message:"Failed to load diff";u({path:$.path,diff:"",binary:!1,truncated:!1,loading:!1,error:_})}}},[e,n,p,t]),I=l.useCallback($=>{k(""),v(!1),C(null),b(null),h($)},[]),R=l.useCallback(()=>{h(null),C(null),x(!1)},[]),L=l.useCallback(async()=>{var $,Y,_;if(m){x(!0),C(null);try{let H;m==="checkpoint"?H=await n(e,"git_checkpoint",{workspace:t,message:g,includeUntracked:f}):m==="stash"?H=await n(e,"git_stash_push",{workspace:t,message:g,includeUntracked:f}):m==="stash_pop"?H=await n(e,"git_stash_pop",{workspace:t}):m==="checkout_files"&&p&&(H=await n(e,"git_checkout_files",{workspace:t,paths:[p.path]}));const W=(H==null?void 0:H.result)??H;if((W==null?void 0:W.success)===!1||W!=null&&W.error){C((W==null?void 0:W.error)??"Action failed"),x(!1);return}m==="checkpoint"?b(`Checkpoint created: ${((Y=($=W==null?void 0:W.checkpoint)==null?void 0:$.commit)==null?void 0:Y.slice(0,7))??"done"}`):m==="stash"?b(`Stashed as ${((_=W==null?void 0:W.stash)==null?void 0:_.stashRef)??"stash@{0}"}`):m==="stash_pop"?b("Stash restored"):(b("File reverted"),u(null)),h(null),await d()}catch(H){C(H instanceof Error?H.message:"Action failed")}finally{x(!1)}}},[m,n,e,t,g,f,p,d]),M=!!(a!=null&&a.hasConflicts),P=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}),N&&s.jsx("a",{href:`${N}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-accent-primary 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(Nt,{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-status-online",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-status-error",children:[a.deleted," deleted"]}),a.stashCount>0&&s.jsxs("span",{children:[a.stashCount," stashed"]}),a.hasConflicts&&s.jsx("span",{className:"font-bold text-status-error",children:"conflicts"}),P===0&&!a.error&&s.jsx("span",{className:"text-status-online",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-status-online",children:[" +",o.totalInsertions]}),o.totalDeletions>0&&s.jsxs("span",{className:"text-status-error",children:[" -",o.totalDeletions]})]})]}),c&&s.jsx("div",{className:"shrink-0 border-b border-border/50 bg-status-error/10 px-4 py-2 text-xs text-status-error",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(_N,{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(RN,{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"})})]}),y&&s.jsxs("div",{className:"shrink-0 border-t border-border/50 bg-status-online/10 px-4 py-2 text-xs text-status-online flex items-center justify-between",children:[s.jsx("span",{children:y}),s.jsx("button",{onClick:()=>b(null),className:"ml-2 text-status-online 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:M,title:M?"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:M,title:M?"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:M||!(a!=null&&a.stashCount),title:M?"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 $=PN((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText($),b("Copied to clipboard"),setTimeout(()=>b(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),m&&s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:s.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[s.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[m==="checkpoint"&&"Create checkpoint commit",m==="stash"&&"Stash changes",m==="stash_pop"&&"Restore latest stash?",m==="checkout_files"&&`Revert changes to ${(p==null?void 0:p.path)??"file"}?`]}),(m==="checkpoint"||m==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:g,onChange:$=>k($.target.value),maxLength:200,placeholder:"Message (required)",className:"rounded border border-border bg-surface-secondary px-2 py-1 text-xs text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-1 focus:ring-border",autoFocus:!0}),s.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:f,onChange:$=>v($.target.checked)}),"Include untracked files"]})]}),j&&s.jsx("p",{className:"text-xs text-status-error",children:j}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:R,disabled:w,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:w||(m==="checkpoint"||m==="stash")&&!g.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:w?"Working…":"Confirm"})]})]})})]})})}function DN({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=l.useState(!1),[o,i]=l.useState(!1),[c,d]=l.useState(!1),[p,u]=l.useState(!1),[m,h]=l.useState(!1),[g,k]=l.useState("quickstart"),[f,v]=l.useState("workspace"),w=l.useMemo(()=>!t&&!e,[t,e]),x=l.useCallback(S=>{a(S),S&&i(!1)},[]),j=l.useCallback(S=>{i(S),S&&a(!1)},[]),C=l.useCallback(()=>{k(r===0?"quickstart":"shortcuts"),v("workspace"),d(!0),a(!1),i(!1)},[r]),y=l.useCallback(()=>{d(!1)},[]),b=l.useCallback(()=>{u(!0)},[]),N=l.useCallback(()=>{u(!1)},[]);return l.useEffect(()=>{if(!w){h(!1);return}h(!0);const S=window.setTimeout(()=>{h(!1)},1e4);return()=>window.clearTimeout(S)},[w]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:p,guideNudgeVisible:m,guideTab:g,shortcutSection:f,isDesktopDashboard:w,setGuideTab:k,setShortcutSection:v,handleInboxOpenChange:x,handleHiddenOpenChange:j,handleOpenShortcutHelp:C,closeShortcutHelp:y,openNewSession:b,closeNewSession:N}}function $N(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 EN(e){return e instanceof Error?e.message:String(e||"")}function BN(e){const t=EN(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function FN({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:i,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:p,mobileChatConversations:u,hiddenConversations:m,ides:h,actionLogs:g,sendDaemonCommand:k,setActionLogs:f,setCliViewModeOverrides:v,isStandalone:w,initialDataLoaded:x,userName:j,requestedMobileTabKey:C,onRequestedMobileTabConsumed:y,requestedMachineId:b,onRequestedMachineConsumed:N,requestedMobileSection:S,onRequestedMobileSectionConsumed:I,containerRef:R,isSplitMode:L,numGroups:M,groupSizes:P,groupedConvs:$,clearedTabs:Y,focusedGroup:_,focusGroup:H,moveTabToGroup:W,splitTabRelative:B,closeGroup:T,handleResizeStart:A,groupActiveTabIds:E,setGroupActiveTab:z,groupTabOrders:G,setGroupTabOrder:re,toggleHiddenTab:X,visibleConversations:te,requestedDesktopTabKey:J,onRequestedDesktopTabConsumed:F,onDesktopActiveTabChange:K,onRequestScrollToBottom:fe,onHideConversation:be,onShowHiddenConversation:oe,onShowAllHiddenConversations:je,scrollToBottomRequest:ge,machineEntries:we,layoutProfile:me,onBrowseMachineDirectory:U,onSaveMachineWorkspace:O,onLaunchMachineIde:Z,onLaunchMachineProvider:V,onListMachineMeshes:he,onLaunchMeshCoordinator:le,onListMachineSavedSessions:D,notifications:de,notificationUnreadCount:Se,liveSessionInboxState:ue,onMarkNotificationRead:q,onMarkNotificationUnread:ve,onDeleteNotification:Ae}){const Ne=Lt.useRef(null),{inboxOpen:Ke,hiddenOpen:ie,shortcutHelpOpen:Fe,newSessionOpen:$e,guideNudgeVisible:tt,guideTab:qe,shortcutSection:ke,isDesktopDashboard:ot,setGuideTab:Ie,setShortcutSection:it,handleInboxOpenChange:ct,handleHiddenOpenChange:Ze,handleOpenShortcutHelp:Ot,closeShortcutHelp:Q,openNewSession:ee,closeNewSession:ae}=DN({isMobile:t,showMobileChatMode:e,visibleConversationCount:te.length}),[pe,xe]=Lt.useState(null),[Me,Le]=Lt.useState(null),Ce=Lt.useCallback((_e,Je)=>{xe({daemonId:_e,workspace:Je})},[]),Ee=Lt.useCallback(_e=>{Le(_e)},[]),Ge=Lt.useCallback(_e=>{var Je;hr.flushSync(()=>{oe(_e)}),(Je=Ne.current)==null||Je.restoreHiddenTabToSavedLocation(_e.tabKey)},[oe]),Xe=Lt.useCallback(_e=>{var Mt;const Je=u.find(It=>Jo(It,_e))||m.find(It=>Jo(It,_e));Je&&(m.some(It=>It.tabKey===Je.tabKey)&&Ge(Je),K(Je.tabKey),(Mt=Ne.current)==null||Mt.activateConversationTab(Je.tabKey),fe(Je.tabKey,"notification-open")),q(_e.id),ct(!1)},[Ge,m,u,K,q,fe]),De=Lt.useCallback(()=>{var Je;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Je=Ne.current)==null||Je.resetAllPanelsToMain(),Ze(!1))},[Ze]),Oe=Lt.useCallback(async _e=>{var Vt;if(!r)return;const Je=(Vt=r.modalButtons)==null?void 0:Vt[_e];if(!Je)return;const Mt=Ks(r);if(!Mt)return;const It=Je.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),zt=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(It);try{await k(Mt,"resolve_action",{button:Je,action:zt?"approve":"reject",buttonIndex:_e,...Ws(r)})}catch(qt){BN(qt)||console.error("[Shortcut approval] Failed:",qt)}},[r,k]),{isMac:ne,actionDefinitions:ce,actionShortcuts:ye,shortcutListening:Be,shortcutListeningDraft:Ue,setShortcutListening:Qe,setShortcutListeningDraft:et,saveShortcuts:Ye}=hk({enabled:ot&&!Fe,onTrigger:_e=>{var Je,Mt,It,zt,Vt,qt,ys,Re,nt,kt,Ht,se,He,Pe,gt,Yt;if(_e==="openShortcutHelp"){Ot();return}if(_e==="openNewSession"){ee();return}if(_e==="hideCurrentTab"){r&&be(r);return}if(_e==="toggleHiddenTabs"){Ze(!ie);return}if(_e==="openHistoryForActiveTab"){r&&!lt(r)&&o(r);return}if(_e==="openRemoteForActiveTab"){r&&!dt(r)&&!lt(r)&&i(r);return}if(_e==="splitActiveTabRight"){(Je=Ne.current)==null||Je.splitActiveTabRight();return}if(_e==="splitActiveTabDown"){(Mt=Ne.current)==null||Mt.splitActiveTabDown();return}if(_e==="floatActiveTab"){(It=Ne.current)==null||It.floatActiveTab();return}if(_e==="popoutActiveTab"){(zt=Ne.current)==null||zt.popoutActiveTab();return}if(_e==="dockActiveTab"){(Vt=Ne.current)==null||Vt.dockActiveTab();return}if(_e==="focusLeftPane"){(qt=Ne.current)==null||qt.focusLeftPane();return}if(_e==="focusRightPane"){(ys=Ne.current)==null||ys.focusRightPane();return}if(_e==="focusUpPane"){(Re=Ne.current)==null||Re.focusUpPane();return}if(_e==="focusDownPane"){(nt=Ne.current)==null||nt.focusDownPane();return}if(_e==="moveActiveTabToLeftPane"){(kt=Ne.current)==null||kt.moveActiveTabToLeftPane();return}if(_e==="moveActiveTabToRightPane"){(Ht=Ne.current)==null||Ht.moveActiveTabToRightPane();return}if(_e==="moveActiveTabToUpPane"){(se=Ne.current)==null||se.moveActiveTabToUpPane();return}if(_e==="moveActiveTabToDownPane"){(He=Ne.current)==null||He.moveActiveTabToDownPane();return}if(_e==="triggerPrimaryApprovalAction"){Oe(0);return}if(_e==="triggerSecondaryApprovalAction"){Oe(1);return}if(_e==="triggerTertiaryApprovalAction"){Oe(2);return}if(_e==="setActiveTabShortcut"){(Pe=Ne.current)==null||Pe.setShortcutForActiveTab();return}if(_e==="selectPreviousGroupTab"){(gt=Ne.current)==null||gt.activatePreviousTabInGroup();return}if(_e==="selectNextGroupTab"){(Yt=Ne.current)==null||Yt.activateNextTabInGroup();return}!r||!dt(r)||lt(r)||_e==="toggleCliView"&&p(d==="chat"?"terminal":"chat")}}),Ve=Lt.useCallback(()=>{Q(),Qe(null),et([])},[Q,Qe,et]),Ct=Lt.useMemo(()=>ke==="all"?ce:ce.filter(_e=>$N(_e)===ke),[ce,ke]),us=Lt.useCallback(()=>{const _e=Object.fromEntries(ce.map(Je=>[Je.id,""]));Ye(_e)},[ce,Ye]),ts=Lt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const _e=Object.fromEntries(ce.map(Je=>[Je.id,Je.defaultShortcut]));Ye(_e)},[ce,Ye]);return Lt.useEffect(()=>{const _e=Je=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Je.metaKey&&Je.key.toLowerCase()==="w":Je.ctrlKey&&Je.key.toLowerCase()==="w")&&(Je.preventDefault(),r&&be&&be(r))};return window.addEventListener("keydown",_e),()=>window.removeEventListener("keydown",_e)},[r,be]),Lt.useEffect(()=>{if(!Fe||Be)return;const _e=Je=>{Je.key==="Escape"&&(Je.preventDefault(),Ve())};return window.addEventListener("keydown",_e,!0),()=>window.removeEventListener("keydown",_e,!0)},[Ve,Fe,Be]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(J0,{activeConv:r,wsStatus:n,isConnected:a,conversations:te,hiddenConversations:m,onOpenHistory:o,onHideConversation:be,onShowConversation:Ge,onShowAllHidden:je,onResetPanelsToMain:De,notifications:de,notificationUnreadCount:Se,onOpenNotification:Xe,onMarkNotificationRead:q,onMarkNotificationUnread:ve,onDeleteNotification:Ae,inboxOpen:Ke,onInboxOpenChange:ct,hiddenOpen:ie,onHiddenOpenChange:Ze,onOpenNewSession:t?void 0:ee,onOpenDashboardGuide:Ot,guideNudgeVisible:tt,actionShortcuts:ye,onOpenRemote:()=>{!r||dt(r)||lt(r)||i(r)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:p,onOpenGitDialog:Ce,onOpenMeshGraph:Ee}),e?s.jsx(sk,{conversations:u,hiddenConversations:m,ides:h,actionLogs:g,sendDaemonCommand:k,setActionLogs:f,setCliViewModeOverrides:v,isStandalone:w,userName:j,requestedActiveTabKey:C,onRequestedActiveTabConsumed:y,requestedMachineId:b,onRequestedMachineConsumed:N,requestedMobileSection:S,onRequestedMobileSectionConsumed:I,onOpenHistory:o,onOpenRemote:i,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:je,onHideConversation:be,onOpenMeshGraph:Ee,onOpenNewSession:ee,liveSessionInboxState:ue}):t?s.jsx(dk,{containerRef:R,isSplitMode:L,numGroups:M,groupSizes:P,groupedConvs:$,clearedTabs:Y,ides:h,actionLogs:g,sendDaemonCommand:k,setActionLogs:f,isStandalone:w,hasRegisteredMachines:we.length>0,userName:j,focusedGroup:_,focusGroup:H,moveTabToGroup:W,splitTabRelative:B,closeGroup:T,handleResizeStart:A,groupActiveTabIds:E,setGroupActiveTab:z,groupTabOrders:G,setGroupTabOrder:re,toggleHiddenTab:X,onOpenNewSession:ee,allowTabShortcuts:!1,liveSessionInboxState:ue}):s.jsx(Ak,{visibleConversations:te,clearedTabs:Y,ides:h,actionLogs:g,sendDaemonCommand:k,setActionLogs:f,isStandalone:w,hasRegisteredMachines:we.length>0,initialDataLoaded:x,userName:j,toggleHiddenTab:X,actionShortcuts:ye,registerActionHandlers:_e=>{Ne.current=_e},onActiveTabChange:K,requestedActiveTabKey:J,onRequestedActiveTabConsumed:F,onRequestScrollToBottom:fe,scrollToBottomRequest:ge,onOpenNewSession:ee,liveSessionInboxState:ue,layoutProfile:me}),$e&&s.jsx(Bk,{machines:we,ides:h,onClose:ae,onBrowseDirectory:U,onSaveWorkspace:O,onLaunchIde:Z,onLaunchProvider:V,onListMeshes:he,onLaunchMeshCoordinator:le,onListSavedSessions:D}),Me&&s.jsx(qm,{activeConv:Me,sendDaemonCommand:k,onClose:()=>Le(null)}),pe&&s.jsx(Jm,{daemonId:pe.daemonId,workspace:pe.workspace,onClose:()=>xe(null)}),Fe&&s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:Ve,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:_e=>_e.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:Ve,"aria-label":"Close dashboard guide",children:s.jsx(Nt,{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(_e=>s.jsx("button",{type:"button",className:`btn btn-sm ${qe===_e.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ie(_e.id),children:_e.label},_e.id))}),qe==="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 ",ne?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),qe==="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."]})]})]})]}),qe==="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(_e=>s.jsx("button",{type:"button",className:`btn btn-sm ${ke===_e.id?"btn-primary":"btn-secondary"}`,onClick:()=>it(_e.id),children:_e.label},_e.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:us,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:ts,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Ct.map(_e=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${Be===_e.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:_e.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:_e.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:_e.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-surface-secondary border border-border-subtle min-w-[72px] text-center",children:Be===_e.id?Ue.length>0?`${Ue.join(" ")} ...`:"Listening...":ye[_e.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Qe(_e.id),et([])},children:Be===_e.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Je={...ye};Je[_e.id]="",Ye(Je)},children:"Disable"})]})]})},_e.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",ne?"⌘⇧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 ON=[{icon:"🦦",title:"Welcome to ADHDev",desc:"Drive any local CLI coding agent — Claude Code, Codex, Gemini — straight from your browser or phone. The agents keep running on your machine; you control them from the web.",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:"Watch and steer, live",desc:"Follow each agent's session in real time and steer it as it works — switch sessions, take screenshots, and (for IDE sessions) view and control the screen over a P2P connection.",visual:"🖱️"},{icon:"🕸️",title:"Orchestrate your agents",desc:"Repo Mesh (Cloud Pro) lets one coordinator hand work to agents across many machines — parallel git worktrees, automatic branch convergence, and cross-checking the same repo from several angles.",visual:"🕸️"}],HN={icon:"🚀",title:"Get started",desc:"Run this on any machine you want to drive, then sign in — the daemon pairs itself to your dashboard automatically.",code:"curl -fsSL https://adhf.dev/install | sh"},WN={icon:"🚀",title:"You're all set",desc:"This dashboard is already connected to your local daemon. Start a session from the Dashboard tab, or add more providers under Burrow → Providers.",visual:"✅"};function KN({onClose:e,standalone:t=!1}){const[r,n]=l.useState(0),a=[...ON,t?WN:HN],o=a[r],i=r===a.length-1;return s.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:"var(--z-modal)",background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:c=>{c.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(Nt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:a.map((c,d)=>s.jsx("div",{style:{width:d===r?24:8,height:8,borderRadius:4,background:d===r?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},d))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:o.visual||o.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:o.icon})," ",o.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:o.desc}),o.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:"$"}),o.code]}),i&&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:()=>i?e():n(c=>c+1),className:"btn btn-primary",children:i?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
|
|
87
|
+
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
88
|
+
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
89
|
+
`})]})}function UN({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 GN({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,i]=l.useState(()=>a||"native"),c=l.useMemo(()=>vp(t),[t]),d=l.useMemo(()=>e?Vi(e,{machineNames:c,connectionStates:r,defaultConnectionState:"new"}):[],[e,c,r]),p=l.useMemo(()=>d.find(f=>f.streamSource==="native"),[d]),u=l.useMemo(()=>d.filter(f=>f.streamSource==="agent-stream"),[d]),m=l.useMemo(()=>e?ls(d,e.id):null,[d,e]);l.useEffect(()=>{a&&i(a)},[a]),l.useEffect(()=>{if(a||!m)return;const f=m.streamSource==="native"?"native":m.tabKey;!f||o===f||o==="native"&&i(f)},[o,m,a]),l.useEffect(()=>{var f;o!=="native"&&(u.some(v=>v.tabKey===o)||i(((f=u[0])==null?void 0:f.tabKey)||"native"))},[o,u]),l.useEffect(()=>{o==="native"&&(p||u[0]&&i(u[0].tabKey))},[o,p,u]);const h=l.useMemo(()=>o==="native"&&p?p:u.find(f=>f.tabKey===o)||m||p||u[0],[o,p,m,u]),g=l.useMemo(()=>u.map(f=>({tabKey:f.tabKey,title:lp(f)||n,status:f.status})),[u,n]),k=l.useCallback(f=>{if(f)return d.find(v=>Jo(v,{sessionId:f,routeId:f,tabKey:f,providerSessionId:f}))},[d]);return{activeChatTab:o,setActiveChatTab:i,activeConv:h,conversations:d,extensionTabs:g,hasExtensions:g.length>0,resolveConversationByTarget:k}}function zN({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:i,isStandalone:c,userName:d,onOpenHistory:p,onConversationChange:u,onClose:m}){const[h,g]=l.useState("split"),[k,f]=l.useState(()=>_s(e)?"native":e.tabKey),v=l.useRef(null),w=l.useMemo(()=>t||r.find(H=>H.id===e.routeId),[e.routeId,t,r]),x=l.useMemo(()=>$t((w==null?void 0:w.type)||""),[w==null?void 0:w.type]),{conversations:j,extensionTabs:C,hasExtensions:y}=GN({ideData:w,allIdes:r,connectionStates:n,ideName:x||"IDE",preferredTabKey:_s(e)?void 0:e.tabKey}),b=l.useMemo(()=>w?ls(j,w.id):null,[w,j]);l.useEffect(()=>{const H=v.current,W={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(v.current=W,!(H&&H.routeId===W.routeId&&H.tabKey===W.tabKey&&H.streamSource===W.streamSource)){if(_s(e)){f("native");return}f(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),l.useEffect(()=>{if(k==="native"){if(j.some(H=>H.streamSource==="native"))return;(b==null?void 0:b.streamSource)==="agent-stream"&&f(b.tabKey);return}if(!j.some(H=>H.tabKey===k)){if((b==null?void 0:b.streamSource)==="agent-stream"){f(b.tabKey);return}f("native")}},[j,k,b]);const N=l.useMemo(()=>k==="native"?j.find(H=>H.streamSource==="native")||e:j.find(H=>H.tabKey===k)||e,[e,j,k]),S=Rp(N),I=l.useMemo(()=>S.status||S.modalMessage||S.modalButtons?{...N,...S.status?{status:S.status}:{},...S.modalMessage!==void 0?{modalMessage:S.modalMessage}:{},...S.modalButtons!==void 0?{modalButtons:S.modalButtons}:{}}:N,[N,S]),R=er(I),L=_a({sendDaemonCommand:o,activeConv:I,setActionLogs:i,isStandalone:c}),{connScreenshot:M,screenshotUsage:P,handleRemoteAction:$}=um({doId:R,targetSessionId:Fu(I),connState:I.connectionState||"new",viewMode:h}),Y=l.useMemo(()=>a.filter(H=>H.routeId===I.tabKey),[a,I.tabKey]);l.useEffect(()=>{u==null||u(I)},[I,u]),l.useEffect(()=>{const H=W=>{W.key==="Escape"&&m()};return window.addEventListener("keydown",H),()=>window.removeEventListener("keydown",H)},[m]);const _=l.useCallback(H=>{H.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal-backdrop)] flex items-center justify-center p-0 md:p-3 bg-black/60 backdrop-blur-md",onClick:m,children:s.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:_,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(ds,{size:16})}),s.jsx("span",{className:"truncate",children:Hi(N)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:m,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(H=>{const W=h===H;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${W?"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:()=>g(H),title:H==="split"?"Split view":"Remote only",children:H==="split"?s.jsx(Ef,{size:15}):s.jsx(ds,{size:15})},H)})}),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(N),title:"Chat History",children:[s.jsx(Ii,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:"History"})]}),s.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:m,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${h==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[h!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${h==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(UN,{hasExtensions:y,ideName:x||"IDE",activeChatTab:k,extensionTabs:C,onSelectTab:f}),s.jsx(pu,{activeConv:I,onModalButton:L.handleModalButton}),s.jsx(ni,{activeConv:I,ideEntry:w,showMetaChips:!1,handleSendChat:L.handleSendChat,handleForceSendChat:L.handleForceSendChat,isSendingChat:L.isSendingChat,sendFeedbackMessage:L.sendFeedbackMessage,handleFocusAgent:L.handleFocusAgent,isFocusingAgent:L.isFocusingAgent,actionLogs:Y,userName:d})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${h==="split"?"order-1 md:order-2":""}`,children:s.jsx(iu,{addLog:()=>{},connState:I.connectionState||"new",connScreenshot:M,screenshotUsage:P,transportType:I.transport,onAction:$})})]})]})})}function VN({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const{t:o}=Pt(),i=T0(e);return s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] 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 mobile-compact-dialog 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-bg-primary",children:[s.jsx("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:o("cliStop.title",{agent:i})}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:o(t?"cliStop.gracefulDescription":"cliStop.forceOnlyDescription")})]}),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:o("cliStop.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:o("cliStop.forceStop")}),s.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:o("common.cancel")})]})]})]})}function qN({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o,interactivePrompt:i}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(G0,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(bp,{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(zN,{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&&(dt(r.targetConv)||lt(r.targetConv))&&s.jsx(VN,{activeConv:r.targetConv,canSaveAndStop:dt(r.targetConv)&&!lt(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(gp,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),s.jsx(cu,{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(KN,{onClose:o.onClose,standalone:o.standalone})]})}function YN({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(ka,{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=es(i,{fallbackId:i.id}),d=n[i.id],p=i.version||i.daemonVersion||"unknown",u=i.versionUpdateRequired===!0,h=Kp(i)==="preview"?"Update to preview":u?"Update now":"Upgrade";return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[s.jsx("span",{className:"font-medium text-text-primary",children:c}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",p]}),u&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),d==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:u?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):d==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):d==="error"?s.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(i.id),children:"retry"}):s.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:u?"var(--status-danger)":"var(--status-warning)",background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(i.id),children: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(Nt,{size:16})})]})}function JN(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function XN(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 QN(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>XN(t)).map(t=>t.id)}}function ZN(){var yl,vl,wl,jl;const{sendCommand:e}=bt(),t=Ar(),r=Lp(),n=ji(),a=mn(),[o,i]=Hh(),c=o.get("activeTab"),d=((yl=n.state)==null?void 0:yl.openRemoteForTabKey)||null,p=((vl=n.state)==null?void 0:vl.openMachineId)||null,u=((wl=n.state)==null?void 0:wl.mobileSection)||null,m=rp(),h=m.ides||[],g=m.initialLoaded??!0,{updateRouteChats:k,setToasts:f}=m,[v,w]=l.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),x=m.toasts||[],j=m.wsStatus||"connected",C=m.isConnected??!0,y=m.connectionStates||{},b=m.showReconnected||!1,{layoutProfile:N,groupAssignments:S,updateGroupAssignments:I,focusedGroup:R,updateFocusedGroup:L,focusGroup:M,groupActiveTabIds:P,updateGroupActiveTabIds:$,setGroupActiveTab:Y,groupTabOrders:_,updateGroupTabOrders:H,setGroupTabOrder:W,groupSizes:B,updateGroupSizes:T,isMobile:A,hasHydratedStoredLayout:E,hydrateStoredLayout:z,focusConversationTab:G}=Xw(),[re,X]=l.useState(()=>Xi());l.useEffect(()=>aw(X),[]);const te=l.useMemo(()=>JN({isMobile:A,mobileViewMode:re}),[A,re]),[J,F]=l.useState([]),[K,fe]=l.useState({}),[be,oe]=l.useState({});hn("Dashboard",{ideCount:h.length,toastCount:x.length,focusedGroup:R,groupCount:Object.keys(S).length,actionLogCount:J.length});const je=l.useMemo(()=>h.filter(at=>at.type==="adhdev-daemon").sort(Di),[h]),we=!!je[0];l.useEffect(()=>{const{metadataDaemonIds:at,runtimeDaemonIds:Wt}=QN(je);for(const Tr of at)t(Tr,{minFreshMs:3e4}).catch(()=>{});for(const Tr of Wt)r(Tr,{minFreshMs:3e4}).catch(()=>{})},[t,r,je]);const me=l.useMemo(()=>kw(h,K),[h,K]),{conversations:U,visibleConversations:O,visibleTabKeys:Z,resolveConversationBySessionId:V,resolveConversationByTarget:he}=$w({ides:me,connectionStates:y,clearedTabs:be}),le=l.useMemo(()=>new Map(U.map(at=>[at.tabKey,at])),[U]);s0(O,te);const D=l.useMemo(()=>uu(h),[h]),de=sm(D,e,l.useCallback(at=>or(f,`⚠️ ${at}`),[f])),{notifications:Se,unreadCount:ue}=mj({conversations:U,liveSessionInboxState:D}),{handleMarkDashboardNotificationRead:q,handleMarkDashboardNotificationUnread:ve,handleDeleteDashboardNotification:Ae}=hj({notifications:Se,sendDaemonCommand:e}),{containerRef:Ne,normalizedGroupAssignments:Ke,numGroups:ie,isSplitMode:Fe,groupedConvs:$e,moveTabToGroup:tt,closeGroup:qe,handleResizeStart:ke,splitTabRelative:ot}=nj({groupAssignments:S,updateGroupAssignments:I,updateFocusedGroup:L,updateGroupActiveTabIds:$,updateGroupTabOrders:H,groupSizes:B,updateGroupSizes:T,isMobile:A,visibleConversations:O,visibleTabKeys:Z}),{activeConv:Ie,openDesktopConversation:it,requestScrollToBottom:ct,scrollToBottomRequest:Ze,setDesktopActiveTab:Ot}=Cj({isMobile:A,conversations:U,visibleConversations:O,groupActiveTabIds:P,focusedGroup:R,groupedConvs:$e,setSearchParams:i});Mj({activeConv:Ie,isMobile:A,liveSessionInboxState:D,sendDaemonCommand:e});const{requestedDesktopTabKey:Q,requestedMobileTabKey:ee,consumeRequestedActiveTab:ae}=Ew({isMobile:A,urlActiveTab:c,resolveConversationBySessionId:V,setSearchParams:i}),{remoteDialogConv:pe,remoteDialogIdeEntry:xe,remoteDialogActiveConv:Me,setRemoteDialogActiveConv:Le,openRemoteDialog:Ce,closeRemoteDialog:Ee,cliStopDialogOpen:Ge,cliStopTargetConv:Xe,requestCliStop:De,cancelCliStop:Oe,confirmCliStop:ne}=Lj({isMobile:A,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:Q,conversations:U,ides:h,resolveConversationByTarget:he,activeConv:Ie,sendDaemonCommand:e}),{historyModalOpen:ce,openHistoryModal:ye,closeHistoryModal:Be,historyTargetConv:Ue,isSavedSessionHistoryTarget:Qe,isHistoryCreatingChat:et,isHistoryRefreshingHistory:Ye,handleHistorySwitchSession:Ve,handleHistoryNewChat:Ct,handleHistoryRefresh:us,savedHistorySessions:ts,savedHistoryFilters:_e,setSavedHistoryFilters:Je,missingWorkspaceResumePath:Mt,isSavedHistoryLoading:It,resumingSavedHistorySessionId:zt,handleRefreshSavedHistory:Vt,handleResumeSavedHistorySession:qt}=Tj({activeConv:Ie,remoteDialogConv:pe,remoteDialogActiveConv:Me,ides:h,sendDaemonCommand:e,updateRouteChats:k,setToasts:f,setClearedTabs:oe,setSearchParams:i}),ys=l.useMemo(()=>O,[O]),Re=A&&re==="chat",nt=l.useMemo(()=>U.filter(at=>Ls(at,D).surfaceHidden),[U,D]),kt=l.useCallback(at=>{const Wt=new URLSearchParams(o);Wt.set("activeTab",at),i(Wt,{replace:!0})},[o,i]),{trackPendingLaunch:Ht}=jj({ides:h,conversations:U,onOpenSession:kt}),{handleBrowseMachineDirectory:se,handleSaveMachineWorkspace:He,handleLaunchMachineIde:Pe,handleLaunchMachineProvider:gt,handleListMachineMeshes:Yt,handleLaunchMeshCoordinator:Mr,handleListMachineSavedSessions:Ha,setActiveCliViewMode:vs}=kj({sendDaemonCommand:e,trackPendingLaunch:Ht,onOpenSession:kt,activeConv:Ie,ides:h,setCliViewModeOverrides:fe});Nw({visibleConversations:O,clearedTabs:be,setClearedTabs:oe,setActionLogs:F,isConversationMuted:de.isMuted}),Bw({ides:h,sendDaemonCommand:e,setToasts:f,resolveConversationByTarget:he});const ah=Pp(),{isRefreshingHistory:oh,handleRefreshHistory:ih}=Wp({sendDaemonCommand:e,activeConv:Ie,chats:(jl=h.find(at=>at.id===(Ie==null?void 0:Ie.routeId)))==null?void 0:jl.chats,updateRouteChats:k,setToasts:f,setClearedTabs:oe});Zw({urlActiveTab:A&&!Re?c:null,conversations:U,resolveConversationBySessionId:V,normalizedGroupAssignments:Ke,hasHydratedStoredLayout:A&&!Re?E:!0,hydrateStoredLayout:A&&!Re?z:()=>{},focusConversationTab:G,setSearchParams:i,historyModalOpen:ce,activeConv:Ie,isRefreshingHistory:oh,ides:h,handleRefreshHistory:ih});const lh=l.useMemo(()=>!Ie||!dt(Ie)||lt(Ie)?null:Ir(Ie),[Ie]),{versionMismatchDaemons:ch,hasRequiredVersionDaemons:bl,targetVersion:dh,versionBannerDismissed:uh,setVersionBannerDismissed:ph,upgradingDaemons:mh,handleBannerUpgrade:hh}=oj({ides:h,sendDaemonCommand:e}),gl=l.useCallback(at=>{de.setHidden(at,!1),it(at)},[it,de]),fh=l.useCallback(()=>{for(const at of nt)de.setHidden(at,!1)},[nt,de]),xh=l.useCallback(at=>{de.setHidden(at,!0)},[de]),bh=l.useCallback(at=>{de.toggleHidden(at)},[de]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[(!uh||bl)&&s.jsx(YN,{daemons:ch,targetVersion:dh,required:bl,upgradingDaemons:mh,onUpgrade:hh,onDismiss:()=>ph(!0)}),s.jsx(FN,{showMobileChatMode:Re,isMobile:A,activeConv:Ie,wsStatus:j,isConnected:C,onOpenHistory:at=>{at&&Le(at),ye()},onOpenRemote:Ce,onStopCli:De,activeCliViewMode:lh,onSetActiveCliViewMode:vs,mobileChatConversations:ys,ides:h,actionLogs:J,sendDaemonCommand:e,setActionLogs:F,setCliViewModeOverrides:fe,isStandalone:we,initialDataLoaded:g,userName:m.userName,requestedMobileTabKey:ee,onRequestedMobileTabConsumed:ae,requestedMachineId:p,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:u,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:Ne,isSplitMode:Fe,numGroups:ie,groupSizes:B,groupedConvs:$e,clearedTabs:be,focusedGroup:R,focusGroup:M,moveTabToGroup:tt,splitTabRelative:ot,closeGroup:qe,handleResizeStart:ke,groupActiveTabIds:P,setGroupActiveTab:Y,groupTabOrders:_,setGroupTabOrder:W,toggleHiddenTab:at=>{const Wt=le.get(at);Wt&&bh(Wt)},visibleConversations:O,hiddenConversations:nt,requestedDesktopTabKey:Q,onRequestedDesktopTabConsumed:ae,onDesktopActiveTabChange:Ot,onRequestScrollToBottom:ct,onHideConversation:xh,onShowHiddenConversation:gl,onShowAllHiddenConversations:fh,scrollToBottomRequest:Ze,machineEntries:je,layoutProfile:N,onBrowseMachineDirectory:se,onSaveMachineWorkspace:He,onLaunchMachineIde:Pe,onLaunchMachineProvider:gt,onListMachineMeshes:Yt,onLaunchMeshCoordinator:Mr,onListMachineSavedSessions:Ha,notifications:Se,notificationUnreadCount:ue,liveSessionInboxState:D,onMarkNotificationRead:q,onMarkNotificationUnread:ve,onDeleteNotification:Ae}),s.jsx("style",{children:`
|
|
90
|
+
body { overflow: hidden; overscroll-behavior: none; }
|
|
91
|
+
`}),s.jsx(qN,{historyModal:{open:ce,targetConv:Ue,ides:h,isCreatingChat:et,isRefreshingHistory:Qe?!1:Ye,savedSessions:ts,savedHistoryFilters:_e,missingWorkspaceResumePath:Mt||null,onSavedHistoryFiltersChange:Je,isSavedSessionsLoading:It,isResumingSavedSessionId:zt,onClose:Be,onNewChat:Ct,onSwitchSession:Ve,onRefreshHistory:Qe?Vt:us,onResumeSavedSession:qt},remoteDialog:{conversation:pe,ideEntry:xe,ides:h,connectionStates:y,actionLogs:J,sendDaemonCommand:e,setActionLogs:F,isStandalone:we,userName:m.userName,onOpenHistory:at=>{at&&Le(at),ye()},onConversationChange:Le,onClose:Ee},cliStopDialog:{open:Ge,targetConv:Xe,onCancel:Oe,onStopNow:async()=>{await ne("hard")},onSaveAndStop:async()=>{await ne("save")}},connectionBanner:{wsStatus:j,showReconnected:b,loginUrl:m.connectionLoginUrl,onReconnect:m.retryServerConnection},toastOverlay:{toasts:x,onDismiss:at=>f(Wt=>Wt.filter(Tr=>Tr.id!==at)),onClick:at=>{if(at.targetKey){const Wt=he(at.targetKey);Wt&&(G(Wt.tabKey,Ke),gl(Wt),ct(Wt.tabKey,"toast-open"))}}},onboarding:{open:v,standalone:we,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}w(!1)}},interactivePrompt:ah})]})}function eC({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const{launchCli:o}=wa(),[i,c]=l.useState([]),[d,p]=l.useState(null),[u,m]=l.useState(null),[h,g]=l.useState(!1),[k,f]=l.useState(null),[v,w]=l.useState(!1),[x,j]=l.useState(""),C=l.useRef(null),y=l.useCallback(T=>{C.current=T},[]),b=l.useCallback((T,A,E=!1)=>{c(z=>[...z.slice(-100),{timestamp:Date.now(),level:T,message:A}]),setTimeout(()=>{var z;return(z=a.current)==null?void 0:z.scrollIntoView({behavior:"smooth"})},100),E&&ut.showToast(A,T==="error"||T==="warn"?"warning":"success")},[a]),N=l.useCallback(T=>{const A=T instanceof Error?T.message:String(T||"");return A.includes("P2P command timeout")||A.includes("P2P not connected")||A.includes("P2P not available")},[]),S=l.useCallback(async(T,A)=>{var E;if(!e||d)return!1;p(T),b("info",`Launching ${$t(T)}${A!=null&&A.workspace?` in ${A.workspace}`:""}...`);try{const z={ideType:T,enableCdp:!0};(E=A==null?void 0:A.workspace)!=null&&E.trim()?z.workspace=A.workspace.trim():A!=null&&A.useDefaultWorkspace&&(z.useDefaultWorkspace=!0);const G=await r(e,"launch_ide",z);return b(G!=null&&G.success?"info":"error",G!=null&&G.success?`${$t(T)} launched`:`Failed: ${G==null?void 0:G.error}`,!0),!!(G!=null&&G.success)}catch(z){return b("error",`Launch error: ${z.message}`,!0),!1}finally{p(null)}},[e,d,b,r]),I=l.useCallback(async T=>{if(!e)return{success:!1};const{cliType:A,dir:E,workspaceId:z,useDefaultWorkspace:G,useHome:re,argsStr:X,model:te,resumeSessionId:J}=T;if(!A)return b("warn","Select a CLI or ACP provider first",!0),{success:!1};const F=X?X.split(/\s+/).filter(Boolean):void 0,K=(E==null?void 0:E.trim())||(z?"(saved id)":G?"(default workspace)":re?"(home)":"");b("info",`Launching ${A}${K?` in ${K}`:""}${te?` (model: ${te})`:""}...`),m(A);try{const fe={cliType:A,cliArgs:F,initialModel:te||void 0};E!=null&&E.trim()?fe.dir=E.trim():z?fe.workspaceId=z:G?fe.useDefaultWorkspace=!0:re&&(fe.useHome=!0),J&&(fe.resumeSessionId=J);const be=await o(e,fe),oe=(be==null?void 0:be.result)||be;return be!=null&&be.success?(b("info",`${A} launched`,!0),(oe==null?void 0:oe.launchSource)==="home"?b("info","📂 Running in home directory (explicit choice)"):(oe==null?void 0:oe.launchSource)==="defaultWorkspace"&&b("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:oe==null?void 0:oe.sessionId}):(b("error",`Failed: ${(be==null?void 0:be.error)||(oe==null?void 0:oe.error)}`,!0),(be==null?void 0:be.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&f({cliType:A,argsStr:X,model:te}),{success:!1,sessionId:oe==null?void 0:oe.sessionId})}catch(fe){return N(fe)?(b("warn",`${A} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(b("error",`Launch error: ${fe.message}`,!0),{success:!1})}finally{m(null)}},[e,b,N,r]),R=l.useCallback(async(T,A,E,z)=>e?T?A.trim()?I({cliType:T,dir:A,argsStr:E,model:z}):(f({cliType:T,argsStr:E,model:z}),{success:!1}):(b("warn","Select a provider",!0),{success:!1}):{success:!1},[e,b,I]),L=l.useCallback(async(T,A,E)=>{if(e&&window.confirm(`Stop ${T}?
|
|
92
|
+
This will terminate the process.`))try{const z=await r(e,"stop_cli",{cliType:T,dir:A,targetSessionId:E});z!=null&&z.success?b("info",`${T} stopped`,!0):b("error",`Stop failed: ${(z==null?void 0:z.error)||"Unknown error"}`,!0)}catch(z){b("error",`Stop failed: ${z.message}`,!0)}},[e,b,r]),M=l.useCallback(async T=>{try{await r(T.daemonId,"restart_ide",{ideType:T.type}),b("info",`${$t(T.type)} restart initiated`,!0)}catch(A){b("error",`Restart failed: ${A.message}`,!0)}},[b,r]),P=l.useCallback(async T=>{if(window.confirm(`Stop ${$t(T.type)}?
|
|
93
|
+
This will disconnect CDP and optionally kill the process.`))try{const A=await r(T.daemonId,"stop_ide",{ideType:T.type,killProcess:!0});A!=null&&A.success?b("info",`${$t(T.type)} stopped`,!0):b("error",`Stop failed: ${(A==null?void 0:A.error)||"Unknown error"}`,!0)}catch(A){b("error",`Stop failed: ${A.message}`,!0)}},[b,r]),$=l.useCallback(async()=>{if(e)try{const T=await r(e,"detect_ides",{});b("info",`Found ${((T==null?void 0:T.result)||[]).length} IDE(s)`,!0)}catch(T){b("error",`Detection failed: ${T.message}`,!0)}},[e,b,r]),Y=l.useCallback(async T=>{if(!e||!T.trim())return!1;g(!0);try{const A=await r(e,"workspace_add",{path:T.trim()});return A!=null&&A.success?(b("info",`Workspace added: ${T.trim()}`),!0):(b("error",(A==null?void 0:A.error)||"workspace_add failed"),!1)}catch(A){return b("error",A.message),!1}finally{g(!1)}},[e,b,r]),_=l.useCallback(async T=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){g(!0);try{const A=await r(e,"workspace_remove",{id:T});A!=null&&A.success?b("info","Workspace removed",!0):b("error",(A==null?void 0:A.error)||"workspace_remove failed",!0)}catch(A){b("error",A.message,!0)}finally{g(!1)}}},[e,b,r]),H=l.useCallback(async T=>{var A;if(e){g(!0);try{const E=await r(e,"workspace_set_default",T===null?{clear:!0}:{id:T});if(E!=null&&E.success){b("info",T?"Default workspace updated":"Default workspace cleared",!0);const z=typeof E.defaultWorkspacePath=="string"?E.defaultWorkspacePath:"";z&&((A=C.current)==null||A.call(C,z))}else b("error",(E==null?void 0:E.error)||"workspace_set_default failed",!0)}catch(E){b("error",E.message,!0)}finally{g(!1)}}},[e,b,r]),W=l.useCallback(async T=>{var E;if(!e||!T.trim())return;const A=T.trim();g(!0);try{const z=await r(e,"workspace_set_default",{path:A});z!=null&&z.success?(b("info","Default workspace set from history"),(E=C.current)==null||E.call(C,A)):b("error",(z==null?void 0:z.error)||"Could not set default (path missing on disk?)")}catch(z){b("error",z.message)}finally{g(!1)}},[e,b,r]),B=l.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:x}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:x})}catch(T){b("warn",`Live nickname updated, but account sync failed: ${T.message}`)}b("info",`Nickname set to "${x||"(cleared)"}"`),w(!1)}catch(T){b("error",`Failed: ${T.message}`)}},[e,x,t,b,n,r]);return{logs:i,launchingIde:d,launchingAgentType:u,workspaceBusy:h,launchPick:k,setLaunchPick:f,editingNickname:v,setEditingNickname:w,nicknameInput:x,setNicknameInput:j,addLog:b,handleLaunchIde:S,runLaunchCliCore:I,handleLaunchCli:R,handleStopCli:L,handleRestartIde:M,handleStopIde:P,handleDetectIdes:$,handleWorkspaceAdd:Y,handleWorkspaceRemove:_,handleWorkspaceSetDefault:H,handleWorkspaceResumePath:W,handleSaveNickname:B,setOnDefaultWorkspaceChanged:y}}function tC({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(jn,{icon:s.jsx(Jd,{size:16}),label:"Uptime",value:typeof e.uptime=="number"?Rb(e.uptime):"Waiting…"}),s.jsx(jn,{icon:s.jsx(ds,{size:16}),label:"IDEs",value:`${t.length}`}),s.jsx(jn,{icon:s.jsx(Mi,{size:16}),label:"CLIs",value:`${r.length}`}),s.jsx(jn,{icon:s.jsx(Ff,{size:16}),label:"ACPs",value:`${n.length}`})]}),s.jsxs(Ss,{padding:"lg",className:"mb-5",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(El,{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(El,{value:i,max:100,label:"Memory",color:"#3b82f6",detail:a?`${Xa(e.totalMem-o)} / ${Xa(e.totalMem)}${e.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Xa(e.totalMem)} total`})]})]})]})}function sC(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 rC(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 Mo(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 hd(e){if(!e||typeof e!="object")return null;if(Mo(e))return e;const t=e,r=t.result;return Mo(r)?r:Mo(t.sourceConfig)?t.sourceConfig:null}function nC(e){const t=e.trim();return t||null}function aC({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var y;const o=t.filter(b=>b.category==="ide"),[i,c]=l.useState(((y=o[0])==null?void 0:y.type)||""),[d,p]=l.useState(""),[u,m]=l.useState(""),[h,g]=l.useState(!1),[k,f]=l.useState(""),[v,w]=l.useState(!1),x=b=>{const N=b.toLowerCase().replace(/[^a-z0-9-]/g,"");p(N),(!u||u===j(d))&&m(j(N))},j=b=>b.split("-").map(N=>N.charAt(0).toUpperCase()+N.slice(1)).join(" "),C=async()=>{if(!(!d||!u||!i)){g(!0),f("");try{const b=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:i});b!=null&&b.success||b!=null&&b.created?(w(!0),a==null||a(d)):f((b==null?void 0:b.error)||"Failed to create provider")}catch(b){f((b==null?void 0:b.message)||"Connection failed")}g(!1)}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:s.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:b=>b.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[s.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:v?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:d})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",d,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",d]})," or use Auto-Fix to implement scripts."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:o.map(b=>s.jsxs("button",{onClick:()=>c(b.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:i===b.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:i===b.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:b.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:i===b.type?"#a78bfa":"var(--text-secondary)"},children:b.displayName})]},b.type))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),s.jsx("input",{value:d,onChange:b=>x(b.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",d||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),s.jsx("input",{value:u,onChange:b=>m(b.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),k&&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:k})]})}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:v?s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:C,disabled:!d||!u||h,className:"machine-btn",style:{background:d&&u?"rgba(34,197,94,0.12)":void 0,borderColor:d&&u?"rgba(34,197,94,0.3)":void 0,color:d&&u?"#86efac":void 0,opacity:!d||!u||h?.4:1},children:h?"⏳ Creating...":"✨ Create Provider"})]})})]})})}const fd={"user-custom":"Custom",trusted:"Official","trusted-with-scripts":"Official · runs JS","external-safe":"External · spec-only","external-untrusted":"⚠ External · untrusted JS"},oC={"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 iC({trust:e,sourceName:t,description:r}){const n=t&&(e==="external-safe"||e==="external-untrusted")?`${fd[e]} · ${t}`:fd[e];return s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded border whitespace-nowrap ${oC[e]}`,title:r,children:n})}function lC(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 cC={detected:"Detected",not_detected:"Not detected",enabled_unchecked:"Enabled (unchecked)",disabled:"Disabled"},xd={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"},dC={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 bd(e){if(!e)return"—";const t=e.ok?"OK":"Failed",r=e.message||e.path||e.command||"";return r?`${t} — ${r}`:t}function uC(e){return e==="cli"||e==="acp"}function pC({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,u=t==null?void 0:t.machineStatus,m=p&&u==="disabled"?"enabled_unchecked":u||(p?"enabled_unchecked":"disabled"),h=uC(e.category);return s.jsxs(Ss,{padding:"none",children:[s.jsxs("button",{onClick:()=>d(g=>!g),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 ${dC[e.category]??"border-border-subtle text-text-muted"}`,children:e.category.toUpperCase()}),(t==null?void 0:t.trust)&&s.jsx(iC,{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 ${xd[m]??xd.disabled}`,children:cC[m]??m}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[h&&s.jsx("button",{onClick:g=>{g.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 g=t==null?void 0:t.links;if(!g)return null;const k=Object.entries(g).map(([f,v])=>({k:f,href:lC(v)})).filter(f=>f.href!==null);return k.length===0?null:s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Links:"})," ",k.map(({k:f,href:v})=>s.jsx("a",{href:v,target:"_blank",rel:"noopener noreferrer",className:"text-violet-400 hover:underline mr-2",children:f},f))]})})()]}),h&&s.jsxs("div",{className:"grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Detection:"})," ",bd(t==null?void 0:t.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Verification:"})," ",bd(t==null?void 0:t.lastVerification)]})]}),e.schema.length>0&&s.jsx("div",{className:"flex flex-col gap-1.5",children:e.schema.map(g=>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:[g.label||g.key,r===`${e.type}.${g.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving…"})]}),g.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:g.description})]}),s.jsx("div",{className:"shrink-0",children:g.type==="boolean"?s.jsx("button",{onClick:()=>void n(e.type,g.key,!(e.values[g.key]??g.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:e.values[g.key]??g.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[g.key]??g.default?21:3}})}):g.type==="number"?s.jsx("input",{type:"number",value:Number(e.values[g.key]??g.default??0)||0,min:g.min,max:g.max,onChange:k=>{const f=parseInt(k.target.value)||0;g.min!==void 0&&f<g.min||g.max!==void 0&&f>g.max||n(e.type,g.key,f)},className:"machine-input w-20 text-center text-[11px]"}):g.type==="select"&&g.options?s.jsx("select",{value:String(e.values[g.key]??g.default??""),onChange:k=>void n(e.type,g.key,k.target.value),className:"machine-input text-[11px]",children:g.options.map(k=>s.jsx("option",{value:k,children:k},k))}):s.jsx("input",{type:"text",defaultValue:String(e.values[g.key]??g.default??""),onBlur:k=>void n(e.type,g.key,k.target.value),className:"machine-input w-[180px] text-[11px]"})})]},g.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 Fn(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function mC({machineId:e,sendDaemonCommand:t,onChange:r}){const[n,a]=l.useState([]),[o,i]=l.useState([]),[c,d]=l.useState(!1),[p,u]=l.useState(null),[m,h]=l.useState(!1),[g,k]=l.useState(""),[f,v]=l.useState("main"),[w,x]=l.useState(""),[j,C]=l.useState(!1),[y,b]=l.useState(null),[N,S]=l.useState(null),I=l.useCallback(async()=>{if(e){d(!0),u(null);try{const P=Fn(await t(e,"list_provider_sources",{}));if(!(P!=null&&P.success)){u((P==null?void 0:P.error)||"Failed to load sources");return}a(P.sources||[]),i(P.conflicts||[])}catch(P){u((P==null?void 0:P.message)||String(P))}finally{d(!1)}}},[e,t]);l.useEffect(()=>{I()},[I]);const R=async()=>{if(g.trim()){C(!0),u(null);try{const P=Fn(await t(e,"add_provider_source",{url:g.trim(),ref:f.trim()||"main",...w.trim()?{name:w.trim()}:{}}));P!=null&&P.success?(h(!1),k(""),v("main"),x(""),await I(),r==null||r()):u((P==null?void 0:P.error)||"Failed to add source")}catch(P){u((P==null?void 0:P.message)||String(P))}finally{C(!1)}}},L=async P=>{if(confirm(`Remove provider source ${P}? This deletes the cloned manifests and clears any active-source entries that pointed here.`)){b(P),u(null);try{const $=Fn(await t(e,"remove_provider_source",{name:P}));$!=null&&$.success?(await I(),r==null||r()):u(($==null?void 0:$.error)||"Failed to remove source")}catch($){u(($==null?void 0:$.message)||String($))}finally{b(null)}}},M=async(P,$)=>{S(`${P}:${$}`),u(null);try{const Y=Fn(await t(e,"set_active_provider_source",{type:P,sourceName:$}));Y!=null&&Y.success?(await I(),r==null||r()):u((Y==null?void 0:Y.error)||"Failed to set active source")}catch(Y){u((Y==null?void 0:Y.message)||String(Y))}finally{S(null)}};return s.jsxs(Ss,{padding:"none",className:"px-4.5 py-3.5",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(P=>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:P.name}),s.jsxs("div",{className:"text-[10px] text-text-muted truncate",children:[P.url," ",s.jsxs("span",{className:"opacity-60",children:["@ ",P.ref]})]})]}),s.jsx("button",{type:"button",onClick:()=>void L(P.name),disabled:y===P.name,className:"machine-btn text-[10px] text-red-400 hover:bg-red-500/[0.10]",children:y===P.name?"…":"Remove"})]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:Object.entries(P.providers).map(([$,Y])=>s.jsxs("span",{className:"mr-3",children:[s.jsxs("span",{className:"text-text-secondary",children:[$,":"]})," ",Y.length]},$))})]},P.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(P=>s.jsxs("li",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"font-mono text-[11px]",children:[P.type," ",s.jsxs("span",{className:"text-text-muted",children:["(",P.category,")"]})]}),s.jsx("div",{className:"flex gap-1.5 flex-wrap",children:P.candidates.map($=>s.jsxs("button",{type:"button",onClick:()=>void M(P.type,$),disabled:N===`${P.type}:${$}`,className:`text-[10px] px-2 py-0.5 rounded border ${P.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:P.active===$?"Active":`Switch active to ${$}`,children:[P.active===$?"● ":"",$]},$))})]},P.type))})]}),m&&s.jsxs("div",{className:"mt-3 rounded border border-sky-500/30 bg-sky-500/[0.06] px-3 py-3",children:[s.jsx("div",{className:"text-[11px] font-semibold text-sky-300 mb-2",children:"Add external source"}),s.jsxs("div",{className:"grid md:grid-cols-3 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1 text-[10px] text-text-secondary md:col-span-3",children:[s.jsx("span",{children:"Git URL"}),s.jsx("input",{type:"text",value:g,onChange:P=>k(P.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:P=>v(P.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:w,onChange:P=>x(P.target.value),placeholder:"@vendor-extra-providers",className:"machine-input text-[11px] font-mono"})]})]}),s.jsxs("div",{className:"mt-3 flex items-center justify-end gap-2",children:[s.jsx("button",{type:"button",onClick:()=>h(!1),className:"machine-btn text-[10px]",children:"Cancel"}),s.jsx("button",{type:"button",onClick:()=>void R(),disabled:j||!g.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:j?"Cloning…":"Clone + register"})]})]})]})}function hC({machineId:e,providers:t,sendDaemonCommand:r}){var H;const[n,a]=l.useState([]),[o,i]=l.useState(!1),[c,d]=l.useState(null),[p,u]=l.useState("all"),[m,h]=l.useState(!1),[g,k]=l.useState(!1),[f,v]=l.useState(!1),[w,x]=l.useState(null),[j,C]=l.useState("normal"),[y,b]=l.useState(""),[N,S]=l.useState(!1),I=l.useCallback(async()=>{if(e)try{const W=await r(e,"get_provider_source_config",{}),B=hd(W);B&&(x(B),C(B.sourceMode),b(B.explicitProviderDir||""))}catch{}},[e,r]),R=l.useCallback(async()=>{if(e){i(!0);try{const W=await r(e,"get_provider_settings",{}),B=sC(W);if(B){const T=rC(B,t,{filterSchema:A=>A.filter(E=>E.key!=="enabled")});T.sort((A,E)=>A.category.localeCompare(E.category)||A.displayName.localeCompare(E.displayName)),a(T)}}catch{}i(!1)}},[e,t,r]);l.useEffect(()=>{n.length===0&&R(),w||I()},[]);const L=async(W,B,T)=>{d(`${W}.${B}`),a(A=>A.map(E=>E.type===W?{...E,values:{...E.values,[B]:T}}:E));try{const A=await r(e,"set_provider_setting",{providerType:W,key:B,value:T});A!=null&&A.success||R()}catch{R()}d(null)},M=async(W,B)=>{await L(W,"enabled",B),await R()},P=async W=>{d(`${W}.detect`);try{await r(e,"detect_provider",{providerType:W})}finally{await R(),d(null)}},$=async W=>{await L(W,"executablePath",""),await L(W,"executableArgs",""),await R()},Y=async()=>{S(!0);try{const W=await r(e,"set_provider_source_config",{providerSourceMode:j,providerDir:nC(y)}),B=hd(W);B?(x(B),C(B.sourceMode),b(B.explicitProviderDir||"")):await I(),await R()}catch{await I()}S(!1)},_=n.filter(W=>p==="all"||W.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(W=>s.jsx("button",{onClick:()=>u(W),className:`machine-btn text-[10px] px-2 py-0.5 ${p===W?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:W.toUpperCase()},W))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>k(W=>!W),className:`machine-btn text-[10px] ${g?"bg-sky-500/[0.10] border-sky-500/30 text-sky-300":""}`,title:"Manage 3rd-party provider sources",children:"🌐 Sources"}),s.jsx("button",{onClick:()=>h(!0),className:"machine-btn text-[10px]",title:"Create a new provider from an existing one",children:"✨ Create"}),s.jsxs("button",{onClick:R,disabled:o,className:"machine-btn text-[10px]",children:[o?"⏳":"↻"," Refresh"]}),s.jsx("button",{onClick:()=>v(W=>!W),className:"machine-btn text-[10px]",title:"Show source configuration (advanced)",children:"⚙ Advanced"})]})]}),g&&s.jsx(mC,{machineId:e,sendDaemonCommand:r,onChange:()=>{R()}}),f&&s.jsxs(Ss,{padding:"none",className:"px-4.5 py-3.5",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:j,onChange:W=>C(W.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:y,onChange:W=>b(W.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void Y(),disabled:N,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:N?"Applying…":"Apply + Reload"})]}),s.jsxs("div",{className:"mt-3 grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"User root:"})," ",(w==null?void 0:w.userDir)||"—"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Upstream root:"})," ",(w==null?void 0:w.upstreamDir)||"—"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Provider roots:"})," ",((H=w==null?void 0:w.providerRoots)==null?void 0:H.join(" → "))||"—"]})]})]}),o&&n.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings…"}):_.length===0?s.jsx(Ss,{padding:"none",className:"px-4.5 py-8 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:_.map(W=>s.jsx(pC,{prov:W,providerInfo:t.find(B=>B.type===W.type),savingKey:c,onSetSetting:L,onEnableToggle:M,onDetect:P,onResetCommand:$},W.type))}),m&&s.jsx(aC,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>h(!1),onCreated:()=>{h(!1),R()}})]})}const fC=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function xC({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function bC(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function gC(e){return e.trim().toLowerCase()}function Fa(e,t){const r=gC(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function hl(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Sr(e,t=220){const r=hl(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function yC(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 vC(e,t){return e.filter(r=>Fa([r.level,r.message],t))}function gd(e){return`${e.timestamp}:${e.level}:${e.message}`}function wC(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const i of e.entries)n.set(gd(i),i);for(const i of t.entries)n.set(gd(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 jC(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 kC(e,t){return e.split(`
|
|
94
|
+
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>Fa([r],t))}function SC(e,t){return e.filter(r=>Fa([r.level,r.category,r.stage,r.interactionId,hl(r.payload)],t))}function NC(e,t){return e.filter(r=>Fa([r.kind,r.topic,r.interactionId,hl(r.payload)],t))}function yd(e){return e==="warn"||e==="error"}function CC({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=>yd(a.level)).length+r.filter(a=>yd(a.level)).length}}function IC({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(`
|
|
95
|
+
`)):t.length>0&&a.push(["[daemon logs]",...t].join(`
|
|
96
|
+
`)),r.length>0&&a.push(["[trace]",...r.map(o=>`${new Date(o.ts).toISOString()} ${o.level.toUpperCase()} ${o.category}.${o.stage} ${Sr(o.payload,500)}`.trim())].join(`
|
|
97
|
+
`)),n.length>0&&a.push(["[browser events]",...n.map(o=>`${new Date(o.ts).toISOString()} ${o.kind}${o.topic?` topic=${o.topic}`:""} ${Sr(o.payload,500)}`.trim())].join(`
|
|
98
|
+
`)),a.join(`
|
|
99
|
+
|
|
100
|
+
`)}function AC({machineId:e,sendDaemonCommand:t}){const[r,n]=l.useState([]),[a,o]=l.useState("empty"),[i,c]=l.useState(""),[d,p]=l.useState([]),[u,m]=l.useState([]),[h,g]=l.useState(null),[k,f]=l.useState(!0),[v,w]=l.useState("info"),[x,j]=l.useState("all"),[C,y]=l.useState(!0),[b,N]=l.useState(!0),[S,I]=l.useState(""),[R,L]=l.useState(""),[M,P]=l.useState(0),$=l.useRef(0),Y=l.useRef(0),_=l.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),H=l.useRef([]),W=l.useCallback(()=>{const re={entries:[],kind:"empty",rawText:"",lastTs:0};_.current=re,$.current=0,n([]),c(""),o("empty"),y(!0)},[]),B=l.useCallback(()=>{H.current=[],Y.current=0,p([]),N(!0)},[]),T=l.useCallback(re=>{re!==v&&(W(),w(re))},[v,W]),A=l.useCallback(re=>{j(X=>X===re?X:re)},[]),E=l.useCallback(()=>{W(),B(),m([]),g(null),I(""),L(""),fr.clear()},[W,B]),z=l.useCallback(()=>{P(re=>re+1)},[]),G=l.useCallback(async()=>{if(!e)return;const re=$.current,X=Y.current,[te,J]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:v,since:re}),t(e,"get_debug_trace",xC({count:120,since:X,category:x}))]);if(te.status==="fulfilled"){const F=te.value,K=(F==null?void 0:F.result)||F,fe=yC(K),be=wC(_.current,fe,300);_.current=be,$.current=be.lastTs,y(!1),I((F==null?void 0:F.success)===!1?String((F==null?void 0:F.error)||"Could not load daemon logs"):""),o(be.kind),c(be.rawText),n(be.entries)}else y(!1),I(te.reason instanceof Error?te.reason.message:"Could not load daemon logs");if(J.status==="fulfilled"){const F=J.value,K=(F==null?void 0:F.result)||F;if((F==null?void 0:F.success)===!1)L(String((F==null?void 0:F.error)||"Could not load daemon trace"));else if(Array.isArray(K==null?void 0:K.trace)){const fe=K.trace,be=jC(H.current,fe,120),oe=fe.reduce((je,ge)=>Math.max(je,Number(ge.ts||0)),X);H.current=be,oe>X&&(Y.current=oe),L(""),p(be)}else L("");N(!1)}else N(!1),L(J.reason instanceof Error?J.reason.message:"Could not load daemon trace");m(fr.list({limit:120})),g(Date.now())},[v,e,t,x]);return l.useEffect(()=>{B()},[B,x]),l.useEffect(()=>{if(!e||(G(),!k))return;const re=setInterval(()=>{G()},3e3);return()=>clearInterval(re)},[k,G,e,M]),{daemonLogs:r,daemonLogKind:a,daemonRawText:i,debugTrace:d,webEvents:u,lastUpdatedAt:h,autoRefresh:k,logLevel:v,traceCategory:x,daemonLoading:C,traceLoading:b,daemonFetchError:S,traceFetchError:R,setAutoRefresh:f,setLogLevel:T,setTraceCategory:A,refresh:z,clear:E}}function MC({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 vd(e){return e==="warn"||e==="error"}function TC(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 _C(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 wd(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function LC(e){const t=Sr(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function RC(e){const t=Sr(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function PC({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:RC(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:LC(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:_C(o,i),severity:TC(o),message:o,raw:o})}),a.sort((o,i)=>o.ts!==i.ts?o.ts-i.ts:wd(o.source)-wd(i.source))}function DC(e){return`${e.source}:${e.severity}:${e.message}`}function $C(e){const t=e.filter(n=>vd(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!vd(n.severity))continue;const a=DC(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 EC(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function jd(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${EC(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function BC({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
|
|
101
|
+
`)),a.push(["[source status]",...r.map(i=>`${i.label}: ${i.status} - ${i.detail}`)].join(`
|
|
102
|
+
`)),t.latestIssue&&a.push(["[latest issue]",jd(t.latestIssue)].join(`
|
|
103
|
+
`)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.repeatedPatterns.map(i=>`${i.count}x ${i.severity.toUpperCase()} ${i.source} ${i.message}`)].join(`
|
|
104
|
+
`));const o=e.slice(-n);return a.push(["[timeline]",...o.length>0?o.map(jd):["No diagnostic events captured."]].join(`
|
|
105
|
+
`)),a.join(`
|
|
106
|
+
|
|
107
|
+
`)}function FC(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function OC(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function HC({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:i,searchQuery:c,daemonLoading:d,traceLoading:p,daemonFetchError:u,traceFetchError:m}){const h=bC(n,o),g=vC(e,c),k=kC(t,c),f=SC(h,c),v=NC(a,c),w=FC(g,i),x=i==="all"?k:[],j=OC(f,i),C=i==="issues"?[]:v,y=CC({daemonLogs:g,daemonRawLines:k,trace:f,webEvents:v}),b=PC({daemonLogs:w,daemonRawLines:x,trace:j,webEvents:C}),N=$C(b),S=MC({daemonLoading:d,traceLoading:p,daemonFetchError:u,traceFetchError:m,daemonLogKind:r,daemonLogsCount:g.length,daemonRawLineCount:k.length,traceCount:f.length,webEventCount:v.length});return{filteredDaemonLogs:g,filteredDaemonRawLines:k,filteredTraceEntries:f,filteredWebEvents:v,visibleDaemonLogs:w,visibleDaemonRawLines:x,visibleTraceEntries:j,visibleWebEvents:C,quickFilterCounts:y,diagnosticEvents:b,diagnosticsSummary:N,sourceStates:S}}function WC(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Xm(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function bi(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 To(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 fl(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function KC({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${bi(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Xm(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:fl(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 UC({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:i,onCopyVisible:c,onToggleAutoRefresh:d,onRefresh:p,onClear:u}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(m=>s.jsx("button",{type:"button",onClick:()=>a(m.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===m.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:m.label},m.id))}),s.jsx("input",{value:r,onChange:m=>o(m.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:i,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:d,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:p,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function GC({logLevel:e,traceCategory:t,onLogLevelChange:r,onTraceCategoryChange:n}){return s.jsx(Ss,{padding:"sm",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:fC.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 zC({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:i,traceFetchError:c}){var u,m;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((m=e.latestIssue)==null?void 0:m.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 ${To(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 ${To(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:[fl(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:Xm(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 ${To(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: ",WC(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 VC({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()," · ",fl(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function qC({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(u=>({...u,timeline:!u.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(u=>s.jsx(KC,{event:u},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,daemon:!u.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${o.length} visible raw line(s) from file fallback`:`${a.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&a.length===0&&o.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&o.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:d==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&a.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&o.map((u,m)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${m}`)),e.daemonLogKind!=="text"&&a.map((u,m)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${bi(u.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(u.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:u.level==="error"?"ERR":u.level==="warn"?"WRN":u.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:u.message})]},`log-${m}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,trace:!u.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[i.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.traceLoading&&i.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&i.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&i.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children: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(u=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${bi(u.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.level.toUpperCase()}),s.jsxs("span",{children:[u.category,".",u.stage]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Sr(u.payload,360)||"No payload"})]},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,web:!u.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[c.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:p.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),c.map(u=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.kind}),u.topic&&s.jsxs("span",{children:["topic=",u.topic]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Sr(u.payload,360)||"No payload"})]},u.id))]})]})]})}function YC({machineId:e,sendDaemonCommand:t}){const r=AC({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),u=l.useRef(!1),m=l.useMemo(()=>HC({daemonLogs:r.daemonLogs,daemonRawText:r.daemonRawText,daemonLogKind:r.daemonLogKind,debugTrace:r.debugTrace,webEvents:r.webEvents,traceCategory:r.traceCategory,quickFilter:n,searchQuery:o,daemonLoading:r.daemonLoading,traceLoading:r.traceLoading,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),[n,o,r.daemonFetchError,r.daemonLoading,r.daemonLogKind,r.daemonLogs,r.daemonRawText,r.debugTrace,r.traceCategory,r.traceFetchError,r.traceLoading,r.webEvents]);l.useEffect(()=>{if(r.autoRefresh&&m.diagnosticEvents.length>0){const k=u.current?"smooth":"instant";setTimeout(()=>{var f;(f=p.current)==null||f.scrollIntoView({behavior:k}),u.current=!0},50)}},[m.diagnosticEvents.length,r.autoRefresh]);const h=l.useCallback(async()=>{var f;const k=IC({daemonLogs:m.visibleDaemonLogs,daemonRawLines:m.visibleDaemonRawLines,trace:m.visibleTraceEntries,webEvents:m.visibleWebEvents});if(!k.trim()){ut.showToast("No visible logs to copy.","info");return}try{await((f=navigator.clipboard)==null?void 0:f.writeText(k)),ut.showToast("Copied visible logs to clipboard.","success")}catch(v){ut.showToast(v instanceof Error?v.message:"Could not copy visible logs","warning")}},[m.visibleDaemonLogs,m.visibleDaemonRawLines,m.visibleTraceEntries,m.visibleWebEvents]),g=l.useCallback(async()=>{var f;const k=BC({events:m.diagnosticEvents,summary:m.diagnosticsSummary,sources:m.sourceStates});try{await((f=navigator.clipboard)==null?void 0:f.writeText(k)),ut.showToast("Copied diagnostic bundle to clipboard.","success")}catch(v){ut.showToast(v instanceof Error?v.message:"Could not copy diagnostic bundle","warning")}},[m.diagnosticEvents,m.diagnosticsSummary,m.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(UC,{quickFilter:n,quickFilterCounts:m.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:i,onCopyDiagnostics:()=>{g()},onCopyVisible:()=>{h()},onToggleAutoRefresh:()=>r.setAutoRefresh(k=>!k),onRefresh:r.refresh,onClear:r.clear}),s.jsx(GC,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(zC,{diagnosticsSummary:m.diagnosticsSummary,diagnosticEventsCount:m.diagnosticEvents.length,sourceStates:m.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(VC,{patterns:m.diagnosticsSummary.repeatedPatterns}),s.jsx(qC,{streams:r,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:m.diagnosticEvents,visibleDaemonLogs:m.visibleDaemonLogs,visibleDaemonRawLines:m.visibleDaemonRawLines,visibleTraceEntries:m.visibleTraceEntries,visibleWebEvents:m.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:p})]})}function JC(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 Qm(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 XC(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const i=String((o==null?void 0:o.lifecycle)||"").trim(),c=Qm((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 QC(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function _o(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 Lo(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Ro(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function kd(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 ZC(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function e2(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-bg-glass text-text-muted"}}function t2(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 s2({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=l.useState(""),[o,i]=l.useState(null),[c,d]=l.useState(!1),p=fw(e,{enabled:!!e,includeSessions:!0,limit:oc,intervalMs:My}),u=p.diagnostics,m=p.loading,h=p.applyDiagnostics,g=l.useMemo(()=>JC({diagnostics:u,loading:m,refreshing:c,error:n}),[u,m,c,n]),k=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:oc}),M=Lo(L);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Could not load hosted runtime diagnostics");h(M.diagnostics||M.result||null),a("")}catch(L){const M=L instanceof Error?L.message:"Could not load hosted runtime diagnostics";a(M)}finally{d(!1)}}},[h,e,r]);l.useEffect(()=>{!e||u||m||c||f()},[u,m,e,f,c]);const v=l.useCallback(async(L,M)=>{const P=`${L}:${M.sessionId}`;if(!(L==="session_host_stop_session"&&!window.confirm(`Stop ${M.displayName}?
|
|
108
|
+
This will terminate the hosted runtime.`))){i(P);try{const $=await r(e,L,{sessionId:M.sessionId}),Y=Lo($);if(!(Y!=null&&Y.success))throw new Error((Y==null?void 0:Y.error)||"Session host action failed");const _=L==="session_host_resume_session"?"resumed":L==="session_host_restart_session"?"restarted":"stopped";ut.showToast(`Session host ${_}: ${M.displayName}`,"success"),await f()}catch($){const Y=$ instanceof Error?$.message:"Session host action failed";ut.showToast(Y,"warning"),a(Y)}finally{i($=>$===P?null:$)}}},[e,f,r]),w=l.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
109
|
+
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 M=await r(e,"session_host_prune_duplicate_sessions",{}),P=Lo(M);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Duplicate prune failed");const $=P.result||{},Y=Array.isArray($.prunedSessionIds)?$.prunedSessionIds.length:0,_=typeof $.duplicateGroupCount=="number"?$.duplicateGroupCount:0;ut.showToast(`Pruned ${Y} duplicate runtime(s) across ${_} group(s)`,"success"),await f()}catch(M){const P=M instanceof Error?M.message:"Duplicate prune failed";ut.showToast(P,"warning"),a(P)}finally{i(M=>M==="session_host_prune_duplicate_sessions"?null:M)}}},[e,f,r]),x=l.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((L,M)=>(M.lastActivityAt||0)-(L.lastActivityAt||0)),[u==null?void 0:u.sessions]),j=l.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:XC(x),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,x]),C=j.liveRuntimes,y=j.recoverySnapshots,b=j.inactiveRecords,N=l.useMemo(()=>t2(C),[C]),S=l.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),I=l.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(L=>L.level==="warn"||L.level==="error")||null,[u==null?void 0:u.recentLogs]),R=(L,M)=>{var A;const P=o===`session_host_resume_session:${L.sessionId}`,$=o===`session_host_restart_session:${L.sessionId}`,Y=o===`session_host_stop_session:${L.sessionId}`,_=Qm(L.meta),H=k.get(L.sessionId),W=L.attachedClients.length===1?"1 client":`${L.attachedClients.length} clients`,B=M==="recovery"?"Recover":"Resume",T=QC(M);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||(H==null?void 0:H.cliName)||L.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${e2(L.lifecycle)}`,children:L.lifecycle}),_&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:_})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:L.workspaceLabel||(H==null?void 0:H.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:((A=L.writeOwner)==null?void 0:A.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:ZC(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(zd,{size:11})," ",W]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",kd(L.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",T]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[M==="recovery"&&(L.lifecycle==="interrupted"||L.lifecycle==="failed"||L.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{v("session_host_resume_session",L)},children:P?`${B}ing…`:B}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{v("session_host_restart_session",L)},children:$?"Restarting…":"Restart"}),M==="live"&&(L.lifecycle==="running"||L.lifecycle==="starting"||L.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{v("session_host_stop_session",L)},children:Y?"Stopping…":"Stop"})]})]})},L.sessionId)};return s.jsxs(Ss,{padding:"lg",className:"mb-5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(Ts,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:tv()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[N>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{w()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${N})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${g.toneClass}`,children:g.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{f()},disabled:m||c,children:[s.jsx(ka,{size:13}),m||c?"Refreshing…":"Refresh"]})]})]}),n&&!u&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(Ys,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:y.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:kd(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Ro(u.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(Ys,{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:[Ro(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(Mi,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:_o("live")}),C.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:C.map(L=>R(L,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Ts,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:_o("recovery")}),y.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:y.map(L=>R(L,"recovery"))})]}),b.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:_o("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:b.map(L=>R(L,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),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 P;const M=x.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:(M==null?void 0:M.displayName)||((P=k.get(L.sessionId))==null?void 0:P.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:Ro(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:u.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function r2({machine:e,launchPick:t,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] 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 n2(e,t){const r=Kp(e),n=cr(e,t),a=qi(e,n),o=en(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 Po({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 Do({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-border-subtle bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function a2({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:i}){const c=n.slice(0,6),d=r.slice(0,4),u=n2(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(Po,{icon:s.jsx(Zs,{size:13}),children:"Current Chats"}),s.jsx(Do,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(m=>{const h=pi(m);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>i(m),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:xt(m)}),h>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Sa(h)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:yr(m)})]},m.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Po,{icon:s.jsx(Jd,{size:13}),children:"Recent Launches"}),s.jsx(Do,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(m=>{const{metaText:h,updatedLabel:g}=tm(m);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>o(m),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:m.label}),g&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:g})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:h})]},m.id)})})})]}),u.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Po,{icon:s.jsx(Ys,{size:13}),children:"Daemon Update"}),s.jsx(Do,{className:u.tone==="good"?"border-emerald-500/20 bg-emerald-500/5":u.tone==="info"?"border-sky-500/20 bg-sky-500/5":"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u.title}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[u.description,u.targetVersion&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",u.targetVersion,u.channel?` (${u.channel})`:""]})]}),u.showButton?s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[s.jsx(ka,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:u.buttonLabel})]}):s.jsx("div",{className:u.tone==="good"?"text-xs font-medium text-emerald-300":"text-xs font-medium text-sky-300",children:"No preview update action is needed."})]})})]})]})}function o2({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:p,handleWorkspaceSetDefault:u}=o,[m,h]=l.useState(!1),[g,k]=l.useState(""),[f,v]=l.useState([]),[w,x]=l.useState(!1),[j,C]=l.useState(""),y=l.useCallback(async N=>{x(!0),C("");try{const S=await sl(i,e,N);k(S.path),v(S.directories)}catch(S){C(S instanceof Error?S.message:"Could not load folder")}finally{x(!1)}},[e,i]),b=l.useCallback(()=>{h(!0);const N=[...r.map(I=>I.workspace),...n.map(I=>I.workspace),...a.map(I=>I.workspace)],S=tl(t.platform,el(N,t.defaultWorkspacePath,(t.workspaces||[]).map(I=>I.path)));y(S)},[a,n,r,y,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs(Ss,{padding:"lg",className:"mb-4",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(br,{size:14})," Workspaces"]}),s.jsx("button",{type:"button",className:"btn bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary px-3 py-1 rounded transition-colors text-xs",disabled:c,onClick:b,children:"+ Add workspace"})]}),(t.workspaces||[]).length===0?s.jsxs("div",{className:"text-[11px] text-text-muted py-4 text-center",children:["No saved workspaces yet. Click ",s.jsx("span",{className:"text-text-secondary",children:"+ Add workspace"})," to pick a folder."]}):s.jsx("ul",{className:"space-y-1.5 max-h-72 overflow-y-auto",children:(t.workspaces||[]).map(N=>{const S=N.id===t.defaultWorkspaceId;return s.jsxs("li",{className:`flex items-start gap-2 text-[11px] rounded-lg border px-2.5 py-2 transition-colors ${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 u(S?null:N.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:gu(N.path,N.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:N.path,children:N.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void p(N.id),children:"Remove"})]},N.id)})})]}),m&&s.jsx(nl,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:g,directories:f,busy:w,error:j,confirmLabel:"Add workspace",onClose:()=>h(!1),onNavigate:N=>{y(N)},onConfirm:N=>{(async()=>{if(!N)return;await d(N)&&h(!1)})()}})]})}function i2({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-border-subtle 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(o2,{machineId:t,machine:e,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:i})]})}function l2({onNicknameSynced:e}={}){var je,ge,we,me,U,O,Z,V,he,le;const{id:t}=Wh(),r=mn(),n=ji(),{sendCommand:a}=bt(),o=Ar(),i=Lp(),c=rp(),d=c.ides||[],p=c.initialLoaded??!0,u=d.find(D=>D.id===t&&D.type==="adhdev-daemon"),m=d.some(D=>D.type==="adhdev-daemon"),h=t?(je=c.connectionRetryStatuses)==null?void 0:je[t]:void 0,g=!!(h!=null&&h.blocked),[k,f]=l.useState("workspace"),[v,w]=l.useState(null);l.useCallback((D,de)=>{w({daemonId:D,workspace:de})},[]);const[,x]=l.useState("ide"),j=l.useRef(null),[C,y]=l.useState(null),b=l.useRef("__home__"),[N,S]=l.useState("__home__"),[I,R]=l.useState(!1),L=l.useRef(null);l.useEffect(()=>{!t||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||o(t,{minFreshMs:3e4}).catch(()=>{})},[o,u,t]),l.useEffect(()=>{if(!t||!u||k!=="overview")return;const D=u.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(()=>{})},[k,i,u,t]),hw(t&&k==="overview"?[t]:[],{enabled:k==="overview",intervalMs:Cy});const M=()=>{if(m){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},P=eC({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:L});l.useEffect(()=>ut.onToast(de=>{c.setToasts(ue=>{if(ue.some(Ae=>Ae.message===de.message&&de.timestamp-Ae.timestamp<3e3))return ue;const ve={id:de.id,message:de.message,type:de.type,timestamp:de.timestamp,targetKey:de.targetKey,actions:de.actions};return[...ue.slice(-4),ve]});const Se=de.duration||5e3;setTimeout(()=>c.setToasts(ue=>ue.filter(q=>q.id!==de.id)),Se)}),[c]);const $=(u==null?void 0:u.availableProviders)||[],Y={};for(const D of $)Y[D.type]=D.icon;const _=u?{id:u.id,hostname:yu(u,{fallbackId:u.id}),platform:((ge=u.machine)==null?void 0:ge.platform)||"unknown",arch:((we=u.machine)==null?void 0:we.arch)||"",cpus:((me=u.machine)==null?void 0:me.cpus)||0,totalMem:((U=u.machine)==null?void 0:U.totalMem)||0,freeMem:(O=u.machine)==null?void 0:O.freeMem,availableMem:(Z=u.machine)==null?void 0:Z.availableMem,loadavg:(V=u.machine)==null?void 0:V.loadavg,uptime:(he=u.machine)==null?void 0:he.uptime,release:((le=u.machine)==null?void 0:le.release)||"",cdpConnected:!!u.cdpConnected,machineNickname:u.machineNickname||null,p2p:u.p2p?{screenshotActive:!1,...u.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:u.detectedIdes||[],workspaces:u.workspaces||[],defaultWorkspaceId:u.defaultWorkspaceId??u.activeWorkspaceId??null,defaultWorkspacePath:u.defaultWorkspacePath??u.activeWorkspacePath??null}:null,H=d.filter(D=>D.daemonId===t&&D.type!=="adhdev-daemon").filter(D=>!on(D)&&!pr(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:Hb(D.aiAgents||(D.agents||[]).map(de=>({id:de.name,name:de.name,status:de.status,version:de.version}))),activeChat:D.activeChat||null,chats:D.chats||[],childSessions:D.childSessions||[],cdpConnected:D.cdpConnected||!1,daemonId:t,lastMessageAt:D.lastMessageAt})),W=d.filter(D=>D.daemonId===t&&on(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&&pr(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})),T=u?es(u,{fallbackId:t}):"",A="workspace",E=n.state,z=E==null?void 0:E.initialMachineTab,G=E==null?void 0:E.initialWorkspaceCategory;E==null||E.initialWorkspaceId,E==null||E.initialWorkspacePath;const re=z==="ides"||z==="clis"||z==="acps"?"workspace":z||A,X=z==="ides"?"ide":z==="clis"?"cli":z==="acps"?"acp":G,te=[...H.map(D=>{var de;return{id:`ide:${D.type}:${D.workspace||""}`,label:((de=D.activeChat)==null?void 0:de.title)||D.type,kind:"ide",providerType:D.type,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:D.lastMessageAt||0}}),...W.map(D=>{var de;return{id:`cli:${D.type}:${D.workspace||""}`,label:((de=D.activeChat)==null?void 0:de.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 de;return{id:`acp:${D.type}:${D.workspace||""}`,label:((de=D.activeChat)==null?void 0:de.title)||D.acpName,kind:"acp",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:Js(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:D.lastMessageAt||0}})].sort((D,de)=>(de.lastLaunchedAt||0)-(D.lastLaunchedAt||0)),J=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(D=>({id:D.id,label:D.title||D.providerName||D.providerType,kind:D.kind,providerType:D.providerType,providerSessionId:D.providerSessionId,subtitle:Js(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace,summaryMetadata:D.summaryMetadata,lastLaunchedAt:D.lastLaunchedAt})):te,F=l.useMemo(()=>{var de;const D=((de=c.connectionStates)==null?void 0:de[t||""])||void 0;return d.filter(Se=>Se.daemonId===t&&Se.type!=="adhdev-daemon").flatMap(Se=>Vi(Se,{connectionStates:t&&D?{[t]:D}:void 0,defaultConnectionState:D})).filter(Se=>!(Se.transport==="pty"&&Se.mode==="terminal")).sort((Se,ue)=>pi(ue)-pi(Se))},[d,c.connectionStates,t]),K=l.useCallback(D=>{const de=Vp(D);de&&r(dn(de))},[r]),fe=l.useCallback(()=>{j.current&&(R(!0),j.current().finally(()=>{j.current=null,R(!1),y(null)}))},[]),be=l.useCallback(D=>{if(!_)return;const{options:de,selectedKey:Se}=em({machine:_,currentWorkspacePath:D.workspace}),ue=async()=>{x(D.kind),f("workspace")};j.current=async()=>{const q=de.find(Ne=>Ne.key===b.current),ve=(q==null?void 0:q.workspacePath)??null,Ae=(q==null?void 0:q.workspaceId)??null;if(D.kind==="ide"&&D.providerType){await P.handleLaunchIde(D.providerType,ve?{workspace:ve}:void 0);return}if((D.kind==="cli"||D.kind==="acp")&&D.providerType){await P.runLaunchCliCore({cliType:D.providerType,dir:Ae?void 0:ve||"",workspaceId:Ae||void 0,model:D.kind==="acp"&&wu(D.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:D.providerSessionId});return}await ue()},b.current=Se,S(Se),y({title:D.kind==="ide"?da("restart-ide",D.label):D.providerSessionId?fp(D.label):da("start-fresh",D.label),description:D.kind==="ide"?ua("restart-ide"):D.providerSessionId?xp():ua("start-fresh"),confirmLabel:D.kind==="ide"?pa("restart-ide"):D.providerSessionId?ai(!0):pa("start-fresh"),busyLabel:D.kind==="ide"?ma("restart-ide"):D.providerSessionId?hp(!0):ma("start-fresh"),workspaceOptions:de,details:[{label:"Mode",value:D.kind.toUpperCase()},...D.providerType?[{label:"Provider",value:D.providerType}]:[]]})},[P,_]);if(l.useEffect(()=>{f(re)},[A,re,t]),l.useEffect(()=>{X&&x(X)},[X,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:M,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 oe=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ds,{size:14})," Workspace"]}),count:H.length+W.length+B.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ts,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ja,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx($f,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(qd,{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:M,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:[P.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:P.nicknameInput,onChange:D=>P.setNicknameInput(D.target.value),onKeyDown:D=>{D.key==="Enter"&&P.handleSaveNickname(),D.key==="Escape"&&P.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:P.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:()=>P.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:()=>{P.setEditingNickname(!0),P.setNicknameInput(_.machineNickname||"")},title:"Click to set nickname",children:T}),g?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),c.retryConnection&&t&&s.jsx("button",{onClick:()=>c.retryConnection(t),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:"Reconnect"})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[_.platform," · ",_.arch]}),s.jsxs("span",{children:[_.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),_.p2p.available&&s.jsxs("span",{children:["P2P ",_.p2p.state==="connected"?"connected":_.p2p.state]}),_.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:_.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:oe.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 ${k===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 ${k===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:[k==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(a2,{machineEntry:u,providers:$,recentLaunches:J,currentConversations:F,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",Up(u))}catch{}},onOpenRecent:be,onOpenConversation:K}),s.jsx(i2,{machine:_,machineId:t,ideSessions:H,cliSessions:W,acpSessions:B,actions:P,sendDaemonCommand:a})]}),k==="providers"&&s.jsx(hC,{machineId:t,providers:$,sendDaemonCommand:a}),k==="overview"&&s.jsx(tC,{machine:_,ideSessions:H,cliSessions:W,acpSessions:B}),k==="session-host"&&s.jsx(s2,{machineId:t,cliSessions:W,sendDaemonCommand:a}),k==="logs"&&s.jsx(YC,{machineId:t,sendDaemonCommand:a})]})})}),P.launchPick&&_&&s.jsx(r2,{machine:_,launchPick:P.launchPick,actions:P}),C&&s.jsx(Zp,{title:C.title,description:C.description,details:C.details,workspaceOptions:C.workspaceOptions,selectedWorkspaceKey:N,onWorkspaceChange:D=>{b.current=D,S(D)},confirmLabel:C.confirmLabel,busyLabel:C.busyLabel,busy:I,onConfirm:fe,onCancel:()=>{j.current=null,y(null)}}),v&&s.jsx(Jm,{daemonId:v.daemonId,workspace:v.workspace,onClose:()=>w(null)}),s.jsx(gp,{toasts:c.toasts||[],onDismiss:D=>c.setToasts(de=>de.filter(Se=>Se.id!==D)),onClickToast:D=>{D.targetKey&&r(dn(D.targetKey))}}),s.jsx("style",{children:`
|
|
110
|
+
@keyframes toast-in {
|
|
111
|
+
from { opacity: 0; transform: translateX(40px); }
|
|
112
|
+
to { opacity: 1; transform: translateX(0); }
|
|
113
|
+
}
|
|
114
|
+
`})]})}function c2({daemonIds:e,meshId:t,sendData:r,onRevisionAdvance:n}){const a=l.useRef(new Map),o=l.useRef(n);o.current=n;const i=[...new Set(e.filter(Boolean))].sort().join(",");l.useEffect(()=>{a.current=new Map},[i,t]),l.useEffect(()=>{if(!t||!r)return;const c=[...new Set(e.filter(Boolean))];if(c.length===0)return;const d=c.map(p=>is.subscribe({sendData:r},p,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${p}`,params:{includeSessions:!0}},u=>{if(u.topic!=="daemon.metadata")return;const m=u.meshStateRevisions;if(!m)return;const h=m[t]??m["*"];if(typeof h!="number")return;const g=a.current.get(p);a.current.set(p,h),g!==void 0&&h>g&&o.current()}));return()=>{for(const p of d)p()}},[i,t,r])}const d2={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},Zm=l.createContext(null);function u2(){const e=l.useContext(Zm);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function p2({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 m2({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 h2({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 f2({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 x2({status:e}){const r={online:{color:"#22c55e",label:"Online"},dirty:{color:"#f59e0b",label:"Dirty",title:"Workspace has uncommitted changes"},offline:{color:"#6b7280",label:"Offline"},degraded:{color:"#ef4444",label:"Degraded",title:"P2P connection to this node is down or timed out — often transient. Wait and retry, or re-establish the node's connection."},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`},title:r.title,children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:r.color}}),r.label]})}function b2(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function g2({meshes:e,loading:t,error:r,onDismissError:n,daemons:a,features:o,showCreate:i,onToggleCreate:c,createName:d,onCreateNameChange:p,createRepoIdentity:u,onCreateRepoIdentityChange:m,createRepoRemoteUrl:h,onCreateRepoRemoteUrlChange:g,newMeshDaemonId:k,onNewMeshDaemonIdChange:f,newMeshWorkspace:v,onNewMeshWorkspaceChange:w,createPickerWorkspaces:x,onSelectMesh:j,onCreate:C,onCancelCreate:y}){return s.jsxs(bn,{icon:s.jsx(Zt,{}),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(Kt,{variant:"error",onDismiss:n,className:"mb-4",children:r}),i&&s.jsxs(ht,{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:k,onChange:b=>f(b.target.value),disabled:!a.length,children:a.length===0?s.jsx("option",{value:"",children:"No connected daemon"}):a.map(b=>s.jsx("option",{value:b.id,children:b2(b)},b.id))})}),o.createDaemonPicker&&s.jsx(jt,{label:"Workspace",hint:"Choose from workspaces registered by the selected daemon.",children:s.jsx("select",{className:"input w-full",value:v,onChange:b=>w(b.target.value),disabled:!k||!x.length,children:k?x.length===0?s.jsx("option",{value:"",children:"No registered workspaces"}):x.map(b=>s.jsx("option",{value:b.path,children:b.label?`${b.label} · ${b.path}`:b.path},b.id||b.path)):s.jsx("option",{value:"",children:"Select a machine first"})})}),s.jsx(jt,{label:"Name",children:s.jsx(os,{value:d,onChange:b=>p(b.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(jt,{label:"Repo remote URL (optional)",hint:"Provide a remote URL OR a stable identity.",children:s.jsx(os,{value:h,onChange:b=>g(b.target.value),placeholder:"https://github.com/user/repo"})}),s.jsx(jt,{label:"Repo identity (optional)",hint:"Provide a remote URL OR a stable identity.",children:s.jsx(os,{value:u,onChange:b=>m(b.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:C,disabled:!d.trim()||!h.trim()&&!u.trim()||o.createDaemonPicker&&(!k||!v),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:y,children:"Cancel"})]})]}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):e.length===0?s.jsx(Ra,{icon:s.jsx(Zt,{}),title:"No Repo Meshes",description:a.length>0?"Create a mesh to get started.":"Connect an ADHDev daemon first.",action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!a.length,onClick:c,children:"Create First Mesh"})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(b=>{var N;return s.jsx("button",{type:"button",onClick:()=>j(b.id),className:"w-full text-left bg-bg-glass border border-border-subtle rounded-xl px-5 py-4 transition-colors hover:border-border-default hover:bg-bg-secondary/70",children:s.jsxs("div",{className:"flex justify-between items-start",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(Zt,{size:16}),s.jsx("span",{className:"font-bold text-sm",children:b.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:b.repoIdentity||b.repo_identity||"No repo identity"}),(b.defaultBranch||b.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(m2,{size:11}),b.defaultBranch||b.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(b.createdAt||b.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((N=b.nodes)==null?void 0:N.length)??b.nodeCount??0," node(s)"]})]})]})},b.id)})})]})}const y2=["claude-cli","codex-cli","gemini-cli","hermes-cli","antigravity-cli"],v2=[{kind:"rca",labelKey:"meshGraph.magiKind.kindRca",hint:"rca"},{kind:"design",labelKey:"meshGraph.magiKind.kindDesign",hint:"design"},{kind:"claim_audit",labelKey:"meshGraph.magiKind.kindClaimAudit",hint:"claim_audit"},{kind:"freeform",labelKey:"meshGraph.magiKind.kindFreeform",hint:"freeform"}];function w2(){return{nodeId:"",provider:"",model:"",n:""}}function Sd(e){var t;return(t=e.providers)!=null&&t.length?e.providers.filter(Boolean):(e.providerPriority??[]).filter(Boolean)}function j2(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function k2(e){const t=[];for(let r=0;r<e.length;r++){const n=e[r],a=n.provider.trim();if(!a)return{error:{code:"provider_required",slot:r+1}};const o=n.nodeId.trim(),i=n.model.trim(),c=n.n.trim();let d;if(c){const p=Number(c);if(!Number.isFinite(p)||p<1)return{error:{code:"replica_min",slot:r+1}};d=Math.floor(p)}t.push({provider:a,...o?{nodeId:o}:{},...i?{model:i}:{},...d!==void 0?{n:d}:{}})}return t.length===0?{error:{code:"no_slot"}}:{slots:t}}function S2({status:e,daemonId:t,sendDaemonCommand:r,availableProviders:n}){const{t:a}=Pt(),{theme:o}=Ps(),i=l.useMemo(()=>Ds(o),[o]),c=l.useMemo(()=>kp(n),[n]),[d,p]=l.useState({}),[u,m]=l.useState(!1),[h,g]=l.useState(null),[k,f]=l.useState({}),[v,w]=l.useState(null),x=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(T=>({nodeId:T.nodeId,machineLabel:T.machineLabel,providers:T.providers,providerPriority:T.providerPriority})),[e==null?void 0:e.nodes]),j=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(T=>T.nodeId),[e==null?void 0:e.nodes]),C=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map(T=>[T.nodeId,T.machineLabel||T.nodeId])),[e==null?void 0:e.nodes]),y=l.useMemo(()=>{const T={};for(const A of x)T[A.nodeId]=Sd(A);return T},[x]),b=l.useMemo(()=>{const T=[...new Set(x.flatMap(Sd).filter(Boolean))];return[...new Set([...T,...y2])].sort()},[x]),N=!!t&&!!r,S=T=>T&&typeof T=="object"&&"result"in T?T.result:T,I=l.useCallback(async()=>{if(!(!t||!r)){m(!0),g(null);try{const T=await r(t,"magi_kind_panel_list",{}),A=S(T);if((A==null?void 0:A.success)===!1)throw new Error(A.error||a("meshGraph.magiKind.errorLoad"));p(A!=null&&A.kindPanels&&typeof A.kindPanels=="object"?A.kindPanels:{}),f({})}catch(T){g((T==null?void 0:T.message)||a("meshGraph.magiKind.errorLoad"))}finally{m(!1)}}},[t,r,a]);l.useEffect(()=>{I()},[I]);const R=l.useCallback(T=>{if(k[T])return k[T];const A=d[T];return A?A.map(j2):[]},[k,d]),L=(T,A)=>{f(E=>({...E,[T]:A}))},M=(T,A,E)=>{const z=R(T);L(T,z.map((G,re)=>re===A?{...G,...E}:G))},P=T=>{L(T,[...R(T),w2()])},$=(T,A)=>{L(T,R(T).filter((E,z)=>z!==A))},Y=l.useCallback(async T=>{if(!t||!r)return;const A=k2(R(T));if("error"in A){const E=A.error,z=E.code==="provider_required"?a("meshGraph.magiKind.errorSlotProvider",{slot:E.slot}):E.code==="replica_min"?a("meshGraph.magiKind.errorSlotReplica",{slot:E.slot}):a("meshGraph.magiKind.errorNoSlot");g(`${T}: ${z}`);return}w(T),g(null);try{const E=await r(t,"magi_kind_panel_set",{kind:T,slots:A.slots}),z=S(E);if((z==null?void 0:z.success)===!1)throw new Error(z.error||a("meshGraph.magiKind.errorSave"));await I()}catch(E){g((E==null?void 0:E.message)||a("meshGraph.magiKind.errorSave"))}finally{w(null)}},[t,r,R,I,a]),_=l.useCallback(async T=>{if(!(!t||!r)&&confirm(a("meshGraph.magiKind.removeConfirm",{kind:T}))){w(T),g(null);try{const A=await r(t,"magi_kind_panel_remove",{kind:T}),E=S(A);if((E==null?void 0:E.success)===!1)throw new Error(E.error||a("meshGraph.magiKind.errorRemove"));await I()}catch(A){g((A==null?void 0:A.message)||a("meshGraph.magiKind.errorRemove"))}finally{w(null)}}},[t,r,I,a]),H=`w-full rounded-lg border px-2.5 py-1.5 text-xs ${i.isDark?"border-white/10 bg-slate-950/40 text-slate-100 placeholder:text-slate-500":"border-slate-300 bg-white text-slate-900 placeholder:text-slate-400"}`,W="btn btn-primary btn-sm",B="btn btn-secondary btn-sm";return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("p",{className:`text-[12px] ${i.textSecondary}`,children:a("meshGraph.magiKind.intro")}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsx("button",{type:"button",className:B,onClick:()=>void I(),disabled:u||!N,children:a(u?"meshGraph.magiKind.loading":"meshGraph.magiKind.refresh")})})]}),!N&&s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${i.textSecondary} ${i.isDark?"border-white/10":"border-slate-200"}`,children:a("meshGraph.magiKind.connectPrompt")}),h&&s.jsx("div",{className:"rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-[12px] text-rose-300",children:h}),s.jsx("div",{className:"flex flex-col gap-3",children:v2.map(({kind:T,labelKey:A,hint:E})=>{const z=R(T),G=!!d[T],re=v===T;return s.jsxs("div",{className:`${i.cardClass} rounded-2xl p-4 flex flex-col gap-3`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[13px] font-semibold ${i.textPrimary}`,children:a(A)}),s.jsx("span",{className:`font-mono text-[10px] ${i.textMuted}`,children:E}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${G?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:G?a("meshGraph.magiKind.agentCount",{count:d[T].length}):a("meshGraph.magiKind.off")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[z.length===0&&s.jsx("div",{className:`rounded-xl border p-2.5 text-[11px] ${i.textSecondary} ${i.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:a("meshGraph.magiKind.noAgents")}),z.map((X,te)=>{const J=X.nodeId?y[X.nodeId]??[]:[],F=X.nodeId&&J.length?J:b;return s.jsxs("div",{className:`rounded-xl border p-2.5 grid grid-cols-1 sm:grid-cols-[1fr_1fr_1fr_auto_auto] gap-x-2 gap-y-1 items-start ${i.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:a("meshGraph.magiKind.machine")}),s.jsxs("select",{className:H,value:X.nodeId,onChange:K=>M(T,te,{nodeId:K.target.value}),title:a("meshGraph.magiKind.machineTitle"),children:[s.jsx("option",{value:"",children:a("meshGraph.magiKind.anyMachine")}),j.map(K=>s.jsx("option",{value:K,children:C[K]??K},K)),X.nodeId&&!j.includes(X.nodeId)&&s.jsx("option",{value:X.nodeId,children:a("meshGraph.magiKind.offlineSuffix",{label:C[X.nodeId]??X.nodeId})})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsxs("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:[a("meshGraph.magiKind.provider")," *"]}),s.jsxs("select",{className:H,value:X.provider,onChange:K=>M(T,te,{provider:K.target.value}),title:a("meshGraph.magiKind.providerTitle"),children:[s.jsx("option",{value:"",children:a("meshGraph.magiKind.selectProvider")}),F.map(K=>s.jsx("option",{value:K,children:K},K)),X.provider&&!F.includes(X.provider)&&s.jsx("option",{value:X.provider,children:X.provider})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:a("meshGraph.magiKind.model")}),(()=>{var be;const K=(X.provider?(be=c.get(X.provider))==null?void 0:be.models:void 0)??[],fe=!!X.model&&K.length>0&&!K.includes(X.model);return K.length>0&&!fe?s.jsxs("select",{className:H,value:K.includes(X.model)?X.model:"",title:a("meshGraph.magiKind.modelTitle"),onChange:oe=>M(T,te,{model:oe.target.value==="__custom__"?" ":oe.target.value}),children:[s.jsx("option",{value:"",children:a("meshGraph.magiKind.modelDefault")}),K.map(oe=>s.jsx("option",{value:oe,children:oe},oe)),s.jsx("option",{value:"__custom__",children:a("meshGraph.magiKind.modelCustom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:H,value:X.model.trim(),placeholder:a("meshGraph.magiKind.modelDefault"),title:a("meshGraph.magiKind.modelTitle"),onChange:oe=>M(T,te,{model:oe.target.value})}),K.length>0&&s.jsx("button",{type:"button",className:`self-start bg-transparent border-none cursor-pointer p-0 text-[10px] ${i.textSecondary} hover:underline`,onClick:()=>M(T,te,{model:""}),children:a("meshGraph.magiKind.backToModelList")})]})})()]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:a("meshGraph.magiKind.copies")}),s.jsx("input",{className:`${H} sm:w-16`,value:X.n,placeholder:"1",inputMode:"numeric",title:a("meshGraph.magiKind.copiesTitle"),onChange:K=>M(T,te,{n:K.target.value})})]}),s.jsx("button",{type:"button",className:`${B} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>$(T,te),"aria-label":a("meshGraph.magiKind.removeAgent"),title:a("meshGraph.magiKind.removeAgent"),children:"✕"})]},te)}),s.jsx("div",{children:s.jsx("button",{type:"button",className:B,onClick:()=>P(T),disabled:!N,children:a("meshGraph.magiKind.addAgent")})})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:W,onClick:()=>void Y(T),disabled:re||!N,children:a(re?"meshGraph.magiKind.saving":"meshGraph.magiKind.save")}),s.jsx("button",{type:"button",className:B,onClick:()=>void _(T),disabled:re||!N||!G,title:a(G?"meshGraph.magiKind.removeBindingTitle":"meshGraph.magiKind.removeBindingDisabledTitle"),children:a("meshGraph.magiKind.removeBinding")})]})]},T)})})]})}function N2({daemonId:e,meshId:t,cliType:r,sendCommand:n}){const{t:a}=Pt(),[o,i]=l.useState(!1),[c,d]=l.useState(!1),[p,u]=l.useState(null),[m,h]=l.useState(null),[g,k]=l.useState(null),f=l.useCallback(async()=>{if(!e||!t){u(a("repoMesh.promptPreview.connectPrompt"));return}d(!0),u(null);try{const w=await n(e,"coordinator_prompt_preview",{meshId:t,cliType:r}),x=w!=null&&w.result&&typeof w.result=="object"?w.result:w;if(!(x!=null&&x.success)){u((x==null?void 0:x.error)||a("repoMesh.promptPreview.errorRender"));return}h(typeof x.prompt=="string"?x.prompt:""),k(typeof x.bytes=="number"?x.bytes:null)}catch(w){u((w==null?void 0:w.message)||String(w))}finally{d(!1)}},[e,t,r,n,a]),v=l.useCallback(()=>{const w=!o;i(w),w&&m===null&&!c&&f()},[o,m,c,f]);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:v,className:"inline-flex items-center gap-1 text-[12px] text-accent-primary bg-transparent border-none cursor-pointer p-0",children:[s.jsx("span",{className:`transition-transform ${o?"rotate-90":""}`,"aria-hidden":!0,children:"▸"}),a(o?"repoMesh.promptPreview.hide":"repoMesh.promptPreview.view"),s.jsxs("span",{className:"text-text-muted",children:["(",r,")"]})]}),o&&s.jsxs("div",{className:"mt-2",children:[c&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Rendering…"}),p&&s.jsxs("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:[p,s.jsx("button",{type:"button",onClick:()=>void f(),className:"ml-2 underline bg-transparent border-none cursor-pointer text-amber-300",children:"Retry"})]}),!c&&!p&&m!==null&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between text-[11px] text-text-muted",children:[s.jsx("span",{children:"This is what a coordinator session gets when Override is empty."}),g!==null&&s.jsxs("span",{children:[(g/1024).toFixed(1)," KB"]})]}),s.jsx("textarea",{readOnly:!0,value:m,rows:14,className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-secondary font-mono",onFocus:w=>w.currentTarget.select()})]})]})]})}const C2=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function I2(e){const t=C2(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function A2(e){const t=e==null?void 0:e.missions;return Array.isArray(t)?t:[]}function M2(e){return typeof e.goal=="string"&&e.goal?{text:e.goal,truncated:!1}:{text:e.goalPreview??"",truncated:e.goalTruncated===!0}}const T2=["active","paused","completed","abandoned"];function Nd(e){return(e.status||"active").toLowerCase()}const _2=8;function L2({status:e,daemonId:t,meshId:r,sendCommand:n}){const a=l.useMemo(()=>A2(e),[e]),[o,i]=l.useState({}),[c,d]=l.useState({}),[p,u]=l.useState(!1),[m,h]=l.useState(null),[g,k]=l.useState("active"),[f,v]=l.useState(!1),w=l.useMemo(()=>{const S={};for(const I of a){const R=Nd(I);S[R]=(S[R]||0)+1}return S},[a]),x=l.useMemo(()=>g==="all"?a:a.filter(S=>Nd(S)===g),[a,g]),j=f?x:x.slice(0,_2),C=x.length-j.length,y=!!t&&a.length>0,b=l.useCallback(async()=>{if(t){u(!0),h(null);try{const S=await n(t,"mesh_status",{meshId:r,verbose:!0}),I=I2(S),R=Array.isArray(I==null?void 0:I.missions)?I.missions:[],L={};for(const M of R)M.id&&typeof M.goal=="string"&&M.goal&&(L[M.id]=M.goal);i(M=>({...M,...L}))}catch(S){h(S instanceof Error?S.message:"Failed to fetch full mission goals")}finally{u(!1)}}},[t,r,n]),N=l.useCallback(S=>{d(I=>({...I,[S]:!I[S]})),!c[S]&&!o[S]&&b()},[c,o,b]);return a.length===0?null:s.jsxs(ht,{title:"Missions",description:"Active and historical missions reported by the coordinator. Expand a goal to fetch its full text on demand.",children:[m&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400",children:m}),s.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[T2.filter(S=>(w[S]||0)>0).map(S=>s.jsxs("button",{type:"button",onClick:()=>{k(S),v(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] capitalize transition-colors ${g===S?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:[S," ",w[S]]},S)),s.jsxs("button",{type:"button",onClick:()=>{k("all"),v(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] transition-colors ${g==="all"?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:["All ",a.length]})]}),x.length===0&&s.jsxs("div",{className:"text-[12px] text-text-muted",children:["No ",g," missions."]}),s.jsx("div",{className:"flex flex-col gap-2",children:j.map(S=>{var Y;const I=c[S.id]===!0,R=o[S.id],L=M2(S),M=I&&R?R:L.text,P=I&&!R&&L.truncated,$=((Y=S.tasks)==null?void 0:Y.total)??0;return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 px-3 py-2.5",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-text-primary",title:S.title,children:S.title||S.id}),S.status&&s.jsx("span",{className:"shrink-0 rounded-full border border-border-subtle px-2 py-0.5 text-[10px] uppercase tracking-wide text-text-muted",children:S.status}),$>0&&s.jsxs("span",{className:"shrink-0 text-[11px] text-text-muted",children:[$," task",$===1?"":"s"]})]}),M&&s.jsxs("div",{className:`mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-text-secondary ${I?"max-h-72 overflow-y-auto":"line-clamp-2"}`,children:[M,P&&s.jsx("span",{className:"text-text-muted",children:" … (full goal unavailable)"})]}),(L.truncated||R)&&y&&s.jsx("button",{type:"button",className:"mt-1.5 text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:()=>N(S.id),disabled:p,children:I?"Show less":p&&!R?"Loading…":"Show full goal"})]},S.id)})}),C>0&&s.jsxs("button",{type:"button",className:"mt-2 text-[12px] text-accent-primary hover:underline",onClick:()=>v(!0),children:["Show ",C," more"]})]})}const R2=["","low","medium","high"],P2={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function Cd(e){return{provider:e.provider||"",model:e.model||"",thinkingLevel:e.thinkingLevel||"",difficulty:Array.isArray(e.difficulty)?e.difficulty:[],capability:Array.isArray(e.capability)?e.capability:[],maxParallel:e.maxParallel!=null?String(e.maxParallel):""}}function Id(e){const t=e.provider.trim();if(!t)return null;const r=e.model.trim(),n=e.thinkingLevel.trim()||void 0,a=Number(e.maxParallel),o=Number.isFinite(a)&&a>0?Math.floor(a):void 0;return{provider:t,...r?{model:r}:{},...n?{thinkingLevel:n}:{},...e.difficulty.length?{difficulty:e.difficulty}:{},...e.capability.length?{capability:e.capability}:{},...o!==void 0?{maxParallel:o}:{}}}function D2(){return{provider:"",model:"",thinkingLevel:"",difficulty:[],capability:[],maxParallel:""}}const Es="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function $2({slots:e,availableProviders:t,saving:r,onSave:n}){const[a,o]=l.useState(()=>e.map(Cd)),i=l.useMemo(()=>JSON.stringify(e),[e]);l.useEffect(()=>{o(e.map(Cd))},[i]);const c=l.useMemo(()=>[...new Set(t.map(w=>w.type).filter(Boolean))],[t]),d=l.useMemo(()=>kp(t),[t]),p=l.useMemo(()=>{const w=a.map(Id).filter(Boolean);return JSON.stringify(w)!==JSON.stringify(e)},[a,e]),u=(w,x)=>o(j=>j.map((C,y)=>y===w?{...C,...x}:C)),m=(w,x)=>o(j=>j.map((C,y)=>{var S;if(y!==w)return C;const b=((S=d.get(x))==null?void 0:S.models)??[],N=!C.model||b.length===0||b.includes(C.model);return{...C,provider:x,...N?{}:{model:""}}})),h=w=>o(x=>x.filter((j,C)=>C!==w)),g=()=>o(w=>[...w,D2()]),k=(w,x)=>o(j=>{const C=w+x;if(C<0||C>=j.length)return j;const y=[...j];return[y[w],y[C]]=[y[C],y[w]],y}),f=(w,x)=>o(j=>j.map((C,y)=>{if(y!==w)return C;const b=C.difficulty.includes(x);return{...C,difficulty:b?C.difficulty.filter(N=>N!==x):[...C.difficulty,x]}})),v=()=>n(a.map(Id).filter(Boolean));return s.jsxs("div",{className:"flex flex-col gap-2",onClick:w=>w.stopPropagation(),children:[a.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"No capability slots set — that's fine. This node still runs tasks using its provider priority order (below). Slots are optional fine-tuning: add one to route specific task difficulties or capabilities to a specific tool."}),a.map((w,x)=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-2.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[s.jsxs("span",{className:"text-[11px] font-semibold text-text-muted",children:["#",x+1]}),s.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:x===0,onClick:()=>k(x,-1),title:"Move up",children:"↑"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:x===a.length-1,onClick:()=>k(x,1),title:"Move down",children:"↓"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-status-error/30 text-status-error hover:bg-status-error/10",onClick:()=>h(x),"aria-label":`Remove slot ${x+1}`,children:s.jsx(Nt,{size:12})})]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Provider"}),c.length>0?s.jsxs("select",{className:Es,value:w.provider,onChange:j=>m(x,j.target.value),children:[s.jsx("option",{value:"",children:"(select)"}),c.map(j=>s.jsx("option",{value:j,children:j},j)),w.provider&&!c.includes(w.provider)&&s.jsx("option",{value:w.provider,children:w.provider})]}):s.jsx("input",{className:Es,value:w.provider,placeholder:"claude-cli",onChange:j=>u(x,{provider:j.target.value})})]}),(()=>{var N;const j=d.get(w.provider),C=(j==null?void 0:j.models)??[],y=(N=j==null?void 0:j.thinking)!=null&&N.length?["",...j.thinking]:R2,b=!!w.model&&C.length>0&&!C.includes(w.model);return s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Model"}),C.length>0&&!b?s.jsxs("select",{className:Es,value:C.includes(w.model)?w.model:"",onChange:S=>u(x,{model:S.target.value==="__custom__"?" ":S.target.value}),children:[s.jsx("option",{value:"",children:"(provider default)"}),C.map(S=>s.jsx("option",{value:S,children:S},S)),s.jsx("option",{value:"__custom__",children:"Custom…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:Es,value:w.model.trim(),placeholder:w.provider?`${w.provider} model`:"model",onChange:S=>u(x,{model:S.target.value})}),C.length>0&&s.jsx("button",{type:"button",className:"self-start bg-transparent border-none cursor-pointer p-0 text-[10px] text-text-muted hover:underline",onClick:()=>u(x,{model:""}),children:"← Back to model list"})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Thinking"}),s.jsx("select",{className:Es,value:w.thinkingLevel,onChange:S=>u(x,{thinkingLevel:S.target.value}),children:y.map(S=>s.jsx("option",{value:S,children:S||"(default)"},S||"_default"))})]})]})})()]}),s.jsxs("div",{className:"mt-2",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Difficulty (blank = all)"}),s.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:Ab.map(j=>{const C=w.difficulty.includes(j);return s.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${C?"border-accent-primary/60 bg-accent-primary/15 text-accent-primary":"border-border-subtle bg-bg-primary/60 text-text-muted hover:text-text-primary"}`,onClick:()=>f(x,j),children:P2[j]},j)})})]}),s.jsxs("div",{className:"mt-2 grid grid-cols-1 sm:grid-cols-2 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Capability tags (comma-separated)"}),s.jsx("input",{className:Es,value:w.capability.join(", "),placeholder:"worktree, os=darwin",onChange:j=>u(x,{capability:j.target.value.split(",").map(C=>C.trim()).filter(Boolean)})})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Max parallel (per slot)"}),s.jsx("input",{type:"number",inputMode:"numeric",min:1,className:Es,value:w.maxParallel,placeholder:"unlimited",onChange:j=>u(x,{maxParallel:j.target.value})})]})]})]},x)),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1",onClick:g,children:[s.jsx(Ti,{size:13})," Add slot"]}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:v,disabled:!!r||!p,children:r?"Saving…":"Save slots"})]})]})}function E2(e){const t=new Map;for(const r of e)r!=null&&r.id&&t.set(r.id,vr(r.availableProviders||[]));return t}function B2(e,t){const r=String(e.daemon_id||e.daemonId||"");return r&&t.has(r)?t.get(r):!r&&t.size===1?[...t.values()][0]:[]}function F2(e){var d,p,u;const t=e,r=[],n=Array.isArray(t.capabilities)?t.capabilities:[];for(const m of n){const h=typeof m=="string"?m.trim():"";h&&r.push({tag:h,custom:!0})}const a=(((d=t.userOverrides)==null?void 0:d.platform)||t.reportedPlatform||"").toString().trim(),o=(((p=t.userOverrides)==null?void 0:p.arch)||t.reportedArch||"").toString().trim();a&&r.push({tag:`os=${a}`,custom:!1}),o&&r.push({tag:`arch=${o}`,custom:!1});const i=Array.isArray((u=t.policy)==null?void 0:u.providerPriority)?String(t.policy.providerPriority[0]||"").trim():"";i&&r.push({tag:`provider=${i}`,custom:!1});const c=typeof t.worktreeBranch=="string"?t.worktreeBranch.trim():"";return t.isLocalWorktree===!0&&c&&r.push({tag:`worktree=${c}`,custom:!1}),r}function O2(e){const t=e.capabilities;return Array.isArray(t)?t.map(r=>typeof r=="string"?r.trim():"").filter(Boolean):[]}const H2=["os=","arch=","provider=","worktree=","converge="];function W2({node:e,saving:t,onSave:r}){const n=l.useMemo(()=>F2(e).filter(k=>!k.custom),[e]),a=l.useMemo(()=>O2(e),[e]),[o,i]=l.useState(a),[c,d]=l.useState(""),p=JSON.stringify(o)!==JSON.stringify(a),m=(k=>{const f=k.trim();return f?/\s/.test(f)?"Tags cannot contain spaces.":H2.some(v=>f.toLowerCase().startsWith(v))?"That prefix is auto-derived — pick a different tag.":o.includes(f)?"Already added.":null:null})(c);function h(){const k=c.trim();!k||m||(i(f=>[...f,k]),d(""))}function g(k){i(f=>f.filter(v=>v!==k))}return s.jsxs("div",{className:"mt-2",onClick:k=>k.stopPropagation(),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wide text-text-muted mr-1",children:"Routing tags"}),n.map(k=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-1.5 py-0.5 font-mono text-[10px] text-text-muted",title:"Auto-derived — can't be edited",children:k.tag},k.tag)),o.map(k=>s.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 font-mono text-[10px] text-accent-primary",title:"Custom tag",children:[k,s.jsx("button",{type:"button",className:"text-accent-primary/70 hover:text-accent-primary bg-transparent border-none cursor-pointer p-0 leading-none",onClick:()=>g(k),disabled:t,"aria-label":`Remove ${k}`,children:"×"})]},k))]}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"text",value:c,onChange:k=>d(k.target.value),onKeyDown:k=>{k.key==="Enter"&&(k.preventDefault(),h())},placeholder:"add a custom tag (e.g. test-runner)",disabled:t,className:"min-w-[12rem] flex-1 px-2 py-1 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-primary"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:h,disabled:t||!c.trim()||!!m,children:"Add"}),p&&s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>r(o),disabled:t,children:t?"Saving…":"Save tags"})]}),m&&s.jsx("div",{className:"mt-1 text-[11px] text-amber-400",children:m}),o.length===0&&n.length===0&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"No routing tags — tasks can run here without matching any specific capability. Tags are optional."})]})}function K2(e,t){return t.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function U2(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 G2(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 z2(e){const t=G2(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"No provider detected on this node — task launch is blocked until a provider is selected or installed. (Empty capability slots alone do not block launch; this means no provider was found.)"}}function V2(e){return e.isLocalWorktree===!0}function q2(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 Y2(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 J2({nodes:e,meshQueue:t,activeDaemon:r,daemons:n,selectedMeshId:a,userName:o,features:i,coordinatorDaemonId:c,availableCliProviders:d,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:h,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:f,onSaveNodeSystemPrompt:v,selectedNodeId:w,onSelectNode:x,showAddNode:j,onShowAddNode:C,onCancelAddNode:y,nodeWorkspace:b,onNodeWorkspaceChange:N,nodeProviderPriority:S,onNodeProviderPriorityChange:I,nodeDaemonId:R,onNodeDaemonIdChange:L,nodeCustomPath:M,onNodeCustomPathChange:P,nodePickerWorkspaces:$,nodePickerProviders:Y,attachableDaemons:_,onAddNode:H,onRemoveNode:W}){const B=l.useMemo(()=>E2(n),[n]),T=l.useMemo(()=>e.filter(A=>!V2(A)),[e]);return s.jsxs(ht,{title:i.addNodeDaemonPicker?`Nodes & Providers (${T.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:[_.length," available"]})]}),n.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:"No connected machine daemons are currently available."}):_.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:_.map(A=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors ${A.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{L(A.id),N(""),P(!1),I(cn(vr(A.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(A)}),A.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:A.id}),s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted",children:[(A.workspaces||[]).length," workspace(s) detected"]})]},A.id))})]}),!j&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:C,children:[s.jsx(f2,{size:13})," ",i.addNodeDaemonPicker?"Attach machine":"Add node"]}),j&&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:()=>{y(),L(""),P(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(Nt,{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:A=>{var E;L(A.target.value),N(""),P(!1),I(cn(vr(((E=n.find(z=>z.id===A.target.value))==null?void 0:E.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:"Select a machine..."}),n.map(A=>s.jsx("option",{value:A.id,children:Ad(A)},A.id))]})}),(i.addNodeDaemonPicker?R:!0)&&s.jsx(jt,{label:"Workspace Path",children:i.addNodeDaemonPicker&&!M&&$.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:$.map(A=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${b===A.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:()=>N(A.path),children:[s.jsx("span",{className:"font-medium block truncate",children:A.label||A.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:A.path})]},A.id||A.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{P(!0),N("")},children:"Or enter a custom path →"})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(os,{value:b,onChange:A=>N(A.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:A=>{A.key==="Enter"&&H()}}),$.length>0&&s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{P(!1),N("")},children:"← Pick from saved workspaces"})]}):(()=>{var z;const A=Array.isArray(r==null?void 0:r.workspaces)?r.workspaces:[],E=`mesh-add-node-workspaces-${a||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(os,{value:b,onChange:G=>N(G.target.value),placeholder:((z=A[0])==null?void 0:z.path)||"/Users/dev/projects/myapp",list:A.length>0?E:void 0,autoFocus:!0}),A.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:E,children:A.map(G=>s.jsx("option",{value:G.path,children:G.label||G.path},G.id||G.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:A.slice(0,6).map(G=>s.jsx("button",{type:"button",onClick:()=>N(G.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:G.path,children:G.label||G.path.split("/").filter(Boolean).pop()||G.path},G.id||G.path))})]})]})})()})}),s.jsx(jt,{label:"Preferred AI tools (in order)",hint:"Order used when launching without an explicit provider.",children:s.jsx(yv,{value:S,availableProviders:i.addNodeDaemonPicker?Y:d,onChange:I})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:H,disabled:!b.trim()||i.addNodeDaemonPicker&&!R,className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>{y(),L(""),P(!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."}),T.length===0?s.jsx(Ra,{icon:s.jsx(br,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:T.map(A=>{var te;const E=z2(A),z=K2(A,t),G=q2(A,r),re=w===A.id,X=A.status||A.machine_status||(z.length>0||G.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 ${re?"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:()=>x(re?null:A.id),onKeyDown:i.addNodeDaemonPicker?void 0:J=>{(J.key==="Enter"||J.key===" ")&&(J.preventDefault(),x(re?null:A.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:A.machine_label||A.machine_nickname||A.hostname||A.workspace}):s.jsx("span",{className:"text-sm font-medium",children:A.workspace.split("/").pop()}),i.addNodeDaemonPicker&&s.jsx(x2,{status:X}),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: ",Y2(n.find(J=>J.id===String(A.daemon_id||"")),o)," · Machine: ",A.machine_label||A.daemon_id||A.workspace]}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:A.workspace}),s.jsx(W2,{node:A,saving:m===A.id,onSave:J=>h(A,J)}),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",onClick:J=>J.stopPropagation(),children:[s.jsx(jt,{label:"Preferred AI tools (capability slots)",hint:"Each slot = provider + model + thinking + the task difficulty/capability it handles + a per-slot parallel cap. Tasks are matched to the best-fit slot (order = preference). With no slots, this node uses its legacy provider order.",children:s.jsx($2,{slots:Array.isArray((te=A.policy)==null?void 0:te.slots)?A.policy.slots:[],availableProviders:B2(A,B),saving:p===A.id,onSave:J=>u(A,J)})}),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:g[A.id]??"",onChange:J=>{const F=J.target.value;k(A.id,F)},onClick:J=>J.stopPropagation(),disabled:f===A.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:J=>{J.stopPropagation(),v(A)},disabled:f===A.id,children:f===A.id?"Saving…":"Save instruction"})})]})]})]}),s.jsx("button",{className:`transition-colors bg-transparent border-none cursor-pointer ${i.addNodeDaemonPicker?"btn btn-sm text-text-muted hover:text-red-400":"text-text-muted hover:text-red-400"}`,onClick:J=>{J.stopPropagation(),W(A.id)},title:"Remove node",children:s.jsx(h2,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:J=>J.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:A.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",s.jsx("span",{className:E.configured?"text-green-400":"text-amber-400",children:E.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:A.repoRoot||A.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",G.length]}),i.addNodeDaemonPicker&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Added:"})," ",new Date(A.created_at||A.createdAt||Date.now()).toLocaleDateString()]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active queue assignments"}),z.length===0?s.jsx("div",{children:"No active assigned queue task for this node."}):s.jsx("ul",{className:"m-0 pl-4",children:z.map(J=>s.jsx("li",{className:"font-mono",children:U2(J)},J.id))})]}),G.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:G.map(J=>s.jsxs("li",{className:"font-mono",children:[J.provider," / ",J.status," / ",J.id]},J.id))})]})]})]})]},A.id)})})]})}function On(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function X2({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:r,coordinatorCliType:n,onCoordinatorCliTypeChange:a,launchingCoordinator:o,launchResult:i,isHostNodeAttached:c,selectedHostNode:d,hostPinned:p,hostLabel:u,hostOnline:m,hostRebindDaemonId:h,onHostRebindDaemonIdChange:g,onLaunchCoordinator:k}){const f=s.jsx(jt,{label:"Coordinator CLI provider",hint:"Tool launched for the host coordinator session.",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:x=>a(x.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"})]})}),v=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});if(p)return s.jsxs(ht,{title:"Mesh Host daemon",description:"The daemon that owns this mesh's coordinator and live truth (status, queue, graph, node detail). Fixed when the mesh is created — it cannot be reassigned here.",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-[13px] text-text-primary ${m?"border-accent-primary/40 bg-accent-primary/10":"border-amber-500/40 bg-amber-500/10"}`,children:[s.jsx("span",{className:"text-text-muted",children:"Host:"}),s.jsx("span",{className:"font-medium",children:u||"Unknown"}),s.jsxs("span",{className:m?"text-text-muted":"text-amber-400",children:["· ",m?"online":"offline"]})]}),(d==null?void 0:d.workspace)&&s.jsxs("span",{className:"text-[12px] text-text-muted",children:["Host node: ",s.jsx("span",{className:"font-mono text-text-secondary",children:d.workspace})]})]}),!m&&s.jsxs("div",{className:"mt-4",children:[s.jsxs(Kt,{variant:"warning",className:"mb-3",children:[s.jsx("strong",{children:"Host offline."})," ","The pinned host daemon is not connected. Live status/queue/graph will not load until it reconnects. You can temporarily route commands through another connected daemon below — this is a routing fallback, not a host reassignment."]}),e.length>0?s.jsx(jt,{label:"Reconnect to command",hint:"Route commands through this connected daemon until the host is back. Does not change the mesh host.",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:h,onChange:x=>g(x.target.value),children:[s.jsx("option",{value:"",children:"Wait for host to reconnect"}),e.map(x=>s.jsx("option",{value:x.id,children:On(x)},x.id))]})}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:"No connected daemons available to route commands through. Bring the host (or another daemon) online."})]}),s.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-[180px_auto] items-end",children:[f,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:k,disabled:o||!t,title:t?void 0:"No command target available — bring the host or a daemon online.",children:o?"Launching...":"Launch Host Coordinator"})]}),v]});const w=e.find(x=>x.id===t);return s.jsxs(ht,{title:"Mesh Host daemon",description:"This mesh has no host yet. Launching the coordinator on a connected daemon fixes that daemon as the mesh host (a 1:1 pin); it owns live truth thereafter.",children:[s.jsxs(Kt,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:"Set the mesh host."})," ","The host is the daemon that owns this mesh's coordinator and live truth. Launch the host coordinator below to set it — the host is fixed once established."]}),e.length>0?s.jsxs(s.Fragment,{children:[t?s.jsx("div",{className:"mb-3 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:c?s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:On(w)}),d!=null&&d.workspace?s.jsxs(s.Fragment,{children:[" · setup node ",s.jsx("span",{className:"font-mono text-text-secondary",children:d.workspace})]}):null,". Launching sets this daemon as the mesh host."]}):s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:On(w)}),". Attach one of its workspaces as a node first, then launch to set the host."]})}):s.jsx(jt,{label:"Host daemon",hint:"Pick the daemon that will host this mesh. Launching the coordinator on it fixes it as the host.",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:"",onChange:x=>r(x.target.value),children:[s.jsx("option",{value:"",children:"Resolving host… (or pick a daemon to host)"}),e.map(x=>s.jsx("option",{value:x.id,children:On(x)},x.id))]})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-[180px_auto] items-end mt-3",children:[f,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:k,disabled:!t||!c||o,title:t?c?void 0:"Attach a workspace from this daemon as a node first.":"Pick a host daemon (or wait for the host pin to resolve) first.",children:o?"Launching...":"Launch Host Coordinator (sets host)"})]})]}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:"No connected daemons. Bring a daemon online to host this mesh."}),v]})}function Q2({meshId:e,availableCliAgents:t}){const{t:r}=Pt(),n=t.find(o=>{const i=o.id.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||o.name.toLowerCase().includes("hermes")}),a=zp(n==null?void 0:n.meshCoordinator,{meshId:e});return a?s.jsx(ht,{title:r("repoMesh.hermesMcp.title"),description:r("repoMesh.hermesMcp.description"),children:s.jsx(xm,{setup:a,providerName:(n==null?void 0:n.name)||r("repoMesh.hermesMcp.fallbackProvider")})}):null}const $o=[{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."}],Z2=[{value:"smart",label:"Smart",description:"Match each task to the node whose capability slot best fits it (task difficulty + capability tags), then load-spread among ties. Auto-enabled when any node has capability slots."},{value:"spread",label:"Spread",description:"Distribute work evenly across eligible nodes (prefers the least-loaded, rotating ties fairly). Set a per-node priority below to bias the order."},{value:"in_order",label:"In order",description:"Assign to nodes in the order they were added — the first eligible node takes the work. No load-spreading."}];function eI(e){return e==="smart"?"fitness":e==="spread"?"least_loaded":"first_eligible"}function tI(e,t){const r=e||"first_eligible";return r==="fitness"?"smart":r==="first_eligible"?"in_order":r==="priority_only"?t!=null&&t.priorityConfigured?"spread":"in_order":r==="least_loaded"||r==="round_robin"?"spread":"in_order"}const sI={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function gi(e){return{...sI,...(e==null?void 0:e.policy)||{}}}function rI(e){return{routeId:`mesh-settings:${e.meshId}`,daemonId:e.daemonId,agentName:e.meshName,agentType:"mesh",status:"idle",title:e.meshName,messages:[],workspaceName:e.meshName,displayPrimary:e.meshName,displaySecondary:"Mesh observability",streamSource:"native",tabKey:`mesh-settings:${e.meshId}`,coordinator:{meshId:e.meshId,role:"coordinator"},settings:{meshCoordinatorFor:e.meshId}}}function nI({selectedMesh:e,error:t,onDismissError:r,onBack:n,onDelete:a,displayedMeshStatus:o,graphLoading:i,graphError:c,onRefreshGraph:d,savingPolicy:p,onUpdatePolicy:u,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:h,savingCoordinatorPrompt:g,onSaveCoordinatorPrompt:k,daemons:f,coordinatorDaemonId:v,onCoordinatorDaemonIdChange:w,coordinatorCliType:x,onCoordinatorCliTypeChange:j,launchingCoordinator:C,launchResult:y,isHostNodeAttached:b,selectedHostNode:N,hostPinned:S,hostLabel:I,hostOnline:R,hostRebindDaemonId:L,onHostRebindDaemonIdChange:M,onLaunchCoordinator:P,activeDaemon:$,activeDaemonId:Y,meshQueue:_,userName:H,availableCliProviders:W,savingNodeSlotsId:B,onUpdateNodeSlots:T,savingNodeCapabilitiesId:A,onUpdateNodeCapabilities:E,nodeSystemPromptDrafts:z,onNodeSystemPromptDraftChange:G,savingNodeSystemPromptId:re,onSaveNodeSystemPrompt:X,selectedNodeId:te,onSelectNode:J,showAddNode:F,onShowAddNode:K,onCancelAddNode:fe,nodeWorkspace:be,onNodeWorkspaceChange:oe,nodeProviderPriority:je,onNodeProviderPriorityChange:ge,nodeDaemonId:we,onNodeDaemonIdChange:me,nodeCustomPath:U,onNodeCustomPathChange:O,nodePickerWorkspaces:Z,nodePickerProviders:V,attachableDaemons:he,onAddNode:le,onRemoveNode:D,availableCliAgents:de,features:Se,sendCommand:ue}){var qe;const q=gi(e),ve=e.nodes||[],Ae=ve.some(ke=>{var Ie;const ot=Number((Ie=ke.policy)==null?void 0:Ie.schedulingPriority);return Number.isFinite(ot)&&ot!==0}),Ne=!q.schedulingStrategy,Ke=l.useMemo(()=>ve.some(ke=>{var ot;return Array.isArray((ot=ke.policy)==null?void 0:ot.slots)&&ke.policy.slots.length>0}),[ve]),ie=Ne?Ke?"smart":ve.length>=2?"spread":null:null,[Fe,$e]=l.useState(!1),tt=!!Y&&!!e.id;return s.jsxs(bn,{icon:s.jsx(Zt,{}),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:()=>d(!0),disabled:i,children:[s.jsx(p2,{size:13}),i?"Probing…":"Refresh"]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>a(e.id),children:"Delete"})]}),children:[t&&s.jsx(Kt,{variant:"error",onDismiss:r,className:"mb-4",children:t}),Se.meshHostDaemonSection&&s.jsx(X2,{daemons:f,coordinatorDaemonId:v,onCoordinatorDaemonIdChange:w,coordinatorCliType:x,onCoordinatorCliTypeChange:j,launchingCoordinator:C,launchResult:y,isHostNodeAttached:b,selectedHostNode:N,hostPinned:S,hostLabel:I,hostOnline:R,hostRebindDaemonId:L,onHostRebindDaemonIdChange:ke=>{M(ke),d()},onLaunchCoordinator:P}),s.jsxs(ht,{title:"Observability",description:"Open the live mesh graph, overview, and runtime status in the observability dialog.",children:[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}),s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("button",{type:"button",className:"btn btn-primary btn-sm inline-flex items-center gap-1.5",onClick:()=>$e(!0),disabled:!tt,title:tt?"Open the mesh graph / overview / status dialog":"A coordinator daemon must be selected first",children:[s.jsx(Zt,{size:14}),"Open mesh graph & status"]}),s.jsx("span",{className:"text-[12px] text-text-muted",children:"Topology graph, overview cards (missions, ledger, queue, nodes, sessions), and per-node runtime drift."})]})]}),s.jsx(J2,{nodes:ve,meshQueue:_,activeDaemon:$,daemons:f,selectedMeshId:e.id,userName:H,features:{addNodeDaemonPicker:Se.addNodeDaemonPicker,nodeInstruction:Se.nodeInstruction},coordinatorDaemonId:v,availableCliProviders:W,savingNodeSlotsId:B,onUpdateNodeSlots:T,savingNodeCapabilitiesId:A,onUpdateNodeCapabilities:E,nodeSystemPromptDrafts:z,onNodeSystemPromptDraftChange:G,savingNodeSystemPromptId:re,onSaveNodeSystemPrompt:X,selectedNodeId:te,onSelectNode:J,showAddNode:F,onShowAddNode:K,onCancelAddNode:fe,nodeWorkspace:be,onNodeWorkspaceChange:oe,nodeProviderPriority:je,onNodeProviderPriorityChange:ge,nodeDaemonId:we,onNodeDaemonIdChange:me,nodeCustomPath:U,onNodeCustomPathChange:O,nodePickerWorkspaces:Z,nodePickerProviders:V,attachableDaemons:he,onAddNode:le,onRemoveNode:D}),s.jsxs(ht,{title:"Scheduling",description:"How untargeted queue work is distributed across eligible nodes.",children:[s.jsxs("fieldset",{className:"border-none p-0 m-0",children:[s.jsx("legend",{className:"text-[13px] font-medium text-text-secondary mb-2",children:"Distribution"}),s.jsx("div",{className:"flex flex-col gap-2",children:Z2.map(ke=>{const Ie=tI(q.schedulingStrategy,{priorityConfigured:Ae})===ke.value;return s.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${Ie?"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-distribution",className:"mt-0.5 accent-[var(--accent-primary)]",value:ke.value,checked:Ie,disabled:p,onChange:()=>u({schedulingStrategy:eI(ke.value)})}),s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-primary",children:[ke.label,ie===ke.value&&s.jsx("span",{className:"rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-accent-primary",children:"Recommended"})]}),s.jsx("span",{className:"block text-[12px] text-text-muted",children:ke.description})]})]},ke.value)})})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving…"})]}),s.jsx(ht,{title:"Dashboard visibility",description:"Whether the worker sessions this coordinator spawns show up in your dashboard inbox and raise notifications.",children:s.jsx(jt,{label:"Coordinator-spawned worker sessions",hint:"Hidden = keep the inbox quiet and mute their notifications; you interact through the coordinator session. Visible = show every spawned worker as its own conversation.",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:q.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:ke=>u({spawnedSessionVisibility:ke.target.value==="visible"?"visible":"hidden"}),disabled:p,children:[s.jsx("option",{value:"hidden",children:"Hidden (no notifications, keep inbox quiet)"}),s.jsx("option",{value:"visible",children:"Visible (show every worker in the dashboard)"})]})})}),o&&s.jsx(ht,{title:"MAGI review panels",description:"MAGI (Multi-Agent Ground-truth Insight) runs a panel of AI agents that cross-check each other's work to surface the ground truth. Choose which agents handle each review type.",children:s.jsx(S2,{status:o,daemonId:Y,sendDaemonCommand:ue,availableProviders:W})}),s.jsx(L2,{status:o,daemonId:Y,meshId:e.id,sendCommand:ue}),Se.coordinatorPrompt&&s.jsxs(ht,{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. Per-mesh overrides apply to this mesh only; user-level overrides apply to every mesh this daemon coordinates.",children:[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-1",children:"This mesh"}),s.jsxs("p",{className:"text-[12px] text-text-muted mb-3",children:["Applies only to coordinator sessions for ",s.jsx("span",{className:"font-mono text-[11px]",children:e.name}),". Leave empty to fall through to the user-level / daemon default."]}),s.jsxs(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:m.override,onChange:ke=>h({...m,override:ke.target.value}),disabled:g,placeholder:"(empty — daemon default applies)"}),s.jsx(N2,{daemonId:Y,meshId:e.id,cliType:x,sendCommand:ue})]}),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:m.append,onChange:ke=>h({...m,append:ke.target.value}),disabled:g,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:g,children:g?"Saving…":"Save coordinator prompt"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>h({override:"",append:""}),disabled:g,title:"Clear both fields. Click Save to commit.",children:"Clear"})]})]}),s.jsxs("div",{className:"mt-5 border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-1",children:"User-level (this daemon)"}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:"Per-machine prompt files on the coordinator daemon. They apply to every mesh this daemon coordinates and are not synced across daemons. Per-mesh overrides above win over these."}),s.jsx(qv,{daemonId:Y||void 0})]})]}),s.jsxs(ht,{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:ke=>ke?"yes":"no",parse:ke=>ke==="yes"},{label:"Auto-commit a checkpoint after each task",key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:ke=>ke?"yes":"no",parse:ke=>ke==="yes"},{label:"Push approval",key:"requireApprovalForPush",opts:[["required","Require approval before push"],["not_required","Do not require approval"]],val:ke=>ke?"required":"not_required",parse:ke=>ke==="required"},{label:"Destructive git approval",key:"requireApprovalForDestructiveGit",opts:[["required","Require approval"],["not_required","Do not require approval"]],val:ke=>ke?"required":"not_required",parse:ke=>ke==="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:ke=>ke||"warn",parse:ke=>ke},{label:"Auto-publish submodule commits (advanced)",key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled","Require explicit approval"],["enabled","Allow Refinery non-force publish"]],val:ke=>ke?"enabled":"disabled",parse:ke=>ke==="enabled"}].map(({label:ke,key:ot,opts:Ie,val:it,parse:ct})=>s.jsx(jt,{label:ke,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:it(q[ot]),onChange:Ze=>u({[ot]:ct(Ze.target.value)}),disabled:p,children:Ie.map(([Ze,Ot])=>s.jsx("option",{value:Ze,children:Ot},Ze))})},ot))}),(()=>{const ke=q.autoFastForward&&typeof q.autoFastForward=="object"?q.autoFastForward:{},ot=ke.enabled!==!1,Ie=ke.remoteNodes===!0,it=ke.mode==="continuous"?"continuous":"idle",ct=Ze=>u({autoFastForward:{...ke,...Ze}});return s.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[s.jsx(jt,{label:"Auto fast-forward idle nodes",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:ot?"enabled":"disabled",onChange:Ze=>ct({enabled:Ze.target.value==="enabled"}),disabled:p,children:[s.jsx("option",{value:"enabled",children:"Enabled (catch up online, clean, behind nodes)"}),s.jsx("option",{value:"disabled",children:"Disabled"})]})}),s.jsx(jt,{label:"Include remote nodes",hint:"Off = only the coordinator's local workspace is auto fast-forwarded.",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:Ie?"yes":"no",onChange:Ze=>ct({remoteNodes:Ze.target.value==="yes"}),disabled:p||!ot,children:[s.jsx("option",{value:"no",children:"No (local workspace only)"}),s.jsx("option",{value:"yes",children:"Yes (delegate to remote owning daemons)"})]})}),s.jsx(jt,{label:"Detection mode",hint:"Idle = on a node's idle edge. Continuous = also scan periodically (base nodes only).",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:it,onChange:Ze=>ct({mode:Ze.target.value==="continuous"?"continuous":"idle"}),disabled:p||!ot||!Ie,children:[s.jsx("option",{value:"idle",children:"Idle edge only"}),s.jsx("option",{value:"continuous",children:"Continuous (periodic scan)"})]})})]})})(),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:q.sessionCleanupOnNodeRemove||"preserve",onChange:ke=>u({sessionCleanupOnNodeRemove:ke.target.value}),disabled:p,children:$o.map(ke=>s.jsx("option",{value:ke.value,children:ke.label},ke.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((qe=$o.find(ke=>ke.value===q.sessionCleanupOnNodeRemove))==null?void 0:qe.description)||$o[0].description})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving…"})]}),Se.hermesMcpConfig&&s.jsx(Q2,{meshId:e.id,availableCliAgents:de}),Se.meshHostDaemonSection&&s.jsxs(Kt,{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."]}),Fe&&tt&&s.jsx(qm,{activeConv:rI({meshId:e.id,daemonId:Y,meshName:e.name}),sendDaemonCommand:ue,onClose:()=>$e(!1)})]})}const Wr=new Map;function aI({daemons:e,primaryDaemonId:t,sendCommand:r,unwrapResult:n,normalizeMesh:a,features:o,loadDaemonMetadata:i}){const c=e.map(T=>T.id).filter(Boolean).sort().join(","),[d,p]=l.useState(()=>Wr.get(c)??[]),[u,m]=l.useState(null),[h,g]=l.useState(()=>!Wr.has(c)),[k,f]=l.useState(null),[v,w]=l.useState(!1),[x,j]=l.useState(""),[C,y]=l.useState(""),[b,N]=l.useState(""),[S,I]=l.useState(""),[R,L]=l.useState(""),M=l.useMemo(()=>e.find(T=>T.id===S),[e,S]),P=(M==null?void 0:M.workspaces)||[],$=l.useMemo(()=>vr((M==null?void 0:M.availableProviders)||[]),[M]);l.useEffect(()=>{!o.createDaemonPicker||!i||!S||!M||!(!M.workspaces||!M.availableProviders)||Promise.resolve(i(S,{minFreshMs:3e4})).catch(()=>{})},[o.createDaemonPicker,i,S,M]);const Y=l.useMemo(()=>e.map(T=>T.id).filter(Boolean).sort().join(","),[e]),_=l.useCallback(async(T=!1)=>{const A=T||Wr.has(Y);g(E=>A?E:!0);try{if(o.createDaemonPicker){const E=await Promise.allSettled(e.map(async re=>{if(!re.id)return[];const X=await r(re.id,"list_meshes",{}),te=n(X);if((te==null?void 0:te.success)===!1)throw new Error(te.error||"Failed to load meshes");return(Array.isArray(te==null?void 0:te.meshes)?te.meshes:[]).map(J=>a(J,re.id)).filter(J=>J.id)})),z=new Map;for(const re of E)if(re.status==="fulfilled")for(const X of re.value)z.has(X.id)||z.set(X.id,X);const G=Array.from(z.values());p(G),Wr.set(Y,G),f(null)}else{if(!t)return;const E=await r(t,"list_meshes");if(E!=null&&E.success){const z=(E.meshes||[]).map(G=>a(G,t));p(z),Wr.set(Y,z),f(null)}else f((E==null?void 0:E.error)||"Failed to load meshes")}}catch(E){f((E==null?void 0:E.message)||"Failed to load meshes")}finally{g(!1)}},[Y,t,r,n,a,o.createDaemonPicker]);async function H(){var z,G;const T=o.createDaemonPicker?S:t;if(!T||!x.trim())return;const A=b.trim(),E=C.trim();if(!(!A&&!E))try{const re={name:x.trim()};A&&(re.repoRemoteUrl=A),E&&(re.repoIdentity=E);const X=await r(T,"create_mesh",re),te=n(X);if((te==null?void 0:te.success)===!1)throw new Error(te.error||"Create failed");const J=typeof((z=te==null?void 0:te.mesh)==null?void 0:z.id)=="string"?te.mesh.id:"";if(J&&o.createDaemonPicker&&R){const F=await r(T,"add_mesh_node",{meshId:J,daemonId:T,machineId:M==null?void 0:M.machineId,workspace:R,role:"host",providerPriority:cn($)}),K=n(F);if((K==null?void 0:K.success)===!1)throw new Error(K.error||"Mesh created but failed to attach workspace")}w(!1),j(""),y(""),N(""),L(""),await _(),(G=te==null?void 0:te.mesh)!=null&&G.id&&m(te.mesh.id)}catch(re){f((re==null?void 0:re.message)||"Create failed")}}async function W(T){var E;if(!confirm("Delete this mesh? This cannot be undone."))return;const A=((E=d.find(z=>z.id===T))==null?void 0:E.__sourceDaemonId)||t;try{const z=await r(A,"delete_mesh",{meshId:T}),G=n(z);if((G==null?void 0:G.success)===!1)throw new Error(G.error||"Failed to delete");u===T&&m(null),await _()}catch(z){f((z==null?void 0:z.message)||"Delete failed")}}function B(){w(!1),j(""),y(""),N("")}return{meshes:d,setMeshes:p,selectedMeshId:u,setSelectedMeshId:m,loading:h,error:k,setError:f,showCreate:v,setShowCreate:w,createName:x,setCreateName:j,createRepoIdentity:C,setCreateRepoIdentity:y,createRepoRemoteUrl:b,setCreateRepoRemoteUrl:N,newMeshDaemonId:S,setNewMeshDaemonId:I,newMeshWorkspace:R,setNewMeshWorkspace:L,createPickerWorkspaces:P,createPickerProviders:$,loadMeshes:_,handleCreate:H,handleDelete:W,cancelCreate:B}}function oI({selectedMesh:e,selectedMeshId:t,primaryDaemonId:r,activeDaemonId:n,daemons:a,sendCommand:o,unwrapResult:i,loadLiveMesh:c,resolveCommandTarget:d,launchCoordinator:p,features:u,loadMeshes:m,loadQueue:h,queueSection:g,setError:k}){const[f,v]=l.useState({}),[w,x]=l.useState(null),[j,C]=l.useState(null),[y,b]=l.useState(!1),[N,S]=l.useState(""),[I,R]=l.useState([]),[L,M]=l.useState(""),[P,$]=l.useState(!1),[Y,_]=l.useState(""),[H,W]=l.useState(!1),[B,T]=l.useState(null),[A,E]=l.useState(!1),[z,G]=l.useState({override:"",append:""}),[re,X]=l.useState(!1),[te,J]=l.useState({}),[F,K]=l.useState(null),fe=l.useMemo(()=>a.find(ue=>ue.id===L),[a,L]),be=(fe==null?void 0:fe.workspaces)||[],oe=l.useMemo(()=>vr((fe==null?void 0:fe.availableProviders)||[]),[fe]);async function je(){const ue=(e==null?void 0:e.__sourceDaemonId)||r;if(!t||!ue)return;const q=N.trim();if(q)try{const ve={meshId:t,workspace:q};u.addNodeDaemonPicker&&L&&(ve.daemonId=L,ve.machineId=fe==null?void 0:fe.machineId),ve.providerPriority=wr(I);const Ae=await o(ue,"add_mesh_node",ve),Ne=i(Ae);if((Ne==null?void 0:Ne.success)===!1)throw new Error(Ne.error||"Add node failed");b(!1),S(""),R([]),M(""),$(!1),await m(),g||await h(t)}catch(ve){k((ve==null?void 0:ve.message)||"Add node failed")}}async function ge(ue){var Ne;if(!e)return;const q=gi(e),ve=((Ne=[{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(Ke=>Ke.value===q.sessionCleanupOnNodeRemove))==null?void 0:Ne.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
|
|
115
|
+
|
|
116
|
+
Node removal cleanup policy: ${ve}`))return;const Ae=e.__sourceDaemonId||r;try{const Ke=await o(Ae,"remove_mesh_node",{meshId:e.id,nodeId:ue}),ie=i(Ke);if((ie==null?void 0:ie.success)===!1)throw new Error(ie.error||"Remove failed");j===ue&&C(null),await m(),g||await h(t)}catch(Ke){k((Ke==null?void 0:Ke.message)||"Remove node failed")}}async function we(ue){if(!e)return;const q={...gi(e),...ue},ve=e.__sourceDaemonId||r;try{E(!0),k(null);const Ae=await o(ve,"update_mesh",{meshId:e.id,policy:q}),Ne=i(Ae);if((Ne==null?void 0:Ne.success)===!1)throw new Error(Ne.error||"Policy update failed");await m()}catch(Ae){k((Ae==null?void 0:Ae.message)||"Policy update failed")}finally{E(!1)}}async function me(ue){if(!t)return;const q=(e==null?void 0:e.__sourceDaemonId)||r,ve=f[ue.id]||iI(ue),Ae=wr(ve),Ne={...ue.policy||{}};delete Ne.provider_priority,Ae.length?Ne.providerPriority=Ae:delete Ne.providerPriority;try{x(ue.id),k(null);const Ke=await o(q,"update_mesh_node",{meshId:t,nodeId:ue.id,policy:Ne,providerPriority:Ae}),ie=i(Ke);if((ie==null?void 0:ie.success)===!1){k(ie.error||"Node policy update failed");return}await m()}catch(Ke){k((Ke==null?void 0:Ke.message)||"Node policy update failed")}finally{x(null)}}const[U,O]=l.useState(null);async function Z(ue,q){if(!t)return;const ve=(e==null?void 0:e.__sourceDaemonId)||r;try{O(ue.id),k(null);const Ae=await o(ve,"update_mesh_node",{meshId:t,nodeId:ue.id,policy:{slots:q}}),Ne=i(Ae);if((Ne==null?void 0:Ne.success)===!1){k(Ne.error||"Node slots update failed");return}await m()}catch(Ae){k((Ae==null?void 0:Ae.message)||"Node slots update failed")}finally{O(null)}}const[V,he]=l.useState(null);async function le(ue,q){if(!t)return;const ve=(e==null?void 0:e.__sourceDaemonId)||r,Ae=q.map(Ne=>Ne.trim()).filter(Boolean);try{he(ue.id),k(null);const Ne=await o(ve,"update_mesh_node",{meshId:t,nodeId:ue.id,capabilities:Ae}),Ke=i(Ne);if((Ke==null?void 0:Ke.success)===!1){k(Ke.error||"Node tag update failed");return}await m()}catch(Ne){k((Ne==null?void 0:Ne.message)||"Node tag update failed")}finally{he(null)}}async function D(){if(!r||!t)return;const q={...(e==null?void 0:e.coordinator)||{}};z.override.trim()?q.systemPromptOverride=z.override:delete q.systemPromptOverride,z.append.trim()?q.systemPromptAppend=z.append:delete q.systemPromptAppend,delete q.systemPromptSuffix;try{X(!0),k(null);const ve=await o(r,"update_mesh",{meshId:t,coordinator:q}),Ae=i(ve);if((Ae==null?void 0:Ae.success)===!1){k(Ae.error||"Coordinator prompt save failed");return}await m()}catch(ve){k((ve==null?void 0:ve.message)||"Coordinator prompt save failed")}finally{X(!1)}}async function de(ue){if(!r||!t)return;const q=(te[ue.id]||"").trim();try{K(ue.id),k(null);const ve=await o(r,"update_mesh_node",{meshId:t,nodeId:ue.id,systemPrompt:q}),Ae=i(ve);if((Ae==null?void 0:Ae.success)===!1){k(Ae.error||"Node instruction save failed");return}await m()}catch(ve){k((ve==null?void 0:ve.message)||"Node instruction save failed")}finally{K(null)}}async function Se(){if(e){k(null),T(null);try{W(!0);const ue=c?await c(n,e.id,e):null,q=d(n,e.id,e,e.nodes||[],ue);if("error"in q)throw new Error(q.error);const ve=await p(q.targetDaemonId,{meshId:e.id,inlineMesh:q.inlineMesh,coordinatorNodeId:q.coordinatorNodeId,cliType:Y.trim()||void 0});T(ve.message)}catch(ue){k((ue==null?void 0:ue.message)||"Coordinator launch failed")}finally{W(!1)}}}return{nodeProviderPriorityDrafts:f,setNodeProviderPriorityDrafts:v,savingNodePolicyId:w,selectedNodeId:j,setSelectedNodeId:C,showAddNode:y,setShowAddNode:b,nodeWorkspace:N,setNodeWorkspace:S,nodeProviderPriority:I,setNodeProviderPriority:R,nodeDaemonId:L,setNodeDaemonId:M,nodeCustomPath:P,setNodeCustomPath:$,nodePickerWorkspaces:be,nodePickerProviders:oe,coordinatorCliType:Y,setCoordinatorCliType:_,launchingCoordinator:H,launchResult:B,savingPolicy:A,coordinatorPromptDraft:z,setCoordinatorPromptDraft:G,savingCoordinatorPrompt:re,nodeSystemPromptDrafts:te,setNodeSystemPromptDrafts:J,savingNodeSystemPromptId:F,savingNodeSlotsId:U,savingNodeCapabilitiesId:V,handleAddNode:je,handleRemoveNode:ge,handleUpdatePolicy:we,handleUpdateNodeProviderPriority:me,handleUpdateNodeSlots:Z,handleUpdateNodeCapabilities:le,handleSaveCoordinatorPrompt:D,handleSaveNodeSystemPrompt:de,handleLaunchCoordinator:Se}}function iI(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 lI(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 cI({primaryDaemonId:e,activeDaemonId:t,sendCommand:r,unwrapResult:n,loadLiveMesh:a,resolveCommandTarget:o}){const[i,c]=l.useState([]),[d,p]=l.useState(null),[u,m]=l.useState(!1),[h,g]=l.useState(null),k=l.useCallback(async v=>{if(!e||!v){c([]);return}try{const w=await r(e,"get_mesh_queue",{meshId:v});c(w!=null&&w.success?Array.isArray(w.queue)?w.queue:[]:[])}catch{c([])}},[e,r]);async function f(v){var w,x;if(v){m(!0),g(null);try{const j=a?await a(t,v.id,v):null,C=o(t,v.id,v,v.nodes||[],j);if("error"in C)throw new Error(C.error);const y=await r(C.targetDaemonId,"get_mesh_queue",{meshId:v.id}),b=n(y);if((b==null?void 0:b.success)===!1)throw new Error(b.error||"Queue load failed");const N=Array.isArray(((w=b==null?void 0:b.result)==null?void 0:w.rows)??(b==null?void 0:b.rows)??(b==null?void 0:b.queue))?((x=b==null?void 0:b.result)==null?void 0:x.rows)??(b==null?void 0:b.rows)??(b==null?void 0:b.queue):[];p(lI(N))}catch(j){g((j==null?void 0:j.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:d,queueLoading:u,queueError:h,loadQueue:k,handleLoadQueue:f}}function dI(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const eh=new Map;function th(e){return e?eh.get(e)??null:null}function uI(e,t){!e||!t||eh.set(e,t)}function pI({selectedMeshId:e,loadMeshStatus:t,extractStatus:r,normalizeNode:n,gateIncompleteGraph:a}){const[o,i]=l.useState(()=>th(e)),[c,d]=l.useState(!1),[p,u]=l.useState(null),[m,h]=l.useState("idle"),[g,k]=l.useState(!1),f=l.useRef(!1);async function v(w,x=e,j=!1){if(!(!w||!x))try{d(!j&&o===null),h(j?"settling":"first_paint"),u(null);const C=await t(w,x,{refresh:j,retryProfile:j?"settled":"interactive"});k(dI(C));const y=r(C),b=n&&y?{...y,nodes:(y.nodes??[]).map(N=>n(N,y.meshId??x,""))}:y;if(b){if(a&&!j&&o!==null&&!M1(_m(b))){h("settling"),f.current||(f.current=!0,Promise.resolve().then(()=>v(w,x,!0)).finally(()=>{f.current=!1}));return}i(b),uI(x,b),h("settled")}else i(null),u("mesh_status returned an unexpected payload."),h("idle")}catch(C){o||i(null),u((C==null?void 0:C.message)||"Failed to load mesh graph"),h("idle")}finally{d(!1)}}return{meshGraphStatus:o,setMeshGraphStatus:i,graphLoading:c,graphError:p,setGraphError:u,graphProvenance:m,graphBootstrapFallback:g,loadGraph:v}}function mI(e,t,r,n,a){if(!e.length)return"";const o=String(a||"");if(o){const d=e.find(p=>Hs(p.id,o));return d?d.id:o}const i=t.find(d=>d.role==="host"),c=String((i==null?void 0:i.daemon_id)||(i==null?void 0:i.daemonId)||"");if(c){const d=e.find(p=>Hs(p.id,c));if(d)return d.id}return""}const hI=7e3,fI=45e3;function xI(){const e=u2(),{sendCommand:t,sendData:r,daemons:n,userName:a,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:d,unwrapResult:p,normalizeMesh:u,normalizeNode:m,resolveCommandTarget:h,features:g,gateIncompleteGraph:k}=e,f=Ar(),v=n[0],w=(v==null?void 0:v.id)||"",x=l.useMemo(()=>((v==null?void 0:v.availableProviders)||[]).filter(nt=>nt.category==="cli").map(nt=>({id:nt.type||nt.id,name:nt.displayName||nt.name||nt.type,meshCoordinator:nt.meshCoordinator})),[v]),j=l.useMemo(()=>vr((v==null?void 0:v.availableProviders)||[]),[v]),{meshes:C,selectedMeshId:y,setSelectedMeshId:b,loading:N,error:S,setError:I,showCreate:R,setShowCreate:L,createName:M,setCreateName:P,createRepoIdentity:$,setCreateRepoIdentity:Y,createRepoRemoteUrl:_,setCreateRepoRemoteUrl:H,newMeshDaemonId:W,setNewMeshDaemonId:B,newMeshWorkspace:T,setNewMeshWorkspace:A,createPickerWorkspaces:E,loadMeshes:z,handleCreate:G,handleDelete:re,cancelCreate:X}=aI({daemons:n,primaryDaemonId:w,sendCommand:t,unwrapResult:p,normalizeMesh:u,features:g,loadDaemonMetadata:f}),te=C.find(Re=>Re.id===y)||null,{meshGraphStatus:J,setMeshGraphStatus:F,graphLoading:K,graphError:fe,setGraphError:be,loadGraph:oe}=pI({selectedMeshId:y,loadMeshStatus:o,extractStatus:d,normalizeNode:m,gateIncompleteGraph:k}),[je,ge]=l.useState(""),[we,me]=l.useState(""),U=g.meshHostDaemonSection&&je||w,{meshQueue:O,loadQueue:Z}=cI({primaryDaemonId:w,activeDaemonId:U,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:h}),{setNodeProviderPriorityDrafts:V,selectedNodeId:he,setSelectedNodeId:le,showAddNode:D,setShowAddNode:de,nodeWorkspace:Se,setNodeWorkspace:ue,nodeProviderPriority:q,setNodeProviderPriority:ve,nodeDaemonId:Ae,setNodeDaemonId:Ne,nodeCustomPath:Ke,setNodeCustomPath:ie,nodePickerWorkspaces:Fe,nodePickerProviders:$e,coordinatorCliType:tt,setCoordinatorCliType:qe,launchingCoordinator:ke,launchResult:ot,savingPolicy:Ie,coordinatorPromptDraft:it,setCoordinatorPromptDraft:ct,savingCoordinatorPrompt:Ze,nodeSystemPromptDrafts:Ot,setNodeSystemPromptDrafts:Q,savingNodeSystemPromptId:ee,savingNodeSlotsId:ae,savingNodeCapabilitiesId:pe,handleAddNode:xe,handleRemoveNode:Me,handleUpdatePolicy:Le,handleUpdateNodeSlots:Ce,handleUpdateNodeCapabilities:Ee,handleSaveCoordinatorPrompt:Ge,handleSaveNodeSystemPrompt:Xe,handleLaunchCoordinator:De}=oI({selectedMesh:te,selectedMeshId:y,primaryDaemonId:w,activeDaemonId:U,daemons:n,availableCliProviders:j,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:h,launchCoordinator:i,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:z,loadQueue:Z,queueSection:g.queueSection,setError:I}),Oe=l.useMemo(()=>n.find(Re=>Re.id===U)||v,[n,U,v]),ne=l.useMemo(()=>new Set(((te==null?void 0:te.nodes)||[]).map(Re=>String(Re.daemon_id||Re.daemonId||""))),[te]),ce=l.useMemo(()=>n.filter(Re=>Re.id&&!ne.has(Re.id)),[n,ne]),ye=(te==null?void 0:te.nodes)||[],Be=l.useMemo(()=>ye.find(Re=>Hs(String(Re.daemon_id||Re.daemonId||""),je)),[ye,je]),Ue=g.meshHostDaemonSection?!!Be:!0,Qe=l.useMemo(()=>{if(!g.meshHostDaemonSection||!te)return{pinned:!1,daemonId:"",label:"",online:!1};const Re=te.meshHost,nt=J!=null&&J.meshId&&String(J.meshId)===String(te.id??"")?J.meshHost:void 0,kt=nt!=null&&nt.hostDaemonId?nt:Re??nt,Ht=String((kt==null?void 0:kt.hostDaemonId)||""),se=ye.find(vs=>vs.role==="host"),He=String((kt==null?void 0:kt.hostNodeId)||(se==null?void 0:se.id)||""),Pe=He?ye.find(vs=>String(vs.id)===He):void 0,gt=String((Pe==null?void 0:Pe.daemon_id)||(Pe==null?void 0:Pe.daemonId)||""),Yt=Ht||gt;if(!Yt)return{pinned:!1,daemonId:"",label:"",online:!1};const Mr=n.find(vs=>Ht&&Hs(vs.id,Ht))||(gt?n.find(vs=>Hs(vs.id,gt)):void 0);if(Mr)return{pinned:!0,daemonId:Mr.id,label:bI(Mr),online:!0};const Ha=String((Pe==null?void 0:Pe.machineLabel)||"")||String((Pe==null?void 0:Pe.workspace)||"")||Yt;return{pinned:!0,daemonId:Yt,label:Ha,online:!1}},[te,ye,n,J,g.meshHostDaemonSection]),et=Qe.daemonId,Ye=Qe.online,Ve=l.useMemo(()=>!g.meshHostDaemonSection||!Qe.pinned?"":!Ye&&we&&n.some(Re=>Re.id===we)?we:et,[g.meshHostDaemonSection,Qe.pinned,Ye,we,n,et]),Ct=l.useMemo(()=>J?[...new Set((J.nodes??[]).map(Re=>String(Re.daemonId||Re.daemon_id||"")).filter(Boolean))]:[],[J]),us=Vm({status:J,daemonId:U||null,extraDaemonIds:Ct,meshId:y,sendData:r});l.useEffect(()=>{V(Object.fromEntries(((te==null?void 0:te.nodes)||[]).map(Re=>[Re.id,gI(Re)])))},[te]),l.useEffect(()=>{const Re=(te==null?void 0:te.coordinator)||{};ct({override:typeof Re.systemPromptOverride=="string"?Re.systemPromptOverride:"",append:typeof Re.systemPromptAppend=="string"?Re.systemPromptAppend:typeof Re.systemPromptSuffix=="string"?Re.systemPromptSuffix:""}),Q(Object.fromEntries(((te==null?void 0:te.nodes)||[]).map(nt=>[nt.id,typeof nt.systemPrompt=="string"?nt.systemPrompt:""])))},[te]),l.useEffect(()=>{const Re=g.addNodeDaemonPicker?cn($e):cn(j);D&&q.length===0&&Re.length>0&&ve(Re)},[D,j,$e,q.length,g.addNodeDaemonPicker]),l.useEffect(()=>{const Re=new Set(((te==null?void 0:te.nodes)||[]).map(nt=>nt.id));he&&!Re.has(he)&&le(null)},[te,he]);const ts=l.useMemo(()=>{var Re;if(!(!(J!=null&&J.meshId)||String(J.meshId)!==String((te==null?void 0:te.id)??"")))return(Re=J.meshHost)==null?void 0:Re.hostDaemonId},[J,te]),_e=l.useMemo(()=>mI(n,ye,U,w,ts),[n,ye,U,w,ts]);l.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!n.length&&!Qe.pinned){ge("");return}const Re=Qe.pinned?Ve:_e;Re&&!Hs(Re,je)&&ge(Re)},[n,je,Qe.pinned,Ve,_e,g.meshHostDaemonSection]),l.useEffect(()=>{we&&(Ye||!n.some(Re=>Re.id===we))&&me("")},[Ye,we,n]),l.useEffect(()=>{if(g.createDaemonPicker){if(!n.length){B("");return}(!W||!n.some(Re=>Re.id===W))&&B(n[0].id)}},[n,W,g.createDaemonPicker]),l.useEffect(()=>{var Re;if(!g.createDaemonPicker||!W){A("");return}if(!E.length){A("");return}E.some(nt=>nt.path===T)||A(((Re=E[0])==null?void 0:Re.path)||"")},[W,T,E,g.createDaemonPicker]);const Je=l.useRef(null);l.useEffect(()=>{if(!y)return;const Re=Je.current!==y;if(Je.current=y,Re){const nt=th(y);F(nt),be(null),oe(U,y,nt!==null)}else be(null),oe(U,y,!0)},[y,U]);const Mt=l.useRef(oe);Mt.current=oe;const It=l.useRef(!1),zt=l.useRef(()=>{});zt.current=()=>{It.current||!y||!U||(It.current=!0,Promise.resolve(Mt.current(U,y,!0)).finally(()=>{It.current=!1}))};const Vt=g.meshStatePushRefresh?fI:hI;c2({daemonIds:l.useMemo(()=>[U,...Ct].filter(Boolean),[U,Ct]),meshId:y,sendData:r,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||zt.current()}}),l.useEffect(()=>{if(!y||!U||typeof document>"u")return;let Re=null;const nt=()=>{document.visibilityState==="visible"&&zt.current()},kt=()=>{Re===null&&(Re=setInterval(nt,Vt))},Ht=()=>{Re!==null&&(clearInterval(Re),Re=null)},se=()=>{document.visibilityState==="visible"?kt():Ht()};return document.visibilityState==="visible"&&kt(),document.addEventListener("visibilitychange",se),()=>{Ht(),document.removeEventListener("visibilitychange",se)}},[y,U,Vt]),l.useEffect(()=>{g.queueSection||Z(y)},[y,g.queueSection]);const qt=l.useMemo(()=>n.map(Re=>Re.id).filter(Boolean).sort().join(","),[n]),ys=l.useRef(!1);return l.useEffect(()=>{z(ys.current),ys.current=!0},[qt]),w?te?s.jsx(nI,{selectedMesh:te,error:S,onDismissError:()=>I(null),onBack:()=>{b(null),F(null)},onDelete:re,displayedMeshStatus:us,graphLoading:K,graphError:fe,onRefreshGraph:()=>oe(U,y,!0),savingPolicy:Ie,onUpdatePolicy:Le,coordinatorPromptDraft:it,onCoordinatorPromptDraftChange:ct,savingCoordinatorPrompt:Ze,onSaveCoordinatorPrompt:Ge,daemons:n,coordinatorDaemonId:je,onCoordinatorDaemonIdChange:ge,coordinatorCliType:tt,onCoordinatorCliTypeChange:qe,launchingCoordinator:ke,launchResult:ot,isHostNodeAttached:Ue,selectedHostNode:Be,hostPinned:Qe.pinned,hostLabel:Qe.label,hostOnline:Ye,hostRebindDaemonId:we,onHostRebindDaemonIdChange:Re=>me(Re),onLaunchCoordinator:De,activeDaemon:Oe,activeDaemonId:U,meshQueue:O,userName:a,availableCliProviders:j,savingNodeSlotsId:ae,onUpdateNodeSlots:Ce,savingNodeCapabilitiesId:pe,onUpdateNodeCapabilities:Ee,nodeSystemPromptDrafts:Ot,onNodeSystemPromptDraftChange:(Re,nt)=>Q(kt=>({...kt,[Re]:nt})),savingNodeSystemPromptId:ee,onSaveNodeSystemPrompt:Xe,selectedNodeId:he,onSelectNode:le,showAddNode:D,onShowAddNode:()=>de(!0),onCancelAddNode:()=>de(!1),nodeWorkspace:Se,onNodeWorkspaceChange:ue,nodeProviderPriority:q,onNodeProviderPriorityChange:ve,nodeDaemonId:Ae,onNodeDaemonIdChange:Ne,nodeCustomPath:Ke,onNodeCustomPathChange:ie,nodePickerWorkspaces:Fe,nodePickerProviders:$e,attachableDaemons:ce,onAddNode:xe,onRemoveNode:Me,availableCliAgents:x,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:t}):s.jsx(g2,{meshes:C,loading:N,error:S,onDismissError:()=>I(null),daemons:n,features:{createDaemonPicker:g.createDaemonPicker},showCreate:R,onToggleCreate:()=>L(!R),createName:M,onCreateNameChange:P,createRepoIdentity:$,onCreateRepoIdentityChange:Y,createRepoRemoteUrl:_,onCreateRepoRemoteUrlChange:H,newMeshDaemonId:W,onNewMeshDaemonIdChange:B,newMeshWorkspace:T,onNewMeshWorkspaceChange:A,createPickerWorkspaces:E,onSelectMesh:b,onCreate:G,onCancelCreate:X}):s.jsx(bn,{icon:s.jsx(Zt,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})})}function bI(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function gI(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 yI({children:e}){const{sendCommand:t,sendData:r}=bt(),{ides:n}=gs(),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),u=(p==null?void 0:p.result)??p;if((u==null?void 0:u.success)===!1)throw new Error(u.error||"Coordinator launch failed");const m=(u==null?void 0:u.sessionId)||((h=u==null?void 0:u.session)==null?void 0:h.id)||(u==null?void 0:u.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:Oi,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,d)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:d2}),[t,r,a]);return s.jsx(Zm.Provider,{value:o,children:e})}function xl(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function vI(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=xl();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 hs(e,t){return await fetch(vI(e),{credentials:"same-origin",...t})}function sh(){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 wI{constructor(){st(this,"adapters",new Map);st(this,"states",new Map);st(this,"runtimeListeners",new Map);st(this,"screenshotCallbacks",new Map);st(this,"statusCallbacks",new Set);st(this,"stateChangeCallbacks",new Set);st(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 hs(`${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 ms=new wI;function jI(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=xl();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Hn=jI(),Md=3e3,kI=3e4;let ns=null,SI=0;const va=new Map;let Bs=null,sn=null;function Td(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Kr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function NI(e){return e==="connected"?"connected":e}async function rn(e,t,r){const n=Sp(e,r||{}),a=ns;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++SI}_${Date.now()}`;return new Promise((i,c)=>{const d=setTimeout(()=>{va.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);va.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 yi(e,t){const r=ns;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 rh(e,t,r){const n=ns;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Sp(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}}ms.registerPtyInputSender(rh);class CI{constructor(t){st(this,"daemonId");st(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(ns==null?void 0:ns.readyState)===WebSocket.OPEN}get connectionState(){return(ns==null?void 0:ns.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return rn(this.daemonId,t,r)}async sendInput(t,r){return rn(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Bs&&(clearInterval(Bs),Bs=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await rn(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());ms.emitScreenshot(this.daemonId,a)}}catch{}};r(),Bs=setInterval(r,2e3)}stopScreenshots(t){Bs&&(clearInterval(Bs),Bs=null)}}let Xt=null;function II(e){return(!Xt||Xt.daemonId!==e)&&(Xt=new CI(e)),Xt}function AI({children:e}){const t=l.useRef(nn()),r=nn();t.current=r;const{setUserName:n}=gs(),a=l.useRef(n);a.current=n;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),d=l.useCallback((f,v)=>{c(f),sn==null||sn(f,v)},[]),p=l.useRef(null),u=l.useRef(),m=l.useRef(Md),h=l.useRef(!0),g=l.useRef(!1),k=l.useRef("initial_connect");return l.useEffect(()=>{h.current=!0,g.current=!1;function f(){var x,j;if(!h.current||((x=p.current)==null?void 0:x.readyState)===WebSocket.OPEN||((j=p.current)==null?void 0:j.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Hn}...`),Kr("connect_attempt",{url:Hn,reason:k.current,delayMs:m.current});let w;try{w=new WebSocket(Hn)}catch(C){console.error("[Standalone WS] Failed to create WebSocket:",C),v();return}p.current=w,w.onopen=()=>{if(!h.current){w.close();return}d("connected"),m.current=Md,Kr("open",{url:Hn,reason:k.current}),is.resubscribeAll({sendData:yi}),console.log("[Standalone WS] Connected")},ns=w,w.onmessage=C=>{var y,b;try{const N=JSON.parse(C.data);if((N.type==="command_result"||N.type==="error")&&N.requestId){const S=va.get(N.requestId);S&&(va.delete(N.requestId),N.type==="error"?S.reject(new Error(((y=N.data)==null?void 0:y.message)||"Command failed")):S.resolve(N.data));return}if(N.type==="session_output"){const S=N.sessionId||N.cliId||N.cliType;S&&ms.emitSessionOutput(S,typeof N.data=="string"?N.data:"",typeof N.seq=="number"?N.seq:void 0);return}if(N.type==="runtime_snapshot"){ms.emitRuntimeSnapshot(N.sessionId,typeof N.text=="string"?N.text:"",typeof N.seq=="number"?N.seq:0,!!N.truncated,typeof N.cols=="number"?N.cols:void 0,typeof N.rows=="number"?N.rows:void 0);return}if(N.type==="topic_update"){const S=N.update;S&&is.publish(S);return}if(N.type==="status"||N.type==="initial_state"){const S=N.data;if(!S)return;const{injectEntries:I,markLoaded:R,getIdes:L}=t.current,M=S.instanceId||"standalone",P=L().find(_=>_.id===M),$=II(M);ms.register(M,$),ms.setState(M,"connected"),d("connected",M),ms.emitStatus(M,S);const Y=oa(S,{daemonId:M,existingDaemon:P,existingEntries:L()});Td("ws_status",{type:N.type,daemonId:M,sessions:(S.sessions||[]).map(_=>({id:_.id,parentId:_.parentId,providerType:_.providerType,kind:_.kind,transport:_.transport,unread:_.unread,inboxBucket:_.inboxBucket,lastSeenAt:_.lastSeenAt,lastUpdated:_.lastUpdated,title:_.title})),recentLaunches:(S.recentLaunches||[]).map(_=>({id:_.id,providerType:_.providerType,kind:_.kind,workspace:_.workspace,lastLaunchedAt:_.lastLaunchedAt}))}),Td("entries",{daemonId:M,entries:Y.filter(_=>_.type!=="adhdev-daemon").map(_=>({id:_.id,type:_.type,unread:_.unread,inboxBucket:_.inboxBucket,lastSeenAt:_.lastSeenAt,lastUpdated:_.lastUpdated,sessionId:_.sessionId}))}),Y.length>0&&I(Y,{authoritativeDaemonIds:[M]}),R(),i.current!==M&&((b=o.current)==null||b.call(o),i.current=M,o.current=is.subscribe({sendData:yi},M,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${M}`,params:{includeSessions:!0}},_=>{if(_.topic!=="daemon.metadata")return;const H=t.current.getIdes(),W=H.find(T=>T.id===M),B=oa(_.status,{daemonId:M,existingDaemon:W,existingEntries:H,timestamp:_.timestamp});B.length>0&&t.current.injectEntries(B,{authoritativeDaemonIds:[M]}),_.userName&&a.current&&a.current(_.userName)}))}}catch(N){console.error("[Standalone WS] Parse error:",N)}},w.onclose=C=>{h.current&&(Xt==null||Xt.stopScreenshots(),Xt&&ms.setState(Xt.daemonId,"disconnected"),d("disconnected"),p.current=null,k.current=`close:${C.code}${C.wasClean?":clean":":unclean"}`,Kr("close",{code:C.code,reason:C.reason||"",wasClean:C.wasClean}),v())},w.onerror=C=>{g.current||!h.current||(k.current="error",Kr("error",{message:C instanceof Event?"event":String(C),readyState:w.readyState}),console.warn("[Standalone WS] Error, will reconnect:",C))}}function v(){if(!h.current)return;clearTimeout(u.current);const w=m.current;console.log(`[Standalone WS] Reconnecting in ${w}ms...`),Kr("schedule_reconnect",{reason:k.current,delayMs:w}),u.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,kI),f()},w)}return f(),()=>{var w;h.current=!1,g.current=!0,(w=o.current)==null||w.call(o),o.current=null,i.current=null,clearTimeout(u.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,ns=null),Xt&&(Xt.stopScreenshots(),ms.unregister(Xt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function MI({children:e}){const[t,r]=l.useState("disconnected"),[n,a]=l.useState(null);l.useEffect(()=>(sn=(i,c)=>{r(i),c&&a(c)},()=>{sn=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=NI(t),d={};return n&&(d[n]=c),d.standalone=c,{wsStatus:t,isConnected:i,connectionStates:d}},[t,n]);return s.jsx(of,{connectionOverrides:o,children:s.jsx(AI,{children:e})})}const nh="adhdev_standalone_font_preferences",qs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Oa=[{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"}],pn=[{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"}],TI=new Set(Oa.map(e=>e.id)),_I=new Set(pn.map(e=>e.id));function xs(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Zn("chat",t.chat),code:Zn("code",t.code),terminal:Zn("terminal",t.terminal)}}function Zn(e,t){const r=qs[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"?TI:_I).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function ea(e,t){var a;const r=Zn(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?Oa:pn;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function LI(e){const t=xs(e),r=ea("chat",t.chat),n=ea("code",t.code),a=ea("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Os(e,t=document.documentElement){const r=xs(e),n=LI(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function vi(e){const t=xs(e);try{localStorage.setItem(nh,JSON.stringify(t))}catch{}return t}function RI(){try{const e=localStorage.getItem(nh);if(e)return xs(JSON.parse(e))}catch{}return qs}function PI(){return Os(RI())}function Ur(e,t){var n;const r=e==="chat"?Oa:pn;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const DI=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Gd,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(Ts,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(Zt,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(ja,{}),label:"Settings"}];function $I({children:e}){const t=mn(),r=ji(),n=l.useMemo(()=>DI.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(Vd,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Ci,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Lv,{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 EI=[{icon:s.jsx(Ts,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Zs,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Yd,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(ds,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(an,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Vd,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],BI=[{icon:s.jsx(Bf,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Gd,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Nr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(_f,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(zd,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Pf,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],FI=[{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 OI(){return s.jsxs(bn,{icon:s.jsx(Ci,{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(ht,{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(ht,{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:EI.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(ht,{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:Np.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Ip.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Cp.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(ht,{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:BI.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(ht,{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:FI.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(Ra,{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(Vf,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Eo(e,t,r){return{...e,[t]:r}}function Bo({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($v,{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(os,{type:"text",className:"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:ea(e,n)})]})]})]})}function HI({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(Kt,{variant:"error",children:n}),a&&s.jsx(Kt,{variant:"success",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Bo,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:Oa,onChange:u=>o(Eo(e,"chat",u))}),s.jsx(Bo,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:pn,onChange:u=>o(Eo(e,"code",u))}),s.jsx(Bo,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:pn,onChange:u=>o(Eo(e,"terminal",u))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",Ur("chat",e.chat.preset)," · Code: ",Ur("code",e.code.preset)," · Terminal: ",Ur("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Ur("chat",qs.chat.preset)," / ",Ur("code",qs.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(ks,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:r||!p,children:r?"Saving…":"Save font settings"}),s.jsx(ks,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:r||!p,children:"Revert to saved"}),s.jsx(ks,{type:"button",variant:"secondary",size:"sm",onClick:d,disabled:r,children:"Reset to defaults"})]})]})}function WI(){const{ides:e}=gs(),t=e.find(F=>F.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=bt(),{userName:a}=gs(),[o,i]=l.useState(a||""),[c,d]=l.useState(null),[p,u]=l.useState(null),[m,h]=l.useState(qs),[g,k]=l.useState(!1),[f,v]=l.useState(""),[w,x]=l.useState(""),[j,C]=l.useState("127.0.0.1"),[y,b]=l.useState(""),[N,S]=l.useState(""),[I,R]=l.useState(""),[L,M]=l.useState(""),[P,$]=l.useState(""),[Y,_]=l.useState(!1),H=async()=>{const K=await(await hs("/auth/session")).json();d(K)},W=async()=>{const K=await(await hs("/api/v1/standalone/preferences")).json();u(K),C(K.standaloneBindHost);const fe=xs(K.standaloneFontPreferences);h(fe),Os(fe),vi(fe)};l.useEffect(()=>{a!==void 0&&i(a)},[a]),l.useEffect(()=>{Promise.all([H(),W()]).catch(F=>{M(F instanceof Error?F.message:String(F))})},[]),l.useEffect(()=>{Os(m)},[m]);const B=F=>{const K=F.target.value.trim();t!=null&&t.id&&K!==a&&n(t.id,"set_user_name",{userName:K}).catch(console.error)},[T,A]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),E=F=>{A(F);try{localStorage.setItem("adhdev_sound",F?"1":"0")}catch{}},z=async()=>{v(""),x(""),k(!0);try{const F=xs(m),K=await hs("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:F})}),fe=await K.json();if(!K.ok)throw new Error((fe==null?void 0:fe.error)||"Failed to save standalone font preferences");const be=xs(fe.standaloneFontPreferences);u(fe),h(be),Os(be),vi(be),x("Standalone chat fonts saved for this self-hosted dashboard.")}catch(F){v(F instanceof Error?F.message:String(F))}finally{k(!1)}},G=()=>{const F=xs(p==null?void 0:p.standaloneFontPreferences);v(""),x(""),h(F),Os(F)},re=()=>{v(""),x(""),h(qs),Os(qs)},X=async()=>{M(""),$(""),_(!0);try{const F=await hs("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:j})}),K=await F.json();if(!F.ok)throw new Error((K==null?void 0:K.error)||"Failed to save standalone network preference");u(K),C(K.standaloneBindHost),$(K.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(F){M(F instanceof Error?F.message:String(F))}finally{_(!1)}},te=async()=>{if(M(""),$(""),N.trim().length<4){M("Password must be at least 4 characters.");return}if(N!==I){M("New password and confirmation do not match.");return}_(!0);try{const F=await hs("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,newPassword:N})}),K=await F.json();if(!F.ok)throw new Error((K==null?void 0:K.error)||"Failed to save password");d(K),await W(),b(""),S(""),R(""),$(c!=null&&c.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),sh()}catch(F){M(F instanceof Error?F.message:String(F))}finally{_(!1)}},J=async()=>{M(""),$(""),_(!0);try{const F=await hs("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,clear:!0})}),K=await F.json();if(!F.ok)throw new Error((K==null?void 0:K.error)||"Failed to clear password");d(K),await W(),b(""),S(""),R(""),$("Standalone password disabled.")}catch(F){M(F instanceof Error?F.message:String(F))}finally{_(!1)}};return s.jsxs(bn,{icon:s.jsx(ja,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(Kt,{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(Kt,{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(ht,{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(ht,{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:j==="127.0.0.1",onChange:()=>C("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:j==="0.0.0.0",onChange:()=>C("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points."})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(ks,{type:"button",variant:"primary",size:"sm",onClick:()=>{X()},disabled:Y,children:Y?"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(ht,{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(Kt,{variant:"error",children:L}),P&&s.jsx(Kt,{variant:"success",children:P}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(os,{type:"password",placeholder:c!=null&&c.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:y,onChange:F=>b(F.target.value)}),s.jsx(os,{type:"password",placeholder:c!=null&&c.hasPasswordAuth?"New password":"New standalone password",value:N,onChange:F=>S(F.target.value)}),s.jsx(os,{type:"password",className:"md:col-span-2",placeholder:"Confirm new password",value:I,onChange:F=>R(F.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(ks,{type:"button",variant:"primary",size:"sm",onClick:()=>{te()},disabled:Y,children:Y?"Saving…":c!=null&&c.hasPasswordAuth?"Update password":"Enable password"}),(c==null?void 0:c.hasPasswordAuth)&&s.jsx(ks,{type:"button",variant:"danger",size:"sm",onClick:()=>{J()},disabled:Y,children:"Disable password"})]})]})}),s.jsx(ht,{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(F=>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 ${F.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:F.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:F.type})]},F.type))})}),s.jsx(ht,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(Uv,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(ht,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:s.jsx(dw,{themeDescription:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI.",mobileDescription:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout.",fontsSlot: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(HI,{value:m,savedValue:xs(p==null?void 0:p.standaloneFontPreferences),saving:g,error:f,notice:w,onChange:h,onSave:()=>{z()},onResetToSaved:G,onResetToDefaults:re})]})})}),s.jsx(ht,{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(Ov,{}),s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(zf,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:T,onChange:E})]})}),s.jsx(ht,{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(Tf,{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(os,{type:"text",className:"w-48 text-right",placeholder:"Anonymous",value:o,onChange:F=>i(F.target.value),onBlur:B,onKeyDown:F=>{F.key==="Enter"&&F.currentTarget.blur()}})]})})})]})}const KI=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],qr="adhdev_onboarding_done",UI=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],GI={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function zI({onDone:e}){const[t,r]=l.useState([]),[n,a]=l.useState(new Set(KI)),[o,i]=l.useState(!0),[c,d]=l.useState(null),[p,u]=l.useState(!1),[m,h]=l.useState(null),[g,k]=l.useState("all");l.useEffect(()=>{let y=!1;const b=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${b}/providers?sort=popular&limit=100`).then(N=>{if(!N.ok)throw new Error(`HTTP ${N.status}`);return N.json()}).then(N=>{y||r(N.providers??[])}).catch(N=>{y||d(N instanceof Error?N.message:String(N))}).finally(()=>{y||i(!1)}),()=>{y=!0}},[]);const f=t.filter(y=>g==="all"||y.category===g),v=["cli","ide","extension","acp"].map(y=>({category:y,items:f.filter(b=>b.category===y)})).filter(y=>y.items.length>0),w=l.useCallback(y=>{a(b=>{const N=new Set(b);return N.has(y)?N.delete(y):N.add(y),N})},[]),x=l.useCallback(async()=>{if(n.size===0){localStorage.setItem(qr,"1"),e();return}u(!0);const y=[];for(const b of n)try{const S=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:b})})).json().catch(()=>({}));y.push({type:b,ok:!!S.success,error:S.error})}catch(N){y.push({type:b,ok:!1,error:N instanceof Error?N.message:String(N)})}h(y),u(!1),y.every(b=>b.ok)&&localStorage.setItem(qr,"1")},[n,e]),j=l.useCallback(()=>{localStorage.setItem(qr,"1"),e()},[e]),C=l.useCallback(()=>{m&&m.every(y=>y.ok)?e():p||j()},[m,p,e,j]);return s.jsx(_u,{open:!0,onClose:C,size:"lg",contentClassName:"max-w-2xl",title:"Welcome to ADHDev",footer:s.jsxs("div",{className:"flex w-full items-center gap-2",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(ks,{variant:"secondary",size:"sm",onClick:j,disabled:p,children:"Skip"}),s.jsx(ks,{variant:"primary",size:"sm",onClick:()=>{m?(localStorage.setItem(qr,"1"),e()):x()},disabled:p||!m&&n.size===0,children:p?"Installing…":m?"Done":`Install ${n.size}`})]})]}),children:s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{className:"text-[12px] text-text-muted",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:UI.map(y=>{const b=y.key==="all"?t.length:t.filter(N=>N.category===y.key).length;return b===0&&y.key!=="all"?null:s.jsxs("button",{onClick:()=>k(y.key),className:`machine-btn text-[10px] px-2 py-0.5 ${g===y.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[y.label," ",s.jsxs("span",{className:"opacity-60",children:["(",b,")"]})]},y.key)})}),o&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:"Loading registry…"}),!o&&c&&s.jsxs(Kt,{variant:"error",children:["Failed to load registry: ",c]}),!o&&!c&&f.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:"No providers in this category."}),!o&&!c&&f.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:v.map(y=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:GI[y.category]??y.category}),s.jsx("div",{className:"grid gap-1.5",children:y.items.map(b=>{var L,M;const N=n.has(b.type),S=m==null?void 0:m.find(P=>P.type===b.type),I=((L=b.manifest)==null?void 0:L.icon)??"📦",R=((M=b.manifest)==null?void 0:M.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${N?"bg-accent-primary/[0.06] border-accent-primary/30":"bg-bg-glass border-border-subtle hover:bg-bg-glass-hover"}`,children:[s.jsx("input",{type:"checkbox",checked:N,onChange:()=>w(b.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:b.displayName}),R&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:R})]}),S&&s.jsx("span",{className:`text-[10px] font-semibold ${S.ok?"text-status-online":"text-status-error"}`,children:S.ok?"✓ installed":`✗ ${S.error??"failed"}`})]},b.type)})})]},y.category))})]})})}function VI(){try{return localStorage.getItem(qr)==="1"}catch{return!1}}Cv();sw();xb();PI();const qI=Bd({baseUrl:"",getToken:xl});function YI({children:e}){const[t,r]=l.useState(null),[n,a]=l.useState(!0),[o,i]=l.useState(""),[c,d]=l.useState(""),[p,u]=l.useState(!1),m=async()=>{a(!0),d("");try{const k=await(await hs("/auth/session")).json();r(k)}catch(g){d(g instanceof Error?g.message:String(g))}finally{a(!1)}};l.useEffect(()=>{m()},[]),l.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let g=!1;return(async()=>{try{const k=await hs("/api/v1/standalone/preferences");if(!k.ok)return;const f=await k.json();if(g)return;const v=xs(f.standaloneFontPreferences);Os(v),vi(v)}catch{}})(),()=>{g=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const h=async g=>{g.preventDefault(),u(!0),d("");try{const k=await hs("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),f=await k.json();if(!k.ok)throw new Error((f==null?void 0:f.error)||"Login failed");r(f),i(""),sh()}catch(k){d(k instanceof Error?k.message:String(k))}finally{u(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:h,children:[s.jsx(os,{type:"password",value:o,onChange:g=>i(g.target.value),placeholder:"Enter standalone password",autoFocus:!0}),s.jsx(ks,{type:"submit",variant:"primary",disabled:p||!o,className:"justify-center",children:p?"Signing in…":"Unlock dashboard"})]}):s.jsx(Kt,{variant:"warning",children:"Password login is not enabled on this server."}),c&&s.jsx(Kt,{variant:"error",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 _d(){const{ides:e,initialLoaded:t}=gs();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(Ho,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Ho,{to:"/dashboard",replace:!0})}function JI(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let r=!1;if(!VI())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(zI,{onDone:()=>t(!1)}):null}function XI(){const{ides:e}=gs(),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}=Pp(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(cu,{promptSession:r,isSubmitting:o,error:a,onSubmit:i,onCancel:c})]}):null}function QI(){const e=l.useMemo(()=>({sendCommand:rn,sendData:yi,sendPtyInput:rh}),[]);return s.jsx(Kh,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(df,{client:qI,children:s.jsx(YI,{children:s.jsx(MI,{children:s.jsx(pf,{value:e,children:s.jsxs(xf,{sendDaemonCommand:rn,children:[s.jsx(XI,{}),s.jsxs($I,{children:[s.jsx(JI,{}),s.jsxs(Uh,{children:[s.jsx(Cs,{path:"/dashboard",element:s.jsx(ZN,{})}),s.jsx(Cs,{path:"/machine",element:s.jsx(_d,{})}),s.jsx(Cs,{path:"/machines/:id",element:s.jsx(l2,{})}),s.jsx(Cs,{path:"/machines",element:s.jsx(_d,{})}),s.jsx(Cs,{path:"/about",element:s.jsx(OI,{})}),s.jsx(Cs,{path:"/settings",element:s.jsx(WI,{})}),s.jsx(Cs,{path:"/mesh",element:s.jsx(yI,{children:s.jsx(xI,{})})}),s.jsx(Cs,{path:"*",element:s.jsx(Ho,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}v0({connectionManager:ms});Gh(document.getElementById("root")).render(s.jsx(QI,{}));
|