@adhdev/daemon-standalone 0.9.82-rc.561 → 0.9.82-rc.562

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,116 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-BNQ0ACgR.js","assets/vendor-D2oK2clQ.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
- var bm=Object.defineProperty;var gm=(e,t,n)=>t in e?bm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var st=(e,t,n)=>gm(e,typeof t!="symbol"?t+"":t,n);import{r as l,j as s,M as wi,a as ym,b as vm,c as wm,u as Xe,t as km,d as jm,i as wt,e as Sm,f as fn,R as Rt,g as hr,h as Bo,k as Ho,D as Nm,E as Cm,l as Mm,C as Am,m as Im,B as Tm,n as Pm,o as Dm,p as Lm,H as vr,P as Ss,q as Rm,s as _m,v as Em,w as $m,x as Fm,y as Bm,z as ki,A as Hm,F as Om,G as Wm,I as Um,J as Ns,N as Oo,K as Km}from"./vendor-D2oK2clQ.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"]'))r(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"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(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 r(a){if(a.ep)return;a.ep=!0;const o=n(a);fetch(a.href,o)}})();function Gm(e={}){const t=Math.max(1,Math.floor(e.capacity||200)),n=[];return{record(r){const a={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...r,payload:r.payload?{...r.payload}:{}};return n.push(a),n.length>t&&n.splice(0,n.length-t),a},list(r={}){const a=Math.max(1,Math.floor(r.limit||100));return n.filter(o=>!r.interactionId||o.interactionId===r.interactionId).filter(o=>!r.topic||o.topic===r.topic).filter(o=>!r.kind||o.kind===r.kind).slice(-a).map(o=>({...o,payload:o.payload?{...o.payload}:{}}))},clear(){n.splice(0,n.length)}}}const xn=Gm();function jl(e){const t={};for(const n of e)n.transport&&(t[n.transport]=(t[n.transport]||0)+1);return{count:e.length,ids:e.map(n=>n.id),statuses:e.map(n=>String(n.status||"unknown")),transports:t}}function zm(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Sl(e){return Array.isArray(e)?[...e]:[]}function Dd(e,t){if(!e)return t??null;const n=Object.prototype.hasOwnProperty.call(e,"messages"),r=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:n?Sl(e.messages):i?[]:t.messages,activeModal:r?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...n?{messages:Sl(e.messages)}:{},...r?{activeModal:e.activeModal??null}:{}}}function zn(e,t){const n=zm(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:n??(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)??n??(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:Dd(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 Ld(e,t,n){if(!(t!=null&&t.length))return(n==null?void 0:n.preserveMissing)===!1&&Array.isArray(t)?t:e;if(!(e!=null&&e.length))return t;const r=t.map(a=>{const o=e.find(i=>i.id===a.id);return o?zn(a,o):a});if((n==null?void 0:n.preserveMissing)!==!1){const a=new Set(t.map(o=>o.id));for(const o of e)a.has(o.id)||r.push(o)}return r}function Nl(e){return!!e&&typeof e=="object"&&"text"in e}function ji(e,t){const n=(t==null?void 0:t.joiner)??" ",r=(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(n):Nl(e)?a=String(e.text||""):a=String(e||""),r?a.replace(/\s+/g," ").trim():a}function bn(e){return ji(e,{normalizeWhitespace:!0})}function Vm(e){let t="";for(let n=0;n<e.length;n++){const r=e[n],a=e.charCodeAt(n);if(!(a<=31&&r!==`
3
- `&&r!==" ")&&!(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+=r}}return t}function Cl(e){var n,r;let t=0;return e.activeChat!==void 0&&(t+=4),e.activeInteractivePrompt!==void 0&&(t+=2),(n=e.childSessions)!=null&&n.length&&(t+=2),e.workspace&&(t+=1),e.machine&&(t+=1),(r=e.agents)!=null&&r.length&&(t+=1),t}function Rd(e,t,n){if(n.type!=="adhdev-daemon")return n;const r={...n},a=t.version??n.version??e.version,o=t.serverVersion??e.serverVersion??n.serverVersion,i=t.versionMismatch===!0||e.versionMismatch===!0,u=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,c=t.versionUpdateReason??e.versionUpdateReason??n.versionUpdateReason;return a&&(r.version=a),o&&(r.serverVersion=o),c&&(r.versionUpdateReason=c),a&&o&&a===o?(delete r.versionMismatch,delete r.serverVersion,delete r.versionUpdateRequired,delete r.versionUpdateReason,r):((t.versionMismatch===!0||i&&a&&o&&a!==o)&&(r.versionMismatch=!0),u&&(r.versionUpdateRequired=!0),r)}function qm(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),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,n=qm(bn(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??""),n].join(":")}function Ym(e,t){if(!Array.isArray(e))return e;if(t!=null&&t.has(e))return{count:e.length,sharedRef:!0};let n=2166136261;for(const r of e){const a=Wa(r);for(let o=0;o<a.length;o+=1)n^=a.charCodeAt(o),n=Math.imul(n,16777619)>>>0}return{count:e.length,hash:n.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 Uo(e,t,n){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&&n.add(i)}if(Array.isArray(e)&&Array.isArray(t)){const i=Math.min(e.length,t.length);for(let u=0;u<i;u+=1)Uo(e[u],t[u],n);return}const r=e,a=t,o=new Set([...Object.keys(r),...Object.keys(a)]);for(const i of o)i!=="messages"&&Uo(r[i],a[i],n)}function Jn(e,t){return Array.isArray(e)?e.map(n=>Jn(n,t)):!e||typeof e!="object"?e:Wo(e)?Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[a])=>r.localeCompare(a)).map(([r,a])=>[r,r==="messages"?Ym(a,t):Jn(a,t)])):Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,Jn(r,t)]))}function Jm(e,t){try{const n=new WeakSet;return Uo(e,t,n),JSON.stringify(Jn(e,n))===JSON.stringify(Jn(t,n))}catch{return!1}}function Ko(e,t,n){return Jm(e,t)?(e._lastUpdate=n,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function _d(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function Xm(e,t,n){t[n]!==void 0&&(e[n]=t[n])}function Ml(e,t,n,r){var c;const a=(c=t.chats)!=null&&c.length?t.chats:e.chats,o=Ld(e.childSessions,t.childSessions,{preserveMissing:r}),i=Dd(t.activeChat,e.activeChat),u=t.workspace||e.workspace;return Rd(e,t,{...e,...t,chats:a,childSessions:o,activeChat:i,workspace:u,_lastUpdate:n})}function Qm(e,t,n){var a,o;const r={};t.status&&t.status!==e.status&&(r.status=t.status),t.cdpConnected!==void 0&&(r.cdpConnected=t.cdpConnected),t.childSessions!==void 0&&(r.childSessions=Ld(e.childSessions,t.childSessions,{preserveMissing:n})),(a=t.chats)!=null&&a.length&&!((o=e.chats)!=null&&o.length)&&(r.chats=t.chats),t.workspace&&(r.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"])Xm(r,t,i);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(r.machineNickname=t.machineNickname),t.versionMismatch===!0&&(r.versionMismatch=!0),r}function Zm(e,t,n,r){const a=Qm(e,t,r),o=Object.keys(a).length>0?Rd(e,t,{...e,...a,_lastUpdate:n}):{...e,_lastUpdate:n};return Ko(e,o,n)}function ef(e){const t=new Set(e.map(o=>o.id)),n=new Set,r=new Set,a=new Set;for(const o of e){const i=_d(o);i&&n.add(i),i&&o.type!=="adhdev-daemon"&&r.add(i),i&&o.type==="adhdev-daemon"&&o._sessionListAuthoritative&&a.add(i)}return{incomingIds:t,incomingDaemonIds:n,daemonIdsWithSessionEntries:r,daemonIdsWithAuthoritativeSessionList:a}}function tf(e,t,n,r,a,o){return!a.has(t)||!o.has(t)||r.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?n>1e4:e.transport==="cdp-page"?n>3e4:!1}function sf(e,t,n,r,a){return e.transport?n.has(t)&&!r.has(t)?!0:a.has(t):!1}function nf(e,t,n){var d,m;const r=Date.now(),a=new Set((n==null?void 0:n.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(h=>({...h,_lastUpdate:r}));const o=new Map;for(const h of t)o.set(h.id,h);const{incomingIds:i,incomingDaemonIds:u,daemonIdsWithSessionEntries:c,daemonIdsWithAuthoritativeSessionList:p}=ef(e);for(const h of e){const g=o.get(h.id);if(!g){o.set(h.id,{...h,_lastUpdate:r});continue}const v=Cl(h),f=Cl(g),y=_d(h),j=!a.has(y);if(v>f){const N=Ml(g,h,r,j);o.set(h.id,Ko(g,N,r));continue}if(v<f){o.set(h.id,Zm(g,h,r,j));continue}const x=h.timestamp||r,w=g._lastUpdate||g.timestamp||0;if(x>=w){const N=Ml(g,h,r,j);o.set(h.id,Ko(g,N,r));continue}(d=h.chats)!=null&&d.length&&!((m=g.chats)!=null&&m.length)&&o.set(h.id,{...g,chats:h.chats})}for(const[h,g]of o){const v=g.daemonId||h.split(":")[0];if(!u.has(v))continue;if(a.has(v)&&p.has(v)&&!i.has(h)){o.delete(h);continue}const f=r-(g._lastUpdate||g.timestamp||0);tf(g,v,f,i,a,c)&&o.delete(h)}for(const[h,g]of o){const v=g.daemonId||h.split(":")[0];if(sf(g,v,u,c,o))continue;r-(g._lastUpdate||g.timestamp||0)>3e5&&g.status!=="online"&&o.delete(h)}return Array.from(o.values())}function rf(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}const Ed=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}),$d=l.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function af({children:e,connectionOverrides:t}){const[n,r]=l.useState([]),[a,o]=l.useState(!1),[i,u]=l.useState([]),[c,p]=l.useState(void 0),d=l.useRef(n);l.useEffect(()=>{d.current=n},[n]);const m=l.useCallback((j,x)=>{r(w=>{let N=!1;const k=w.map(b=>b.id!==j||b.chats===x?b:(N=!0,{...b,chats:x}));return N?k:w})},[]),h=l.useCallback((j,x)=>{r(w=>{const N=w.length===0?j:nf(j,w,x),k=!rf(w,N);return k&&xn.record({kind:"dashboard.entries_applied",payload:{incoming:jl(j),next:jl(N)}}),k?N:w})},[]),g=l.useCallback(()=>o(!0),[]),v=l.useMemo(()=>({injectEntries:h,markLoaded:g,getIdes:()=>d.current}),[h,g]),f=t,y=l.useMemo(()=>({ides:n,updateRouteChats:m,initialLoaded:a,toasts:i,setToasts:u,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:c,setUserName:p}),[n,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,c]);return s.jsx($d.Provider,{value:v,children:s.jsx(Ed.Provider,{value:y,children:e})})}function bs(){return l.useContext(Ed)}function ar(){return l.useContext($d)}function Fd(e){const{baseUrl:t,getToken:n,onUnauthorized:r}=e;function a(u){return u.startsWith("http")?u:`${t}${u.startsWith("/")?"":"/"}${u}`}function o(u){const c=n==null?void 0:n(),p=a(u),d=u.startsWith("http")?new URL(p):new URL(p,typeof window<"u"?window.location.origin:"http://localhost");return c&&d.searchParams.set("token",c),!u.startsWith("http")&&!t?`${d.pathname}${d.search}${d.hash}`:d.toString()}async function i(u,c={}){const p={"Content-Type":"application/json",...c.headers||{}},d=n==null?void 0:n();d&&(p.Authorization=`Bearer ${d}`);const m=a(u),h=new AbortController,g=setTimeout(()=>h.abort(),15e3);try{const v=await fetch(m,{...c,headers:p,signal:h.signal});if(v.status===401)throw r==null||r(),new Error("Unauthorized");if(!v.ok){const f=await v.json().catch(()=>({error:v.statusText}));throw new Error(f.error||`API Error: ${v.status}`)}return v.json()}finally{clearTimeout(g)}}return{getDaemons:()=>i("/api/v1/daemons"),getDaemonStatus:u=>i(`/api/v1/daemons/${u}/status`),sendCommand:(u,c,p={})=>i(`/api/v1/daemons/${u}/command`,{method:"POST",body:JSON.stringify({type:c,payload:p})}),execTerminal:(u,c,p)=>i(`/api/v1/daemons/${u}/terminal`,{method:"POST",body:JSON.stringify({command:c,name:p})}),sendAgentMessage:(u,c,p)=>i(`/api/v1/shortcuts/${u}/chat`,{method:"POST",body:JSON.stringify({agentType:c,message:p})}),getAgentStatus:u=>i(`/api/v1/shortcuts/${u}/status`),approveAgent:(u,c,p)=>i(`/api/v1/shortcuts/${u}/approve`,{method:"POST",body:JSON.stringify({agentType:c,action:p?"approve":"reject"})}),getMuxState:u=>i(`/api/v1/mux/${encodeURIComponent(u)}/state`),getMuxSocketInfo:u=>i(`/api/v1/mux/${encodeURIComponent(u)}/socket-info`),controlMux:(u,c,p={})=>i(`/api/v1/mux/${encodeURIComponent(u)}/control`,{method:"POST",body:JSON.stringify({type:c,payload:p})}),getMuxEventsUrl:u=>o(`/api/v1/mux/${encodeURIComponent(u)}/events`),getRuntimeEventsUrl:u=>o(`/api/v1/runtime/${encodeURIComponent(u)}/events`),request:i}}const of=Fd({baseUrl:"http://localhost:3847"}),lf=l.createContext(of);function cf({client:e,children:t}){return s.jsx(lf.Provider,{value:e,children:t})}const df={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Bd=l.createContext(df);function uf({value:e,children:t}){return s.jsx(Bd.Provider,{value:e,children:t})}function yt(){return l.useContext(Bd)}function Hd(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function pf(e){const t=Hd(e);if(!t||t.error!=="untrusted_external_provider")return null;const n=t.provider&&typeof t.provider=="object"?t.provider:null;return{providerType:typeof(n==null?void 0:n.type)=="string"?n.type:null,sourceName:typeof(n==null?void 0:n.sourceName)=="string"?n.sourceName:null,description:typeof t.hint=="string"?t.hint:void 0}}function hf(e){const[t,n]=l.useState(null),r=l.useCallback(async(i,u)=>{const c=m=>e(i,"launch_cli",{...u,...m}),p=await c({}),d=pf(p);return d?new Promise(m=>{n({providerType:d.providerType||String(u.cliType??"?"),sourceName:d.sourceName,description:d.description,retry:()=>c({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){n(null);try{const u=await i.retry(),c=Hd(u);c!=null&&c.success?i.resolve({ok:!0,response:u}):i.resolve({ok:!1,error:(c==null?void 0:c.error)||"launch failed after confirm",response:u})}catch(u){i.resolve({ok:!1,error:(u==null?void 0:u.message)||String(u)})}}},[t]),o=l.useCallback(()=>{const i=t;i&&(n(null),i.resolve({ok:!1,cancelled:!0}))},[t]);return{launchCli:r,pending:t,confirm:a,cancel:o}}function mf({providerType:e,sourceName:t,description:n,onConfirm:r,onCancel:a}){const o=l.useRef(null);return l.useEffect(()=>{var i;(i=o.current)==null||i.focus()},[]),l.useEffect(()=>{const i=u=>{u.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:n??"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:r,className:"px-3 py-1 text-sm rounded bg-amber-500 text-black font-semibold hover:opacity-90",children:"Activate"})]})]})})}const Od=l.createContext(null);function ff({sendDaemonCommand:e,children:t}){const n=hf(e),r=l.useMemo(()=>({launchCli:n.launchCli}),[n.launchCli]);return s.jsxs(Od.Provider,{value:r,children:[t,n.pending&&s.jsx(mf,{providerType:n.pending.providerType,sourceName:n.pending.sourceName,description:n.pending.description,onConfirm:n.confirm,onCancel:n.cancel})]})}function wa(){const e=l.useContext(Od);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 xf(e,t,n){return Number(e.receivedAt||n[ta(e)]||0)||0}function Ud(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function bf(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function Dn(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 Ua(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 gf(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t^e.charCodeAt(n),t|=0;return(t>>>0).toString(36)}function ta(e,t){const n=e,r=ji(e.content,{joiner:`
5
- `}),a=[e.id?`id:${e.id}`:"",n._localId?`local:${n._localId}`:"",n._turnKey?`turn:${n._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:${gf(r)}`,o?`ts:${o}`:""].filter(Boolean).join("|")}function yf(e){let t=2166136261;for(const n of e){const r=String(n||"");for(let a=0;a<r.length;a+=1)t^=r.charCodeAt(a),t=Math.imul(t,16777619)>>>0;t^=255,t=Math.imul(t,16777619)>>>0}return t.toString(16).padStart(8,"0")}function vf(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Kd(e){return e?yf([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),vf(e.content)]):""}const Si=200,wf=80,Al=650,Ln=new Map;function sa(e,t){if(!e)return!1;const n=String(e.messageFingerprint||"");return n?n===String(t||""):!0}function kf(e,t){if(!Array.isArray(e)||e.length===0)return"0:empty";const n=String(t||"").trim();if(n)return`${e.length}:${n}`;const r=e[e.length-1];return`${e.length}:${Kd(r)}`}function jf(e,t,n,r){return e||!t?!1:sa(n,r)}function Sf({scrollTop:e,scrollHeight:t,clientHeight:n,topThresholdPx:r=wf,bottomThresholdPx:a=Si}){const o=Math.max(0,Number(e)||0),i=Math.max(0,Number(t)||0),u=Math.max(0,Number(n)||0);return Math.max(0,i-u)<=0?{showTop:!1,showBottom:!1}:{showTop:o>r,showBottom:Math.max(0,i-o-u)>a}}function Nf(e){return Sf({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function Vn(e,t=Si){return!!e&&e.fromBottom>=t}function Cf(e,t){return sa(e,t)?!Vn(e):!0}function Mf({hasSelection:e,userScrolledUp:t,hasChatContentChanged:n=!0}){return!(e||t||!n)}function Af({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:n}){return e?!1:n||!t}function Ka(e,t){const n=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(n)?n:t.top}const Ye={size:18};function Gd({size:e=Ye.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=Ye.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 Is({size:e=Ye.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=Ye.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 If({size:e=Ye.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 Tf({size:e=Ye.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=Ye.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=Ye.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 Pf({size:e=Ye.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 ka({size:e=Ye.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=Ye.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 Df({size:e=Ye.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 Lf({size:e=Ye.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=Ye.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 us({size:e=Ye.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 Mi({size:e=Ye.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 gn({size:e=Ye.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 ja({size:e=Ye.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=Ye.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 or({size:e=Ye.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 es({size:e=Ye.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 Rf({size:e=Ye.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=Ye.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=Ye.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=Ye.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=Ye.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),s.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),s.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function Ii({size:e=Ye.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=Ye.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=Ye.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=Ye.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 Mt({size:e=Ye.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 $f({size:e=Ye.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=Ye.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 Bf({size:e=Ye.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=Ye.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 Cn({size:e=Ye.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=Ye.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 Of({size:e=Ye.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 Wf({size:e=Ye.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=Ye.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=Ye.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 Kf({size:e=Ye.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 Gf({size:e=Ye.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 zf({size:e=Ye.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 Vf({size:e=Ye.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 qf({size:e=Ye.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 Yf({size:e=Ye.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 Jf({size:e=Ye.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 Xf({size:e=Ye.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 Qf({size:e=Ye.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",Il=new Set(["hidden","debug","internal"]),Tl=new Set(["visible","user","chat"]),Zf=new Set(["debug","trace","internal"]),ex=new Set(["tool_call","terminal_command","runtime_activity"]),tx=new Set(["runtime_status","provider_chrome","control"]),sx=new Set(["thought","tool","terminal"]);function tu(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function rn(e){return typeof e=="string"?e.trim().toLowerCase():""}function Ga(e,t,n){return e[n]??(t==null?void 0:t[n])}function Pl(e,t,n){const r=e;return n.some(a=>r[a]===!0||(t==null?void 0:t[a])===!0)}function nx(e,t){const n=rn(e.kind);return n||(t==="tool"?"tool":"standard")}function za(e,t,n){const r=tu(e),a=typeof(r==null?void 0:r.label)=="string"?r.label.trim():"";return a||(t==="terminal"||n==="terminal_command"?"Terminal":t==="tool"||n==="tool_call"?"Tool":t==="thought"?"Thought":n==="runtime_activity"?"Runtime":"Activity")}function rx(e){const t=e.content;return Array.isArray(t)&&t.some(n=>!!n&&typeof n=="object"&&n.type!=="text")}function Pi(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=tu(e),n=rn(e.role),r=nx(e,n),a=rn(Ga(e,t,"visibility")),o=rn(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??a),i=rn(Ga(e,t,"audience")),u=rn(Ga(e,t,"source")),c=Il.has(a)||Il.has(o)||Zf.has(i)||Pl(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),p=Tl.has(a)||Tl.has(o)||i==="chat"||Pl(e,t,["userFacing"]),d=sx.has(r)||ex.has(u);if(c)return{surface:d?"activity":"internal",isUserFacing:!1,isActivityFacing:d,isInternal:!d,role:n,kind:r,label:za(e,r,u)};if(p)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:n,kind:r,label:za(e,r,u)};if((n==="system"||r==="system")&&rx(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:n,kind:r,label:"Chat"};if(tx.has(u)||n==="system"||r==="system")return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:n,kind:r,label:"Internal"};if(d)return{surface:"activity",isUserFacing:!1,isActivityFacing:!0,isInternal:!1,role:n,kind:r,label:za(e,r,u)};const m=(n==="user"||n==="human"||n==="assistant")&&(r==="standard"||r==="");return{surface:m?"chat":"internal",isUserFacing:m,isActivityFacing:!1,isInternal:!m,role:n,kind:r,label:m?"Chat":"Internal"}}function ax(e){return(Array.isArray(e)?e:[]).filter(t=>Pi(t).isUserFacing)}function su(e){return(Array.isArray(e)?e:[]).filter(t=>Pi(t).isActivityFacing)}function nu(e){const t=e.content;return typeof t=="string"?t:(()=>{try{return JSON.stringify(t??"")}catch{return String(t??"")}})()}function ox(e){return`${String(e.role||"")}::${nu(e)}`}function ix(e){if(e.length<2)return e;const t=[];let n="";for(const r of e){const a=ox(r);nu(r).trim().length>0&&a===n||(t.push(r),n=a)}return t}function lx(e,t,n){return!n||t.length===0?e:[...e,...t].sort((r,a)=>{const o=Number(r.receivedAt??r.timestamp??0)||0,i=Number(a.receivedAt??a.timestamp??0)||0;if(o!==i)return o-i;const u=Number(r.index??0)||0,c=Number(a.index??0)||0;return u-c})}function Dl(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(eu))==="1"}catch{return!1}}function cx({text:e}){const{t}=Xe("common"),[n,r]=l.useState(!1),a=l.useCallback(()=>{navigator.clipboard.writeText(e).catch(()=>{}),r(!0),setTimeout(()=>r(!1),1500)},[e]);return s.jsx("button",{type:"button",onClick:a,"aria-label":t("chat.copyMessage"),className:"chat-copy-btn",children:n?s.jsx(Pf,{size:11}):s.jsx(qd,{size:11})})}const ru=[ym,{singleTilde:!1}],au=[ru,vm,wm],dx=[ru];function wr(e,t,n){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,n?s.jsx("div",{className:"mt-1 opacity-80",style:{whiteSpace:"pre-wrap"},children:n}):null]})}function Ll(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):Ud(e)?s.jsx(wi,{remarkPlugins:au,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}const ux=l.memo(function({content:t,renderAsPreformatted:n,renderAsMarkdown:r}){return n?s.jsx("pre",{className:"chat-preformatted",children:t}):r?s.jsx(wi,{remarkPlugins:au,children:t}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:t})});function Rn({parts:e,renderAsPreformatted:t}){return s.jsx("div",{className:"flex flex-col gap-2",children:e.map((n,r)=>{if(n.type==="text")return s.jsx("div",{children:Ll(String(n.text||""),t)},`text-${r}`);if(n.type==="image"){const a=Ua(n),o=n.alt||n.description||Dn(n.uri,"image");return a?s.jsx("img",{src:a,alt:o,className:"max-w-full rounded-md border border-border-subtle"},`image-${r}`):s.jsx("div",{children:wr("Image",o,n.mimeType)},`image-fallback-${r}`)}if(n.type==="audio"){const a=Ua(n);return a?s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("audio",{controls:!0,src:a,className:"max-w-full"}),n.transcript?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:n.transcript}):null]},`audio-${r}`):s.jsx("div",{children:wr("Audio",Dn(n.uri,"audio"),n.transcript||n.mimeType)},`audio-fallback-${r}`)}if(n.type==="video"){const a=Ua(n),o=n.title||n.name||n.alt||Dn(n.uri,"video"),i=[n.transcript,n.description,n.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:n.posterUri,className:"max-w-full rounded-md border border-border-subtle"}):wr("Video",o,i),a&&i?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:i}):null]},`video-${r}`)}if(n.type==="resource_link"){const a=n.title||n.name||Dn(n.uri,"resource"),o=[n.description,n.mimeType].filter(Boolean).join(`
7
- `);return s.jsxs("div",{className:"flex flex-col gap-1",children:[n.uri?s.jsx("a",{href:n.uri,target:"_blank",rel:"noreferrer",download:!0,className:"underline break-all",children:a}):wr("Resource",a,o),n.uri&&o?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:o}):null]},`resource-link-${r}`)}if(n.type==="resource"&&n.resource){const a=Dn(n.resource.uri,"resource");if(n.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}),Ll(n.resource.text,!0)]},`resource-${r}`);if(n.resource.uri)return s.jsx("a",{href:n.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:a},`resource-uri-${r}`)}return null})})}const px=l.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(wi,{remarkPlugins:dx,children:t.text}),s.jsx("span",{className:"action-time",children:Wd(t.timestamp)})]})},(e,t)=>e.log===t.log);function Rl(e){const t=e.meta;return[Kd(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:n,agentName:r,userName:a,isCliMode:o,isTextExpanded:i,onToggleTextExpanded:u}){var S,M,A;const c=(t.role||"").toLowerCase(),p=c==="user"||c==="human",d=t.kind||(c==="tool"?"tool":"standard"),m=Pi(t),h=bf(t.content)?t.content:null,g=!!(h!=null&&h.some(T=>T.type!=="text")),v=ji(t.content,{joiner:`
8
- `});if(m.isActivityFacing&&d!=="thought"&&d!=="tool"&&d!=="terminal"){const T=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:T})]}),g&&h?s.jsx("div",{className:"chat-msg-activity-body",children:s.jsx(Rn,{parts:h,renderAsPreformatted:!1})}):s.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:v})]})}if(d==="thought"){const T=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(Bf,{size:13}),s.jsx("span",{children:T})]}),s.jsx("div",{className:"chat-msg-body",children:v})]})}if(d==="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(Rn,{parts:h,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:v})]});if(d==="terminal"){const T=(M=t.meta)!=null&&M.isRunning?"⏳":"✅",L=typeof((A=t.meta)==null?void 0:A.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:T}),s.jsx("span",{children:L})]}),g&&h?s.jsx("div",{className:"chat-msg-body",children:s.jsx(Rn,{parts:h,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:v})]})}if(d==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:g&&h?s.jsx(Rn,{parts:h,renderAsPreformatted:!1}):v.slice(0,100)});const f=t.meta,j=(typeof(f==null?void 0:f.renderMode)=="string"?f.renderMode.trim():"")==="preformatted",x=v,w=!1,N=x,k=j,b=!p&&!k&&Ud(N),C=["chat-message-row",p?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return s.jsx("div",{className:C,children:(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||r}),s.jsxs("span",{className:"chat-bubble-header-end",children:[(x||g)&&s.jsx(cx,{text:v}),n!=null&&s.jsx("span",{className:"chat-time",children:Wd(n)})]})]}),(x||g)&&s.jsx("div",{className:"chat-markdown",children:g&&h?s.jsx(Rn,{parts:h,renderAsPreformatted:k}):s.jsx(ux,{content:N,renderAsPreformatted:k,renderAsMarkdown:b})}),w]})})},(e,t)=>(e.message===t.message||Rl(e.message)===Rl(t.message))&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),mx=l.forwardRef(function({messages:t,actionLogs:n,agentName:r="Agent",userName:a,isCliMode:o=!1,isWorking:i=!1,contextKey:u="",receivedAtMap:c={},lastMessageHash:p,showActivityMessages:d=!1,emptyState:m,onLoadMore:h,isLoadingMore:g,hasMoreHistory:v,hiddenLiveCount:f=0,loadError:y,scrollToBottomRequestNonce:j,isVisible:x=!0},w){const N=l.useRef(null),k=l.useRef(null),b=l.useRef(null),C=l.useRef(0),S=l.useRef(""),M=l.useRef(""),A=l.useRef(!1),T=l.useRef(null),L=l.useRef(!1),P=l.useRef(null),B=l.useRef(!1),[z,R]=l.useState(new Set),[_,K]=l.useState({showTop:!1,showBottom:!1}),E=l.useRef(!1),D=l.useRef(!1),$=l.useRef(x),I=l.useRef(x),G=l.useRef(null);I.current=x;const Y=()=>{const ce=N.current;return ce?ce.scrollHeight-ce.scrollTop-ce.clientHeight<Si:!0},Z=l.useCallback(()=>{const ce=N.current,F=ce?Nf(ce):{showTop:!1,showBottom:!1};K(le=>le.showTop===F.showTop&&le.showBottom===F.showBottom?le:F)},[]),q=l.useCallback((ce="auto")=>{var le;const F=N.current;F&&(F.scrollTo({top:F.scrollHeight,behavior:ce}),(le=F.ownerDocument.defaultView)==null||le.requestAnimationFrame(()=>Z()))},[Z]),ne=l.useCallback((ce="auto")=>{var le;const F=N.current;F&&(F.scrollTo({top:0,behavior:ce}),(le=F.ownerDocument.defaultView)==null||le.requestAnimationFrame(()=>Z()))},[Z]),ue=l.useCallback(()=>{var de;const ce=N.current,F=(de=window.getSelection)==null?void 0:de.call(window);if(!ce||!F||F.rangeCount===0||F.isCollapsed){B.current=!1;return}const le=F.anchorNode,je=F.focusNode;B.current=!!(le&&je&&ce.contains(le)&&ce.contains(je))},[]),ae=l.useMemo(()=>{const ce=ax(t),F=su(t);return ix(lx(ce,F,d))},[t,d]),O=ae.length===t.length?p:void 0,se=kf(ae,O),X=l.useCallback(()=>{const ce=N.current;if(!ce||!u||!I.current)return;const F={top:ce.scrollTop,fromBottom:Math.max(0,ce.scrollHeight-ce.scrollTop-ce.clientHeight),messageFingerprint:se};G.current={contextKey:u,snapshot:F},Ln.set(u,F)},[u,se]),oe=l.useCallback((ce="auto")=>{T.current!=null&&cancelAnimationFrame(T.current),T.current=requestAnimationFrame(()=>{T.current=null,q(ce)})},[q]),Se=l.useCallback(()=>{E.current=!1,L.current=!0,D.current=!0,P.current!=null&&window.clearTimeout(P.current),P.current=window.setTimeout(()=>{L.current=!1,P.current=null},Al)},[]);l.useEffect(()=>{const ce=!A.current,F=M.current!==u;if(M.current=u,ce||F){A.current=!0;const je=u?Ln.get(u):null,de=!!je&&sa(je,se);E.current=de?Vn(je):!1,L.current=Cf(je,se),B.current||(de?requestAnimationFrame(()=>{const H=N.current;H&&(Ka(H,je),E.current=Vn(je),Z(),D.current=!0)}):oe("auto")),C.current=ae.length,S.current=se;return}ae.length>C.current;const le=se!==S.current;Mf({hasSelection:B.current,userScrolledUp:E.current,hasChatContentChanged:le})&&oe("auto"),C.current=ae.length,S.current=se},[se,u,ae.length,oe,Z]),l.useEffect(()=>{j&&(Se(),B.current||oe("auto"))},[Se,oe,j]),l.useEffect(()=>{const ce=$.current;ce&&!x&&X(),I.current=x,$.current=x;const F=u?Ln.get(u):null;if(jf(ce,x,F,se)){if(!F)return;E.current=Vn(F),L.current=!1,B.current||requestAnimationFrame(()=>{const le=N.current;le&&(Ka(le,F),Z())});return}},[x,u,se,Se,X,oe,Z]),l.useEffect(()=>()=>{const ce=G.current;ce&&Ln.set(ce.contextKey,ce.snapshot),T.current!=null&&cancelAnimationFrame(T.current),P.current!=null&&window.clearTimeout(P.current)},[]),l.useEffect(()=>{const ce=k.current,F=N.current;if(!ce||!F)return;const le=()=>{P.current!=null&&window.clearTimeout(P.current),P.current=window.setTimeout(()=>{L.current=!1,P.current=null},Al)},je=new ResizeObserver(()=>{Z();const de=L.current;Af({hasSelection:B.current,userScrolledUp:E.current,contextAutoScrollActive:de})&&(oe("auto"),de&&le())});return je.observe(ce),F!==ce&&je.observe(F),()=>{je.disconnect(),P.current!=null&&(window.clearTimeout(P.current),P.current=null)}},[oe,u,Z]),l.useImperativeHandle(w,()=>({scrollToBottom:(ce="smooth")=>{q(ce)}}),[q]),l.useEffect(()=>{const ce=N.current;if(!ce)return;let F;const le=()=>{X(),clearTimeout(F),F=setTimeout(()=>{E.current=!Y(),Z()},50)};return ce.addEventListener("scroll",le,{passive:!0}),()=>{ce.removeEventListener("scroll",le),clearTimeout(F)}},[X,Z]),l.useEffect(()=>(document.addEventListener("selectionchange",ue),()=>document.removeEventListener("selectionchange",ue)),[ue]);const ye=l.useRef(0),ke=l.useRef(!1);l.useEffect(()=>{const ce=N.current;if(!ce||!ke.current||ye.current===0)return;const F=ce.scrollHeight-ye.current;F>0&&(ce.scrollTop=F),Z(),X(),ye.current=0,ke.current=!1},[ae.length,X,Z]),l.useEffect(()=>{if(D.current||!u)return;const ce=Ln.get(u),F=N.current;if(!(!ce||!F)){if(!sa(ce,se)){q("auto"),D.current=!0;return}Ka(F,ce),E.current=Vn(ce),Z(),D.current=!0}},[u,se,ae.length,q,Z]);const me=()=>{const ce=N.current;ce&&(ye.current=ce.scrollHeight),ke.current=!0,h==null||h()},U=()=>{E.current=!0,ne("smooth"),X()},W=()=>{Se(),q("smooth"),X()},Q=l.useMemo(()=>{const ce=ae.map((de,H)=>({type:"message",data:de,index:H,ts:xf(de,H,c)}));if(!n||n.length===0)return ce;const F=[...n].sort((de,H)=>de.timestamp-H.timestamp).map((de,H)=>({type:"action",data:de,index:H,ts:de.timestamp})),le=[];let je=0;for(const de of ce){for(;je<F.length&&de.ts>0&&F[je].ts<de.ts;)le.push(F[je++]);le.push(de)}for(;je<F.length;)le.push(F[je++]);return le},[ae,n,c]),V=f>0||!!v,fe=f>0?`↑ Show ${Math.min(f,80)} earlier messages${f>80?` (${f} hidden)`:""}`:y?`↻ ${y}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:N,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:k,className:"chat-container-content",children:[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 ${y&&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:fe})}),Q.length===0&&!V&&(m||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),Q.map(ce=>{if(ce.type==="action"){const be=ce.data;return s.jsx(px,{log:be},`action-${ce.index}`)}const F=ce.data;ce.index;const le=ta(F),je=F.receivedAt||c[le],de=`${u}-${le}`,H=z.has(de);return s.jsx(hx,{message:F,receivedAt:je,agentName:r,userName:a,isCliMode:o,isTextExpanded:H,onToggleTextExpanded:()=>R(be=>{const Ne=new Set(be);return H?Ne.delete(de):Ne.add(de),Ne})},`msg-${le}`)}),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})]})}),(_.showTop||_.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[_.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"}),_.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:W,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),fx=l.memo(mx,(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),xx="modulepreload",bx=function(e){return"/"+e},_l={},gx=function(t,n,r){let a=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),u=(i==null?void 0:i.nonce)||(i==null?void 0:i.getAttribute("nonce"));a=Promise.allSettled(n.map(c=>{if(c=bx(c),c in _l)return;_l[c]=!0;const p=c.endsWith(".css"),d=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${d}`))return;const m=document.createElement("link");if(m.rel=p?"stylesheet":xx,p||(m.as="script"),m.crossOrigin="",m.href=c,u&&m.setAttribute("nonce",u),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 ${c}`)))})}))}function o(i){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=i,window.dispatchEvent(u),!u.defaultPrevented)throw i}return a.then(i=>{for(const u of i||[])u.status==="rejected"&&o(u.reason);return t().catch(o)})};let El=!1;const ou=l.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:n,fontSize:r=13,readOnly:a=!1,sizingMode:o="measured"},i)=>{const u=l.useRef(null),[c,p]=l.useState(null),d=l.useRef([]),m=l.useRef(!1),h=l.useRef(!1),g=l.useRef(!1),v=l.useRef(!1),f=()=>{const y=u.current;if(y){m.current&&(y.clear(),m.current=!1);for(const j of d.current)y.write(j.data,j.onProcessed);d.current=[],h.current&&(y.fit(),h.current=!1),g.current&&(y.bumpResize(),g.current=!1),v.current&&(y.scrollToTop(),v.current=!1)}};return l.useImperativeHandle(i,()=>({write:(y,j)=>{u.current?u.current.write(y,j):d.current.push({data:y,onProcessed:j})},clear:()=>{u.current?u.current.clear():(d.current=[],m.current=!0)},reset:()=>{u.current&&typeof u.current.reset=="function"?u.current.reset():(d.current=[],m.current=!0)},resize:(y,j)=>{u.current&&typeof u.current.resize=="function"&&u.current.resize(y,j)},fit:()=>{u.current?u.current.fit():h.current=!0},bumpResize:()=>{u.current?u.current.bumpResize():g.current=!0},scrollToTop:()=>{u.current?u.current.scrollToTop():v.current=!0},getSelection:()=>{var y,j;return((j=(y=u.current)==null?void 0:y.getSelection)==null?void 0:j.call(y))||""},getVisibleText:()=>{var y,j;return((j=(y=u.current)==null?void 0:y.getVisibleText)==null?void 0:j.call(y))||""}}),[]),l.useEffect(()=>{c&&f()},[c]),l.useEffect(()=>{let y=!1;return gx(()=>import("./terminal-BNQ0ACgR.js"),__vite__mapDeps([0,1,2])).then(j=>{El||(El=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),y||p(()=>j.GhosttyTerminalView)}).catch(j=>{console.error("[CliTerminal] failed to load terminal renderer",j)}),()=>{y=!0}},[]),c?s.jsx(c,{ref:u,onInput:e,onViewportMetrics:t,onScrollMetrics:n,fontSize:r,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 Ht(...e){return km(jm(e))}const yx={lg:"rounded-lg",xl:"rounded-xl","2xl":"rounded-2xl"},vx={none:"",sm:"p-3",md:"px-4 py-3.5",lg:"px-5 py-4"},js=l.forwardRef(function({radius:t="xl",padding:n="md",className:r,...a},o){return s.jsx("div",{ref:o,className:Ht("border border-border-subtle bg-bg-secondary",yx[t],vx[n],r),...a})});function kr({label:e,value:t,sub:n,icon:r}){return s.jsxs(js,{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsx("span",{className:"text-base flex items-center",children:r}),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}),n&&s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:n})]})}function $l({value:e,max:t,label:n,color:r="#8b5cf6",detail:a,compact:o=!1}){const i=t>0?Math.min(Math.round(e/t*100),100):0,u=i>85?"#ef4444":i>60?"var(--status-warning)":r;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:n}),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:u}})})]}):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:n}),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, ${u}, ${u}cc)`}})}),a&&s.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function wx({cursorPos:e,viewportRef:t,imgRef:n}){var x;if(!e||!n.current)return null;const r=n.current,a=r.getBoundingClientRect(),o=(x=t.current)==null?void 0:x.getBoundingClientRect();if(!o)return null;const i=r.naturalWidth||a.width,u=r.naturalHeight||a.height,c=i/u,p=a.width/a.height;let d,m,h,g;c>p?(d=a.width,m=a.width/c,h=0,g=(a.height-m)/2):(m=a.height,d=a.height*c,h=(a.width-d)/2,g=0);const v=a.left-o.left+h+d*e.nx,f=a.top-o.top+g+m*e.ny,y=Math.max(8,Math.min(o.width-8,v)),j=Math.max(8,Math.min(o.height-8,f));return s.jsxs("div",{style:{position:"absolute",left:y-8,top:j-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[s.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:5,top:5,width:6,height:6,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 0 8px rgba(59,130,246,0.6)"}})]})}function kx({inputMode:e,onToggleInputMode:t,isImeOpen:n,setIsImeOpen:r,isMenuOpen:a,setIsMenuOpen:o,imeText:i,setImeText:u,handleImeSubmit:c,isConnActive:p,zoom:d,isMobile:m,mobileFillZoom:h,onZoomOut:g,onZoomReset:v,onZoomIn:f,transportType:y,screenshotUsage:j,lastActionStatus:x}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:w=>w.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[s.jsxs("div",{onClick:t,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[s.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),s.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),s.jsxs("div",{className:"relative",children:[s.jsx("div",{onClick:()=>{r(w=>!w),o(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${n?"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:"⌨️"})}),n&&s.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:s.jsx("input",{type:"text",placeholder:"Type & Enter...",value:i,autoFocus:!0,onTouchStart:w=>w.stopPropagation(),onChange:w=>u(w.target.value),onKeyDown:w=>{c(w)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{o(w=>!w),r(!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"})]}),d>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(d*100),"%"]}),y==="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"}),y==="relay"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),j&&j.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:j.budgetExhausted?"#ef4444":"#c4b5fd",background:j.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:j.budgetExhausted?"TURN blocked":`TURN ${j.dailyUsedMinutes}/${j.dailyBudgetMinutes}m`}),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:w=>w.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",d<=(m?h:1)+.01?m?"FILL":"FIT":`${Math.round(d*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:w=>{w.stopPropagation(),g()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),s.jsx("button",{onClick:w=>{w.stopPropagation(),v()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:m?"FILL":"FIT"}),s.jsx("button",{onClick:w=>{w.stopPropagation(),f()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function jx({waitingLabel:e,waitingHint:t,transportType:n}){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}),n==="relay"&&s.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function Sx(){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 Fl(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 mr(e,t){const n=l.useRef(null),r=l.useRef(0);l.useEffect(()=>{if(!Sx())return;r.current+=1;const a=n.current;if(!a){console.debug(`[render-trace] ${e}#${r.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(t).map(([i,u])=>[i,Fl(u)]))}),n.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}#${r.current}`,{changed:o,snapshot:Object.fromEntries(o.map(i=>[i,Fl(t[i])]))}),n.current=t})}function Nx({containerRef:e,viewportRef:t,imgRef:n,inputMode:r,setInputMode:a,minZoom:o,zoomRef:i,panXRef:u,panYRef:c,setPanX:p,setPanY:d,setZoom:m,lastWheelTimeRef:h,onAction:g,setLastActionStatus:v,spawnRippleFromNormalized:f,clampPan:y,isMobile:j,mobileFillZoom:x}){const[w,N]=l.useState(null),k=l.useRef(null),b=l.useRef(null),C=l.useRef(null),S=l.useRef(!1),M=l.useRef(null),A=l.useRef(0),T=l.useRef(null),L=l.useRef(1),P=l.useRef({x:0,y:0}),B=l.useRef(!1),z=l.useRef(r),R=l.useRef(g),_=30,K=550,E=18,D=60,$=400,I=12,G=()=>{if(k.current)return;const q={nx:.5,ny:.5};k.current=q,N(q)};return l.useEffect(()=>{z.current=r,r==="mouse"&&G()},[r]),l.useEffect(()=>{R.current=g},[g]),l.useEffect(()=>{const q=e.current;if(!q)return;const ne=oe=>{if(!n.current)return null;const Se=n.current.getBoundingClientRect();return!Se.width||!Se.height?null:{nx:Math.max(0,Math.min(1,(oe.clientX-Se.left)/Se.width)),ny:Math.max(0,Math.min(1,(oe.clientY-Se.top)/Se.height))}},ue=(oe,Se)=>{if(!n.current)return{dnx:0,dny:0};const ye=n.current,ke=ye.getBoundingClientRect(),me=ye.naturalWidth||ke.width,U=ye.naturalHeight||ke.height,W=me/U,Q=ke.width/ke.height;let V,fe;return W>Q?(V=ke.width,fe=ke.width/W):(fe=ke.height,V=ke.height*W),{dnx:oe/V,dny:Se/fe}},ae=(oe,Se,ye)=>{if(ye<=1.05)return;const ke=-(oe-.5)*100,me=-(Se-.5)*100,U=y(ke,me,ye);(Math.abs(U.x-u.current)>.1||Math.abs(U.y-c.current)>.1)&&(p(U.x),d(U.y),u.current=U.x,c.current=U.y)},O=oe=>{const Se=t.current;if(Se&&oe.target instanceof Node&&Se.contains(oe.target))oe.preventDefault();else return;if(oe.touches.length===1){const ye=oe.touches[0];b.current={x:ye.clientX,y:ye.clientY,time:Date.now()},C.current={x:ye.clientX,y:ye.clientY},B.current||(S.current=!1),M.current=setTimeout(()=>{if(!S.current&&!B.current)if(S.current=!0,z.current==="mouse"){const ke=k.current||{nx:.5,ny:.5};v("Right Click"),f(ke.nx,ke.ny,"right"),R.current("input_click",{...ke,button:"right"}).catch(()=>{})}else{const ke=ne(ye);ke&&(v("Right Click"),f(ke.nx,ke.ny,"right"),R.current("input_click",{...ke,button:"right"}).catch(()=>{}))}},500);return}if(oe.touches.length===2){M.current&&clearTimeout(M.current),S.current=!0,B.current=!0;const ye=oe.touches[1].clientX-oe.touches[0].clientX,ke=oe.touches[1].clientY-oe.touches[0].clientY;T.current=Math.sqrt(ye*ye+ke*ke),L.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}}},se=oe=>{const Se=t.current;if(Se&&oe.target instanceof Node&&Se.contains(oe.target)&&oe.preventDefault(),oe.touches.length===1&&C.current){const ye=oe.touches[0],ke=ye.clientX-C.current.x,me=ye.clientY-C.current.y;if(!S.current&&b.current){const U=ye.clientX-b.current.x,W=ye.clientY-b.current.y;Math.sqrt(U*U+W*W)>8&&(S.current=!0,M.current&&clearTimeout(M.current))}if(S.current)if(z.current==="mouse"){const U=ue(ke,me),W=k.current||{nx:.5,ny:.5},Q=Math.max(0,Math.min(1,W.nx+U.dnx)),V=Math.max(0,Math.min(1,W.ny+U.dny));k.current={nx:Q,ny:V},N({nx:Q,ny:V}),v(`Cursor: ${Math.round(Q*100)}%, ${Math.round(V*100)}%`),ae(Q,V,i.current);const fe=Date.now();fe-h.current>=30&&(h.current=fe,R.current("input_mouseMoved",{nx:Q,ny:V}).catch(()=>{}))}else if(i.current>1){const U=t.current;if(U){const W=U.clientWidth,Q=U.clientHeight,V=u.current+ke/W*100,fe=c.current+me/Q*100,ce=y(V,fe,i.current);p(ce.x),d(ce.y),u.current=ce.x,c.current=ce.y}}else{const U=ne(ye);if(U){const W=Date.now();W-h.current>=40&&(h.current=W,v("Scroll"),R.current("input_wheel",{nx:U.nx,ny:U.ny,deltaX:Math.round(-ke*2.5),deltaY:Math.round(-me*2.5)}).catch(()=>{}))}}C.current={x:ye.clientX,y:ye.clientY};return}if(oe.touches.length===2&&T.current!==null){const ye=oe.touches[1].clientX-oe.touches[0].clientX,ke=oe.touches[1].clientY-oe.touches[0].clientY,U=Math.sqrt(ye*ye+ke*ke)/T.current,W=(oe.touches[0].clientX+oe.touches[1].clientX)/2,Q=(oe.touches[0].clientY+oe.touches[1].clientY)/2,V=W-P.current.x,fe=Q-P.current.y,ce=Math.abs(U-1)>.03;if(z.current==="mouse"){if(ce){const F=Math.max(o,Math.min(5,L.current*U));m(F),i.current=F}else if(Math.abs(V)>2||Math.abs(fe)>2){const F=k.current||{nx:.5,ny:.5},le=Date.now();le-h.current>=30&&(h.current=le,v("Scroll"),R.current("input_wheel",{nx:F.nx,ny:F.ny,deltaX:Math.round(-V*3),deltaY:Math.round(-fe*3)}).catch(()=>{}))}}else{const F=Math.max(o,Math.min(5,L.current*U));m(F),i.current=F;const le=t.current;if(le&&F>1){const je=le.clientWidth,de=le.clientHeight,H=u.current+V/je*100,be=c.current+fe/de*100,Ne=y(H,be,F);p(Ne.x),d(Ne.y),u.current=Ne.x,c.current=Ne.y}}P.current={x:W,y:Q}}},X=oe=>{var Se;if(M.current&&clearTimeout(M.current),T.current=null,oe.touches.length===1&&B.current){const ye=oe.touches[0];b.current={x:ye.clientX,y:ye.clientY,time:Date.now()},C.current={x:ye.clientX,y:ye.clientY},S.current=!0;return}if(oe.touches.length===0){if(B.current){B.current=!1,S.current=!1;return}if(oe.changedTouches.length===1){const ye=oe.changedTouches[0],ke=Date.now(),me=ke-(((Se=b.current)==null?void 0:Se.time)||0),U=b.current?ye.clientX-b.current.x:0,W=b.current?ye.clientY-b.current.y:0,Q=Math.sqrt(U*U+W*W);if(z.current==="mouse"){if(me<_||me>K||Q>E){S.current=!1;return}const V=k.current||ne(ye);V&&(v(`Click: ${Math.round(V.nx*100)}%, ${Math.round(V.ny*100)}%`),f(V.nx,V.ny,"left"),R.current("input_click",{...V}).catch(()=>{}))}else{if(S.current){S.current=!1;return}if(me<D||me>$||Q>I){S.current=!1;return}const V=ne(ye);if(!V)return;ke-A.current<300?(v("Double tap"),f(V.nx,V.ny,"double"),R.current("input_click",{...V,clickCount:2}).catch(()=>{}),A.current=0):(v(`Tap: ${Math.round(V.nx*100)}%, ${Math.round(V.ny*100)}%`),f(V.nx,V.ny,"left"),R.current("input_click",{...V}).catch(()=>{}),A.current=ke)}}S.current=!1}};return q.addEventListener("touchstart",O,{passive:!1}),q.addEventListener("touchmove",se,{passive:!1}),q.addEventListener("touchend",X,{passive:!1}),()=>{q.removeEventListener("touchstart",O),q.removeEventListener("touchmove",se),q.removeEventListener("touchend",X),M.current&&clearTimeout(M.current)}},[e,t,n,o,i,u,c,p,d,m,h,v,f,y]),{cursorPos:w,cursorPosRef:k,handleToggleInputMode:()=>{a(q=>{const ne=q==="touch"?"mouse":"touch";return ne==="mouse"&&G(),ne})},handleZoomReset:()=>{const q=j?x:1;m(q),i.current=q,p(0),d(0),u.current=0,c.current=0}}}function iu({onAction:e,addLog:t,connState:n,connScreenshot:r,screenshotUsage:a,transportType:o}){const i=l.useRef(null),u=l.useRef(null),c=l.useRef(null),[p,d]=l.useState(null),[m,h]=l.useState(""),[,g]=l.useState(!1),[v,f]=l.useState([]),y=l.useRef(0),[j,x]=l.useState(!1),[w,N]=l.useState(!1),k=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[b,C]=l.useState(k?"mouse":"touch"),[S,M]=l.useState(1),A=l.useRef(!1),[T,L]=l.useState(1),[P,B]=l.useState(0),[z,R]=l.useState(0);mr("RemoteView",{connState:n,hasScreenshot:!!r,inputMode:b,zoom:T,panX:P,panY:z,isMenuOpen:j,isImeOpen:w});const _=l.useRef(0),K=l.useRef(T),E=l.useRef(P),D=l.useRef(z);l.useEffect(()=>{K.current=T},[T]),l.useEffect(()=>{E.current=P},[P]),l.useEffect(()=>{D.current=z},[z]),l.useEffect(()=>{var me;(me=i.current)==null||me.focus()},[]);const $=n==="connected",I=r,G=$?"Connected. Waiting for first frame...":n==="connecting"?"Connecting to Host...":"Reconnecting to Host...",Y=$?"The remote stream is warming up":"Waiting for the remote stream to catch up";l.useEffect(()=>{if(!k||A.current||!I)return;const me=c.current,U=u.current;if(!me||!U)return;const W=()=>{const Q=U.clientWidth,V=U.clientHeight,fe=me.naturalWidth,ce=me.naturalHeight;if(!fe||!ce||!Q||!V)return;const F=Math.min(Q/fe,V/ce),je=Math.max(Q/fe,V/ce)/F;je>1.01&&(M(je),L(je),K.current=je),A.current=!0};me.complete&&me.naturalWidth?W():me.addEventListener("load",W,{once:!0})},[I,k]);const Z=.5;l.useEffect(()=>{T<=Z&&(B(0),R(0))},[T,Z]);const q=(me,U,W)=>{if(W<=Z)return{x:0,y:0};const Q=(W-1)/(2*W)*100,V=(W-1)/(2*W)*100;return{x:Math.max(-Q,Math.min(Q,me)),y:Math.max(-V,Math.min(V,U))}},ne=(me,U)=>{if(!c.current)return null;const W=c.current.getBoundingClientRect();return!W.width||!W.height?null:{nx:Math.max(0,Math.min(1,(me-W.left)/W.width)),ny:Math.max(0,Math.min(1,(U-W.top)/W.height))}},ue=(me,U,W)=>{const Q=u.current;if(!Q)return;const V=Q.getBoundingClientRect(),fe=++y.current;f(ce=>[...ce,{id:fe,x:me-V.left,y:U-V.top,type:W}]),setTimeout(()=>f(ce=>ce.filter(F=>F.id!==fe)),600)},ae=(me,U,W)=>{const Q=c.current,V=u.current;if(!Q||!V)return;const fe=Q.getBoundingClientRect(),ce=V.getBoundingClientRect(),F=Q.naturalWidth||fe.width,le=Q.naturalHeight||fe.height,je=F/le,de=fe.width/fe.height;let H,be,Ne,Ce;je>de?(H=fe.width,be=fe.width/je,Ne=0,Ce=(fe.height-be)/2):(be=fe.height,H=fe.height*je,Ne=(fe.width-H)/2,Ce=0);const $e=fe.left-ce.left+Ne+H*me,Qe=fe.top-ce.top+Ce+be*U,dt=++y.current;f(it=>[...it,{id:dt,x:$e,y:Qe,type:W}]),setTimeout(()=>f(it=>it.filter(he=>he.id!==dt)),600)},O=async me=>{var W;const U=ne(me.clientX,me.clientY);if(U){d(`Click: ${Math.round(U.nx*100)}%, ${Math.round(U.ny*100)}%`),ue(me.clientX,me.clientY,"left"),(W=i.current)==null||W.focus();try{const Q=await e("input_click",{nx:U.nx,ny:U.ny});Q!=null&&Q.success||t(`❌ Click failed: ${Q==null?void 0:Q.error}`)}catch(Q){t(`❌ Click error: ${Q.message||Q}`)}}},se=async(me,U,W,Q=0)=>{try{await e("input_key",{type:W?"char":"keyDown",key:me,code:U,text:W?me:void 0,unmodifiedText:W?me:void 0,modifiers:Q})}catch(V){t(`❌ Key error: ${V.message||V}`)}},X=async me=>{if(me.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(me.key)&&me.preventDefault();let W=0;me.altKey&&(W|=1),me.ctrlKey&&(W|=2),me.metaKey&&(W|=4),me.shiftKey&&(W|=8),d(`Key: ${me.key}`),await se(me.key,me.code,me.key.length===1,W)},oe=async me=>{if(me.key==="Enter"){if(me.nativeEvent.isComposing)return;if(m){const U=m;h(""),d(`IME Sent: ${U}`);try{const W=await e("input_type",{text:U});W!=null&&W.success||t(`❌ IME error: ${W==null?void 0:W.error}`)}catch(W){t(`❌ IME error: ${W.message}`)}}else d("Key: Enter"),await se("Enter","Enter",!1)}};l.useEffect(()=>{const me=i.current;if(!me)return;const U=W=>{var Q;if((Q=c.current)!=null&&Q.contains(W.target)){W.preventDefault();const V=Date.now();if(V-_.current<40)return;_.current=V;const fe=ne(W.clientX,W.clientY);if(!fe)return;d(`Scroll: ${Math.round(W.deltaY)}`),e("input_wheel",{nx:fe.nx,ny:fe.ny,deltaX:Math.round(W.deltaX),deltaY:Math.round(W.deltaY)}).catch(()=>{})}};return me.addEventListener("wheel",U,{passive:!1}),()=>me.removeEventListener("wheel",U)},[e]);const{cursorPos:Se,handleToggleInputMode:ye,handleZoomReset:ke}=Nx({containerRef:i,viewportRef:u,imgRef:c,inputMode:b,setInputMode:C,minZoom:Z,zoomRef:K,panXRef:E,panYRef:D,setPanX:B,setPanY:R,setZoom:L,lastWheelTimeRef:_,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:ae,clampPan:q,isMobile:k,mobileFillZoom:S});return s.jsxs("div",{ref:i,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:X,onContextMenu:me=>me.preventDefault(),onFocus:()=>g(!0),onBlur:()=>g(!1),tabIndex:0,children:[s.jsxs("div",{ref:u,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[I?s.jsx("img",{ref:c,src:I,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${T}) translate(${P}%, ${z}%)`,transformOrigin:"center center",cursor:b==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:O,onContextMenu:me=>me.preventDefault(),onDragStart:me=>me.preventDefault()}):s.jsx(jx,{waitingLabel:G,waitingHint:Y,transportType:o}),b==="mouse"&&I&&s.jsx(wx,{cursorPos:Se,viewportRef:u,imgRef:c}),v.map(me=>{const W={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(${W}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),s.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${W}, 0.9)`,boxShadow:`0 0 12px rgba(${W}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},me.id)})]}),s.jsx(kx,{inputMode:b,onToggleInputMode:ye,isImeOpen:w,setIsImeOpen:N,isMenuOpen:j,setIsMenuOpen:x,imeText:m,setImeText:h,handleImeSubmit:oe,isConnActive:$,zoom:T,isMobile:k,mobileFillZoom:S,onZoomOut:()=>L(me=>Math.max(.5,me-.25)),onZoomReset:ke,onZoomIn:()=>L(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 Bl(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 Cx(e){var t;return Bl(e.activeInteractivePrompt)||Bl((t=e.activeChat)==null?void 0:t.activeInteractivePrompt)}function Mx(e){return e.sessionId||e.instanceId||e.id}function Ax(e,t){const n=typeof t=="string"?t.trim():"";for(const r of e){const a=Cx(r);if(!a)continue;const o=Mx(r);if(n&&n!==o&&n!==r.id)continue;return{daemonId:r.daemonId||r.id.split(":")[0]||r.id,sessionId:o,routeId:r.id,providerType:r.type,title:r.title||r.cliName||r.type,prompt:a}}return null}function lu(e,t){var r;const n={};for(const a of e.questions){const o=t[a.questionId]||{},i=Array.from(new Set((o.selectedLabels||[]).map(c=>c.trim()).filter(Boolean))),u=(r=o.freeformText)==null?void 0:r.trim();n[a.questionId]={selectedLabels:i,...u?{freeformText:u}:{}}}return{promptId:e.promptId,answers:n}}const Ix=200;function Hl(e){const t={};for(const n of(e==null?void 0:e.prompt.questions)||[])t[n.questionId]={selectedLabels:[],freeformText:""};return t}function Ol(e,t){var n,r;return!!((n=t==null?void 0:t.freeformText)!=null&&n.trim())||(((r=t==null?void 0:t.selectedLabels)==null?void 0:r.length)||0)>0||e.options.length===0&&e.allowFreeform}function Tx({label:e,description:t,selected:n,multiSelect:r,disabled:a,onClick:o}){return s.jsx("button",{type:"button",disabled:a,role:r?"checkbox":"radio","aria-checked":n,onClick:o,className:`w-full text-left rounded-md border px-3 py-2 transition ${n?"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 ${r?"rounded-sm":"rounded-full"} ${n?"border-accent-primary bg-accent-primary text-accent-on-primary":"border-border-subtle"}`,children:n?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:n,onSubmit:r,onCancel:a}){var A;const[o,i]=l.useState(()=>Hl(e)),[u,c]=l.useState(0),[p,d]=l.useState(!1),m=l.useRef(!1);l.useEffect(()=>{if(i(Hl(e)),c(0),d(!1),m.current=!1,!(e==null?void 0:e.prompt.promptId))return;const L=setTimeout(()=>{m.current=!0,d(!0)},Ix);return()=>clearTimeout(L)},[e==null?void 0:e.prompt.promptId]);const h=(e==null?void 0:e.prompt.questions)||[],g=h.length,v=u===g-1,f=g===1,y=h[u],j=y?o[y.questionId]:void 0,x=y?Ol(y,j):!1,w=l.useMemo(()=>e?e.prompt.questions.every(T=>Ol(T,o[T.questionId])):!1,[e,o]);if(!e)return null;const N=(T,L)=>{i(P=>{const B=P[T.questionId]||{selectedLabels:[]},z=B.selectedLabels||[],R=T.multiSelect?z.includes(L)?z.filter(_=>_!==L):[...z,L]:[L];return{...P,[T.questionId]:{...B,selectedLabels:R}}})},k=(T,L)=>{i(P=>({...P,[T]:{...P[T]||{selectedLabels:[]},freeformText:L}}))},b=()=>{u<g-1&&c(T=>T+1)},C=()=>{u>0&&c(T=>T-1)},S=()=>{!w||t||!m.current||r(o)},M=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:[u+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(Mt,{size:16})})]})]}),!f&&s.jsx("div",{className:"flex shrink-0 gap-1.5 px-5 pt-3",children:h.map((T,L)=>s.jsx("div",{className:`h-1.5 flex-1 rounded-full transition-colors ${L<u?"bg-accent-primary":L===u?"bg-accent-primary/60":"bg-border-default"}`},T.questionId))}),s.jsxs("div",{className:"min-h-0 flex-1 space-y-4 overflow-y-auto px-5 py-4",children:[y&&s.jsxs("section",{className:"space-y-3",children:[s.jsxs("div",{children:[y.header&&s.jsx("div",{className:"mb-1 text-xs font-semibold uppercase tracking-normal text-text-muted",children:y.header}),s.jsxs("div",{className:"text-sm font-semibold text-text-primary",children:[f?"":`${u+1}. `,y.question]}),y.multiSelect&&y.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:y.multiSelect?"group":"radiogroup","aria-label":y.question,children:y.options.map(T=>{var L;return s.jsx(Tx,{label:T.label,description:T.description||T.preview,selected:(((L=M.answers[y.questionId])==null?void 0:L.selectedLabels)||[]).includes(T.label),multiSelect:y.multiSelect,disabled:t,onClick:()=>N(y,T.label)},T.label)})}),y.allowFreeform&&s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-xs font-semibold text-text-muted",children:"Other"}),s.jsx("textarea",{value:((A=o[y.questionId])==null?void 0:A.freeformText)||"",disabled:t,onChange:T=>k(y.questionId,T.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"})]})]}),n&&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:n})]}),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&&u>0&&s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:C,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||v?s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:S,disabled:!w||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:n="",nowLabel:r="now",nowThreshold:a=60}=t,o=Date.now()-e,i=Math.floor(o/1e3);if(i<a)return r;const u=Math.floor(i/60);if(u<60)return`${u}m${n}`;const c=Math.floor(u/60);if(c<24)return`${c}h${n}`;const p=Math.floor(c/24);return p<7?`${p}d${n}`:new Date(e).toLocaleDateString()}const du=e=>Sa(e);function Px(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 Mn(e){const t=e.connectionState==="failed"||e.connectionState==="closed",n=e.connectionState==="connecting"||e.connectionState==="new",r=e.status==="generating"||e.status==="no_progress"||e.status==="long_generating"||e.status==="streaming",a=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:n,isGenerating:r,isWaiting:a}}function uu(e){const t=new Map,n=(r,a)=>{r&&t.set(r,{sessionId:r,...Px(a)})};for(const r of e)if(r.type!=="adhdev-daemon"){n(r.sessionId,r);for(const a of r.childSessions||[])n(a.id,a)}return t}function Ps(e,t){if(e.sessionId){const n=t.get(e.sessionId);if(n)return n}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1,muted:!1,completionMarker:"",seenCompletionMarker:""}}function Na(e,t,n){const r=Ps(e,t),a=Mn(e),o=a.isReconnecting,i=a.isConnecting,u=a.isGenerating,c=a.isWaiting,p=r.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||c,d=r.inboxBucket==="working"||u,h=!!(r.inboxBucket==="task_complete"&&r.unread&&!(n!=null&&n.hideOpenTaskCompleteUnread&&(n!=null&&n.isOpenConversation)));return{unread:h,requiresAction:p,isWorking:d,isReconnecting:o,isConnecting:i,isGenerating:u,isWaiting:c,inboxBucket:p?"needs_attention":d?"working":h?"task_complete":"idle"}}function Dx(e,t,n){return Na(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:n==null?void 0:n.isOpenConversation}).unread}function pu({activeConv:e,onModalButton:t}){const{t:n}=Xe(),[r,a]=l.useState(null);if(l.useEffect(()=>{a(null)},[e.modalMessage,e.status,e.connectionState]),!Mn(e).isWaiting||!e.modalButtons)return null;const i=c=>{r||(a(c),t(c))},u=c=>c.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return s.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&s.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:e.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[s.jsx(Ys,{size:14})," ",n(r?"approval.processing":"approval.actionRequired")]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((c,p)=>{const d=u(c).toLowerCase(),m=/^(run|approve|accept|yes|allow|always)/.test(d),h=/^(reject|deny|delete|remove|abort)/.test(d),g=r===c,v=r!==null;return s.jsx("button",{onClick:()=>i(c),disabled:v,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"} ${v&&!g?"opacity-40":"opacity-100"} ${v?"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?"⏳ ...":u(c)},p)})})]})]})}const Di="adhdev_controls_bar_visible",Go="adhdev:controlsbarvisibilitychange";function Va(e){if(!e)return!1;try{return e.getItem(Di)==="1"}catch{return!1}}function Lx(e,t){if(t)try{t.setItem(Di,e?"1":"0")}catch{}}function Rx(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Go,{detail:{visible:e}}))}function Li(){const[e,t]=l.useState(()=>typeof window>"u"?!1:Va(window.localStorage)),n=l.useRef(e),r=l.useCallback((i,u=!0)=>{n.current=i,t(i),typeof window<"u"&&Lx(i,window.localStorage),u&&Rx(i)},[]);l.useEffect(()=>{const i=c=>{const p=c.detail,d=typeof(p==null?void 0:p.visible)=="boolean"?p.visible:Va(window.localStorage);n.current=d,t(d)},u=c=>{if(c.key!==Di)return;const p=Va(window.localStorage);n.current=p,t(p)};return window.addEventListener(Go,i),window.addEventListener("storage",u),()=>{window.removeEventListener(Go,i),window.removeEventListener("storage",u)}},[]);const a=l.useCallback(i=>{r(i)},[r]),o=l.useCallback(()=>{r(!n.current)},[r]);return{isVisible:e,setVisibility:a,toggleVisibility:o}}const hu=["en","ko","ja","zh-CN","es"],Xn="en",qa=[{code:"en",label:"English"},{code:"ko",label:"한국어"},{code:"ja",label:"日本語"},{code:"zh-CN",label:"中文(简体)"},{code:"es",label:"Español"}];function un(e){return typeof e=="string"&&hu.includes(e)}function _x(e){if(!e)return Xn;const t=e.trim().toLowerCase();if(!t)return Xn;if(t==="zh"||t.startsWith("zh-")||t.startsWith("zh_"))return"zh-CN";const n=t.split(/[-_]/)[0];return n==="en"?"en":n==="ko"?"ko":n==="ja"?"ja":n==="es"?"es":Xn}const Ex={label:"Language",select:"Select language"},$x={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"},Bx={label:{success:"Done",warning:"Attention",info:"Update"},dismiss:"Dismiss"},Hx={actionNeeded:"Action needed",taskComplete:"Task complete",markRead:"Mark read",markUnread:"Mark unread",delete:"Delete"},Ox={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"},Wx={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"},Kx={processing:"PROCESSING...",actionRequired:"ACTION REQUIRED"},Gx={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"},zx={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)"},Vx={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"},panel:{selectNode:"Select a node to view details.",submoduleBadge:"Submodule",dirtyBadge:"Dirty",outOfSyncBadge:"Out of sync",conflictBadge:"Conflict",orphanBadge:"Orphan",fieldWorkspace:"Workspace",fieldBranch:"Branch",fieldUpstream:"Upstream",fieldUpstreamState:"Upstream state",fieldHead:"HEAD",fieldSubmodulePath:"Submodule path",fieldSubmoduleCommit:"Submodule commit",fieldParentNode:"Parent node",fieldAhead:"Ahead",fieldBehind:"Behind",fieldDirtyFiles:"Dirty files",fieldActiveSessions:"Active sessions",fieldProviders:"Providers",fieldConnection:"Connection",fieldLinkNote:"Link note",fieldError:"Error",orphanReasons:"Orphan reasons",attachedChats:"Attached chats",providerUnknown:"provider unknown",statusAwaiting:"awaiting approval",statusGenerating:"generating",statusIdle:"idle",statusCoordinator:"coordinator",statusWorker:"worker",runtimeAgeNotReported:"runtime age not reported",upstreamVerified:"verified",upstreamUnverifiedFetch:"unverified (fetch failed)",upstreamUnverified:"unverified",upstreamUnavailable:"unavailable",needsFollowUp:"needs follow-up",refined:"refined"},obs:{tabOverview:"Overview",tabStatus:"Status",tabGraph:"Graph",convergenceMergedToMain:"Merged to main",convergenceNeedsMerge:"Needs merge",convergenceBlockedReview:"Blocked — needs review",convergenceCleanup:"Ready to clean up",convergenceNotMergeable:"Not mergeable",followUpLabel:"Follow-up — {{status}}",selectedNode:"Selected node",selectedEdge:"Selected edge",activeSessions:"Active Sessions",ledger:"Ledger (mesh-wide)",queueTasks:"Queue tasks",keyWarning:"Key warning",healResult:"Heal result",healPreview:"Heal preview",noResultCode:"No result code returned.",health:"Health",legend:"Legend",checking:"Checking",heal:"Heal",loadingGraph:"Loading graph…",bootstrapBanner:"Awaiting live data — showing setup inventory until peer mesh_status probes succeed.",emptyGraph:"No live mesh graph is available for this coordinator yet.",fieldMachine:"Machine",fieldLocality:"Locality",fieldWorkspace:"Workspace",fieldHead:"HEAD",fieldDirtyAheadBehind:"Dirty/ahead/behind",fieldSessions:"Sessions",fieldUpstream:"Upstream",fieldSource:"Source",fieldTransport:"Transport",fieldMachineId:"Machine id",fieldDaemonId:"Daemon id",fieldFrom:"From",fieldTo:"To",fieldLabel:"Label",fieldCompleted:"Completed",fieldFailed:"Failed",fieldLaunched:"Launched",fieldRecentFailures:"Recent failures",meshConnecting:"mesh connecting...",connecting:"connecting...",providerUnknown:"provider unknown"}},qx={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",remoteUrl:"Repo remote URL (optional)",remoteUrlHint:"Provide a remote URL OR a stable identity.",repoIdentity:"Repo identity (optional)",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 →",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.)",titleNoCount:"Nodes & Providers",workspacesDetected:"{{count}} workspace(s) detected",pickFromSaved:"← Pick from saved workspaces",ownerMachine:"Owner: {{owner}} · Machine: {{machine}}"},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.",online:"online",offline:"offline",noCommandTarget:"No command target available — bring the host or a daemon online.",pickHostFirst:"Pick a host daemon (or wait for the host pin to resolve) first.",attachNodeFirst:"Attach a workspace from this daemon as a node first."},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)",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)",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"}},Yx={copyMessage:"Copy message"},Jx={connectingToMachine:"Connecting to your machine",establishingP2P:"Establishing P2P connection",agentNotMonitored:"Agent not monitored",clickToSwitchMonitoring:"Click to switch monitoring to this agent",agentPanelHidden:"Agent panel is not visible yet",openPanelHint:"Open the agent panel or chat view in the app you are using to start viewing messages",noMessagesYet:"No messages yet",loadingChat:"Loading chat...",openPanel:"Open {{label}} Panel",switchingPanel:"Switching...",openingPanel:"Opening..."},Xx={attachImage:"Attach image",placeholder:"Send message to {{panel}}... (Shift+Enter for newline)",sendMessage:"Send message",dropImage:"Drop image here"},Qx={noConversations:"No conversations yet",waitingForDaemon:"Waiting for your daemon",connectYourMachines:"Connect your machines",daemonDescription:"Start the ADHDev daemon to connect this dashboard. Once it is online, you can launch sessions with any installed provider.",installDescription:"Install ADHDev on a machine, sign in, and it will show up here.",newSession:"New session",newSessionDescription:"A connected machine is ready. Start a new session with any installed provider — CLI, ACP, or IDE."},Zx={loadOlderOutput:"Load older terminal output",loadingOlder:"Loading older...",debug:"Debug",copy:"Copy",openControlKeys:"Open terminal control keys",closeControlKeys:"Close terminal control keys"},eb={muteThis:"Mute this chat",unmuteThis:"Unmute this chat",mutedTitle:"Muted — notifications silenced. Click to unmute.",muteTitle:"Mute notifications for this chat"},tb={switchToTerminal:"Switch to Terminal view",switchToChat:"Switch to Chat view"},sb={resumeSavedHistory:"Resume saved history",startFresh:"Start fresh",resumingSavedHistory:"Resuming saved history…",startingFresh:"Starting fresh…",startIde:"Start IDE",startingIde:"Starting IDE…",startAcpSession:"Start ACP session",startingAcpSession:"Starting ACP session…",recoverHostedRuntime:"Recover hosted runtime",hostedRuntimeRecoveryDescription:"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead.",openSavedHistory:"Open saved history",savedHistoryTitle:"Saved History",savedHistoryHelper:"Use saved history when you want continuity in the same provider conversation.",savedHistoryEmpty:"No saved history found yet.",refreshSavedHistory:"Refresh saved history",refreshingSavedHistory:"Refreshing saved history…",startFreshWith:"Start fresh with {{label}}?",restart:"Restart {{label}}?",startFreshReview:"Review the provider and target folder before starting fresh.",restartIdeReview:"Review or change the target workspace before restarting this IDE.",restartStoppedReview:"Review or change the target workspace before restarting this stopped session.",confirmStartFresh:"Start fresh",confirmRestart:"Restart",confirmStartingFresh:"Starting fresh…",confirmRestarting:"Restarting…",resumeWith:"Resume saved history with {{label}}?",resumeReview:"Review or change the target workspace before resuming saved history."},nb={nav:{dashboard:"Dashboard",settings:"Settings",docs:"Docs",about:"About"},layout:{expandSidebar:"Expand sidebar",collapseSidebar:"Collapse sidebar",collapse:"Collapse"},auth:{loading:"Loading standalone dashboard…",loadError:"Failed to load standalone auth status: {{error}}",signInTitle:"Standalone sign-in",passwordProtected:"This self-hosted dashboard is protected by a local password.",tokenProtected:"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session.",passwordPlaceholder:"Enter standalone password",unlock:"Unlock dashboard",signingIn:"Signing in…",noPasswordEnabled:"Password login is not enabled on this server."},machine:{loading:"⏳ Loading machine...",awaitingInput:"Awaiting your input ↑"},settings:{title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",infoNotice:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint.",publicHostWarning:"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.",daemonSection:"Daemon",daemonDescription:"Connection health and local endpoints for the self-hosted runtime.",versionLabel:"Version",statusLabel:"Status",statusRunning:"● Running",statusNotConnected:"○ Not connected",currentBindLabel:"Current bind",defaultBindLabel:"Default bind",authLabel:"Auth",authPassword:"Password enabled",authToken:"Token enabled",authNone:"No auth configured",networkSection:"Network Access",networkDescription:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",networkHint:"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.",localhostLabel:"Localhost only",localhostHint:"Bind to 127.0.0.1. Best when only this machine should open the dashboard.",allInterfacesLabel:"All interfaces",allInterfacesHint:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points.",saveNetworkMode:"Save default network mode",saving:"Saving…",networkRestartHint:"Applies on next standalone restart. Current run stays bound to {{host}}.",networkSavedAll:"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.",networkSavedLocal:"Default standalone network mode set to localhost only. Restart standalone to apply it.",securitySection:"Dashboard Security",securityDescription:"Self-hosted-only password protection for browsers using this standalone dashboard.",passwordSet:"A local password is currently required for browser access. Existing sessions are rotated when you change it.",passwordNotSet:"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended.",currentPasswordPlaceholder:"Current password",currentPasswordFirstTimePlaceholder:"Current password (not needed for first setup)",newPasswordPlaceholder:"New password",newPasswordFirstTimePlaceholder:"New standalone password",confirmPasswordPlaceholder:"Confirm new password",updatePassword:"Update password",enablePassword:"Enable password",disablePassword:"Disable password",passwordUpdated:"Standalone password updated.",passwordEnabled:"Standalone password enabled.",passwordDisabled:"Standalone password disabled.",passwordTooShort:"Password must be at least 4 characters.",passwordMismatch:"New password and confirmation do not match.",detectedIdesSection:"Detected IDEs",detectedIdesDescription:"Editors discovered by the local daemon on this machine.",noIdesDetected:"No IDEs detected. Start an IDE to see it here.",machineSection:"Machine",machineDescription:"The local burrow exposed by your standalone daemon.",daemonNotConnected:"Daemon not connected. Run 'adhdev-standalone' to start.",appearanceSection:"Appearance",appearanceDescription:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",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.",fontsLabel:"Fonts",fontsDescription:"Standalone-only typography overrides for chat text, markdown code, and terminal output.",fontsSaved:"Standalone chat fonts saved for this self-hosted dashboard.",notificationsSection:"Notifications",notificationsDescription:"Browser prompts and local sound cues for agent activity.",soundEffectsLabel:"Sound Effects",soundEffectsDescription:"Play a sound when agent completes or needs approval",profileSection:"Profile",profileDescription:"How your name appears in local chat threads and dashboard views.",displayNameLabel:"Display Name",displayNameHint:"Your name shown in chat threads and on the team dashboard.",displayNamePlaceholder:"Anonymous"},onboarding:{title:"Welcome to ADHDev",selectedCount_one:"{{count}} provider selected",selectedCount_other:"{{count}} providers selected",skip:"Skip",installing:"Installing…",done:"Done",installCount:"Install {{count}}",intro:"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 Burrow → Providers → Add provider.",loadingRegistry:"Loading registry…",loadError:"Failed to load registry: {{error}}",noProviders:"No providers in this category.",installed:"✓ installed",installFailed:"✗ {{error}}"},about:{title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",selfHostedEdition:"Self-hosted edition",headline:"Keep the same dashboard experience, with the runtime fully on-device.",description:"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.",docs:"Docs ↗",github:"GitHub ↗",tryCloud:"Try Cloud ↗",includedSection:"Included in standalone",includedDescription:"The local-first feature set available without the cloud control plane.",inventorySection:"Built-in inventory",inventoryDescription:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",cloudExtrasSection:"Cloud-only extras",cloudExtrasDescription:"Capabilities that need the hosted control plane or team infrastructure.",comparisonSection:"Self-hosted vs Cloud",comparisonDescription:"The product split at a glance.",featureHeader:"Feature",selfhostHeader:"Selfhost",cloudHeader:"Cloud",cloudOptional:"Cloud is optional, not required",cloudOptionalDescription:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",compareCloud:"Compare Cloud ↗",discord:"Discord ↗"},fonts:{fontOverridesNotice:"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.",chat:"Chat text",chatDescription:"Assistant/user prose, markdown text, thought cards, and system notes.",code:"Code blocks",codeDescription:"Markdown code fences, inline code, and preformatted command output.",terminal:"Terminal",terminalDescription:"Terminal transcript cards and tool/command rows in chat mode.",livePreview:"Live preview",resolvedStack:"Resolved stack:",defaults:"Defaults:",saveFontSettings:"Save font settings",revertToSaved:"Revert to saved",resetToDefaults:"Reset to defaults",saving:"Saving…"}},rb={login:{eyebrow:"Cloud sign-in",title:"Sign in to ADHDev",subtitle:"Connect your machines, get approval and completion notifications, and keep your coding agents moving when you are away from your desk.",continueWith:"Continue with {{provider}}",connecting:"Connecting...",devDivider:"dev",devLogin:"Dev Login (test_jwt_token)",providerNote:"GitHub and Google are used only for authentication.",errorUnverifiedEmail:"This login provider did not return a verified email, so we could not safely sign you in.",termsPrefix:"By continuing, you agree to our ",termsLink:"Terms of Service",termsAnd:" and ",privacyLink:"Privacy Policy",termsSuffix:"."},account:{title:"Account",subtitle:"Profile, plan & activity",tabAccount:"Account",tabBilling:"Billing",tabActivity:"Activity",profile:"Profile",noName:"No name",displayName:"Display Name",displayNameDesc:"Your name shown in the dashboard and team workspaces.",nicknamePlaceholder:"Nickname",save:"Save",saving:"...",cancel:"Cancel",saved:"Saved",edit:"Edit",failedToSave:"Failed to save",userId:"User ID",loadingProfile:"Loading profile...",planLimits:"Plan limits",limitMachines:"Machines",limitP2P:"P2P Connections",limitWebhooks:"Webhooks",limitTurnRelay:"TURN Relay",enabled:"Enabled",disabled:"Disabled",frozen:"Frozen",session:"Session",logout:"Logout",logoutConfirm:"Are you sure you want to logout?",logoutDesc:"Sign out of your ADHDev account on this device.",dangerZone:"Danger zone",dangerZoneDesc:"Permanently delete your account and all associated data. This action cannot be undone.",deleteAccount:"Delete account",deleteWillRemove:"This will permanently delete:",deleteItemProfile:"Your profile and login credentials",deleteItemKeys:"All API keys and connection tokens",deleteItemWebhooks:"Webhooks and delivery history",deleteItemPush:"Push notification subscriptions",deleteItemSessions:"Shared sessions and audit logs",deleteTypeConfirm:"Type {{keyword}} to confirm:",deleting:"Deleting...",permanentlyDelete:"Permanently delete",failedToDeleteAccount:"Failed to delete account",registeredMachines:"Registered Machines",machinesSummary:"{{count}} registered · {{online}} online",machinesLimit:"(limit: {{limit}})",loadingMachines:"Loading machines...",noMachinesRegistered:"No machines registered",runSetupPrefix:"Run ",runSetupMiddle:", then start ",runSetupSuffix:" on a machine to register it here.",removeMachineConfirm:"Remove this machine? It will need to run `adhdev setup` again to reconnect.",failedToDeleteMachine:"Failed to delete machine",failedToUpdate:"Failed to update",rename:"Rename",online:"Online",connecting:"Connecting",lastSeen:"Last seen {{time}}",removeMachine:"Remove machine",never:"Never",justNow:"Just now",minutesAgo:"{{minutes}}m ago",hoursAgo:"{{hours}}h ago",daysAgo:"{{days}}d ago"},billing:{currentPlan:"Current Plan:",statusTrial:"Trial",statusActive:"Active",statusPastDue:"Past Due",statusCanceled:"Canceled",nextBilling:"Next billing: {{date}}",trialEnds:"Trial ends: {{date}}",accessUntil:"Access until: {{date}}",updatePayment:"Please update your payment method",managePayment:"Manage Payment & Invoices",couldNotOpenPortal:"Could not open billing portal",statMachines:"Machines",statTeam:"Team",statTurnPerDay:"TURN min/day",monthly:"Monthly",yearly:"Yearly",savePercent:"Save 17%",paddleLoading:"Paddle is loading, please try again.",cancelConfirm:"Are you sure you want to cancel your subscription? You will retain access until the end of your billing period.",teamSeats:"Team Seats",seatsUsed:"{{used}} / {{total}} seats used",pricePerMonth:"${{price}}/mo",cannotReduceSeats:"Cannot reduce below {{count}} seats (currently in use). Remove members first.",removeSeat:"− Remove Seat",addSeat:"+ Add Seat",cancelSubscription:"Cancel Subscription",cancelRetainAccess:"You will retain access to {{plan}} features until the end of your current billing period.",cancelTeamDowngrade:" All team members will be downgraded to their personal plans."},activity:{filterPlaceholder:"Filter by action, resource, or source...",refresh:"Refresh",loading:"Loading...",noLogs:"No logs",noMatchingLogs:"No matching logs found.",logsWillAppear:"Actions will appear here as they happen.",colAction:"Action",colResource:"Resource",colSource:"Source",colTime:"Time",logCount:"{{count}} logs",logCountFiltered:" (filtered from {{total}})"},webhooks:{title:"Webhooks",subtitle:"Real-time event notifications",addWebhook:"+ Add Webhook",eventDaemonConnect:"Daemon Connected",eventDaemonDisconnect:"Daemon Disconnected",eventAgentStatus:"Agent Status Change",eventApprovalRequired:"Approval Required",failed:"Failed",deleteConfirm:"Delete this webhook?",testFailed:"Test failed",secretTitle:"Webhook Secret",secretShownOncePrefix:"Shown ",secretShownOnce:"only once",secretShownOnceSuffix:". Use to verify ",copy:"Copy",done:"Done",newWebhook:"New Webhook",labelUrl:"URL",urlPlaceholder:"https://your-service.com/webhook",labelEvents:"Events",allEvents:"All Events (*)",creating:"Creating...",create:"Create",cancel:"Cancel",loading:"Loading...",noWebhooks:"No webhooks",noWebhooksDesc:"Receive real-time notifications about events.",setupFirst:"Set up first webhook",off:"OFF",autoDisabled:"Auto-disabled",autoDisabledTitle:"Auto-disabled after 10 consecutive failures",failuresWarning:"⚠ {{count}} failures",failuresTitle:"{{count}} consecutive failures — will auto-disable at 10",all:"ALL",history:"History",test:"Test",delete:"Delete",deleting:"...",recentDeliveries:"Recent Deliveries",refresh:"Refresh",noDeliveries:"No deliveries yet. Use 🧪 to send a test.",request:"REQUEST",response:"RESPONSE",securityTitle:"Security",securityVerifyPrefix:"Verify ",securityVerifySuffix:" with your secret",securityHttps:"Use HTTPS endpoints only",securityAsync:"Return 2xx immediately, process async",securityAutoDisable:"Auto-disabled after 10 consecutive failures"},apiKeys:{title:"API Keys",keyCount:"{{count}} keys",playground:"Playground",create:"+ Create",scopeDaemonRead:"Daemon Read",scopeDaemonReadDesc:"List daemons & status",scopeDaemonControl:"Daemon Control",scopeDaemonControlDesc:"Commands, launch/stop, disconnect",scopeAgentRead:"Agent Read",scopeAgentReadDesc:"Status & chat history",scopeAgentControl:"Agent Control",scopeAgentControlDesc:"Send, approve/reject",scopeTerminal:"Terminal",scopeTerminalDesc:"Execute commands",scopeWebhooks:"Webhooks",scopeWebhooksDesc:"Manage hooks & deliveries",frozen:"Frozen",revokeConfirm:"Revoke this API key? This cannot be undone.",failedToLoad:"Failed to load",failed:"Failed",upgradePlan:"Upgrade your plan →",keyCreated:"Key Created!",copyNow:"Copy now — shown only once.",copied:"Copied",copy:"Copy",testKey:"Test",dismiss:"Dismiss",playgroundTitle:"API Playground",enterKeyToTest:"Enter an API key to test.",open:"Open",createKeyTitle:"Create API Key",labelName:"Name",namePlaceholder:"e.g. Production Bot",permissions:"Permissions ({{count}})",createBtn:"Create",cancel:"Cancel",loading:"Loading...",noKeys:"No API Keys",noKeysDesc:"Create a key to integrate with external services.",createFirstKey:"Create First Key",usedDate:"Used {{date}}",neverUsed:"Never used",revoke:"Revoke",usageLabel:"Usage:",apiReference:"API Reference →"},auditLogs:{title:"Audit Logs",subtitle:"Security events & API history",refresh:"Refresh",filterPlaceholder:"Filter by action, resource, or source...",loading:"Loading...",noLogs:"No logs",noMatchingLogs:"No matching logs found.",logsWillAppear:"Actions will appear here as they happen.",colAction:"Action",colResource:"Resource",colSource:"Source",colTime:"Time",logCount:"{{count}} logs",logCountFiltered:" (filtered from {{total}})"}},ab={chatHistory:"Chat History",startNewChat:"+ Start New Chat Session",creating:"⌛ Creating...",searchPlaceholder:"Search title or preview",filterWorkspace:"Filter by workspace",filterModel:"Filter by model",sortRecent:"Most recent",sortOldest:"Oldest first",sortMessages:"Most messages",resumeReadyOnly:"Resume-ready only",untitledSession:"Untitled Session",noSavedPreview:"No saved preview yet",workspaceUnknown:"Workspace unknown",selectedWorkspaceSuffix:" · selected workspace",msgCount:"{{count}} msgs",statusActive:"ACTIVE",statusMissingWorkspace:"MISSING WORKSPACE",statusResumeSelectedWorkspace:"RESUME IN SELECTED WORKSPACE",statusResuming:"RESUMING...",statusResume:"RESUME",noMatchingHistory:"No saved history matches these filters.",noRecentChats:"No recent chat sessions found.",refreshHistory:"Refresh History",refreshing:"⌛ Refreshing..."},ob={language:Ex,common:$x,connection:Fx,toast:Bx,notification:Hx,event:Ox,dashboard:Wx,cliStop:Ux,approval:Kx,newSession:Gx,mobileInbox:zx,meshGraph:Vx,repoMesh:qx,chat:Yx,chatPane:Jx,chatInput:Xx,paneGroup:Qx,terminal:Zx,conversation:eb,cliView:tb,launch:sb,standalone:nb,cloud:rb,historyModal:ab},ib={label:"언어",select:"언어 선택"},lb={cancel:"취소"},cb={disconnected:"연결 끊김",connected:"연결됨",connectedToDashboard:"대시보드에 연결됨",connectingToMachine:"머신에 연결 중...",networkOffline:"네트워크 오프라인",reconnecting:"재연결 중",sessionExpired:"세션이 만료되었습니다.",logInAgain:"다시 로그인",connectionFailed:"연결에 실패했습니다 — 페이지를 새로고침하거나 잠시 후 다시 시도하세요.",reconnectNow:"지금 재연결"},db={label:{success:"완료",warning:"주의",info:"업데이트"},dismiss:"닫기"},ub={actionNeeded:"조치 필요",taskComplete:"작업 완료",markRead:"읽음 표시",markUnread:"읽지 않음 표시",delete:"삭제"},pb={taskCompleted:"{{label}} 에이전트 작업 완료",taskCompletedWithDuration:"{{label}} 에이전트 작업 완료 ({{duration}}초)",approvalNeeded:"{{label}} 승인 필요",noProgress:"{{label}} 에이전트 진행 없음",noProgressWithDuration:"{{label}} 에이전트 진행 없음 ({{minutes}}분)",noProgressTitle:"{{label}} — 진행 없음",noProgressBody:"에이전트가 {{duration}} 넘게 진행이 없습니다",viewRequest:"{{requester}}님이 세션 보기를 요청합니다",viewRequestTitle:"보기 요청",viewRequestApproved:"보기 요청이 승인되었습니다",viewRequestDeclined:"{{target}}님이 보기 요청을 거절했습니다",someoneRequester:"팀 멤버",someoneTarget:"팀 멤버"},hb={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:"대기 중인 활동이 없습니다."}},mb={title:"{{agent}}을(를) 중지할까요?",gracefulDescription:"중지는 지원되는 경우 프로바이더에게 정상 종료를 요청합니다. 강제 중지는 런타임을 즉시 종료합니다.",forceOnlyDescription:"이 프로바이더는 정상 중지를 지원하지 않습니다. 강제 중지는 런타임을 즉시 종료합니다.",stop:"중지",forceStop:"강제 중지"},fb={processing:"처리 중...",actionRequired:"조치 필요"},xb={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:"Repo Mesh",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:"세션을 재개할 수 없습니다"},bb={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:"세션 중지 (에이전트를 종료합니다)"},gb={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:"잘림"},panel:{selectNode:"노드를 선택하면 상세 정보를 확인할 수 있습니다.",submoduleBadge:"서브모듈",dirtyBadge:"변경됨",outOfSyncBadge:"미동기화",conflictBadge:"충돌",orphanBadge:"고아",fieldWorkspace:"워크스페이스",fieldBranch:"브랜치",fieldUpstream:"업스트림",fieldUpstreamState:"업스트림 상태",fieldHead:"HEAD",fieldSubmodulePath:"서브모듈 경로",fieldSubmoduleCommit:"서브모듈 커밋",fieldParentNode:"부모 노드",fieldAhead:"앞섬",fieldBehind:"뒤처짐",fieldDirtyFiles:"변경 파일",fieldActiveSessions:"활성 세션",fieldProviders:"프로바이더",fieldConnection:"연결",fieldLinkNote:"링크 비고",fieldError:"오류",orphanReasons:"고아 원인",attachedChats:"연결된 채팅",providerUnknown:"알 수 없는 프로바이더",statusAwaiting:"승인 대기 중",statusGenerating:"생성 중",statusIdle:"유휴",statusCoordinator:"코디네이터",statusWorker:"워커",runtimeAgeNotReported:"런타임 경과 시간 미보고",upstreamVerified:"확인됨",upstreamUnverifiedFetch:"미확인 (fetch 실패)",upstreamUnverified:"미확인",upstreamUnavailable:"사용 불가",needsFollowUp:"후속 작업 필요",refined:"정제됨"},obs:{tabOverview:"개요",tabStatus:"상태",tabGraph:"그래프",convergenceMergedToMain:"main에 병합됨",convergenceNeedsMerge:"병합 필요",convergenceBlockedReview:"차단됨 — 리뷰 필요",convergenceCleanup:"정리 준비 완료",convergenceNotMergeable:"병합 불가",followUpLabel:"후속 작업 — {{status}}",selectedNode:"선택된 노드",selectedEdge:"선택된 엣지",activeSessions:"활성 세션",ledger:"원장 (메시 전체)",queueTasks:"큐 작업",keyWarning:"핵심 경고",healResult:"힐 결과",healPreview:"힐 미리보기",noResultCode:"반환된 결과 코드가 없습니다.",health:"헬스",legend:"범례",checking:"확인 중",heal:"힐",loadingGraph:"그래프 로딩 중…",bootstrapBanner:"라이브 데이터 대기 중 — 피어 mesh_status 프로브 성공 전까지 설정 인벤토리를 표시합니다.",emptyGraph:"이 코디네이터에 대한 라이브 메시 그래프가 아직 없습니다.",fieldMachine:"머신",fieldLocality:"로컬리티",fieldWorkspace:"워크스페이스",fieldHead:"HEAD",fieldDirtyAheadBehind:"변경/앞섬/뒤처짐",fieldSessions:"세션",fieldUpstream:"업스트림",fieldSource:"소스",fieldTransport:"전송",fieldMachineId:"머신 ID",fieldDaemonId:"데몬 ID",fieldFrom:"출발",fieldTo:"도착",fieldLabel:"레이블",fieldCompleted:"완료",fieldFailed:"실패",fieldLaunched:"시작됨",fieldRecentFailures:"최근 실패",meshConnecting:"메시 연결 중...",connecting:"연결 중...",providerUnknown:"알 수 없는 프로바이더"}},yb={page:{title:"Repo Mesh",subtitle:"다중 워크스페이스 오케스트레이션",waitingForDaemon:"데몬 연결 대기 중...",observabilitySecondary:"메시 관측성"},list:{title:"Repo Meshes",count_one:"메시 {{count}}개",count_other:"메시 {{count}}개",createMesh:"+ 메시 생성",createTitle:"Create Repo Mesh",createOnMachine:"생성할 머신",createOnMachineHint:"메시 설정은 선택한 데몬에 저장됩니다.",noConnectedDaemon:"연결된 데몬 없음",workspace:"워크스페이스",workspaceHint:"선택한 데몬에 등록된 워크스페이스에서 선택하세요.",selectMachineFirst:"머신을 먼저 선택하세요",noRegisteredWorkspaces:"등록된 워크스페이스 없음",name:"이름",remoteUrl:"리포 리모트 URL (선택)",remoteUrlHint:"리모트 URL 또는 안정적인 식별자 중 하나를 제공하세요.",repoIdentity:"리포 식별자 (선택)",create:"생성",cancel:"취소",loading:"메시 불러오는 중...",emptyTitle:"No Repo Meshes",emptyWithDaemons:"메시를 생성하여 시작하세요.",emptyNoDaemons:"먼저 ADHDev 데몬을 연결하세요.",createFirst:"첫 메시 생성",noRepoIdentity:"리포 식별자 없음",repoMeshFallback:"Repo Mesh",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:"또는 사용자 지정 경로 입력 →",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:"이 노드에서 감지된 프로바이더가 없습니다 — 프로바이더가 선택되거나 설치될 때까지 작업 실행이 차단됩니다. (빈 역량 슬롯만으로는 실행이 차단되지 않습니다. 이것은 프로바이더를 찾지 못했다는 의미입니다.)",titleNoCount:"노드 및 제공자",workspacesDetected:"워크스페이스 {{count}}개 감지됨",pickFromSaved:"← 저장된 워크스페이스에서 선택",ownerMachine:"소유자: {{owner}} · 머신: {{machine}}"},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:"연결된 데몬이 없습니다. 이 메시를 호스팅할 데몬을 온라인으로 만드세요.",online:"온라인",offline:"오프라인",noCommandTarget:"사용 가능한 명령 대상이 없습니다 — 호스트 또는 데몬을 온라인 상태로 만드세요.",pickHostFirst:"먼저 호스트 데몬을 선택하세요(또는 호스트 핀이 확정될 때까지 기다리세요).",attachNodeFirst:"먼저 이 데몬의 워크스페이스를 노드로 연결하세요."},slotEditor:{empty:"설정된 역량 슬롯이 없습니다 — 괜찮습니다. 이 노드는 여전히 프로바이더 우선순위(아래)로 작업을 실행합니다. 슬롯은 선택적 미세 조정입니다: 특정 작업 난이도나 역량을 특정 도구로 라우팅하려면 하나 추가하세요.",moveUp:"위로 이동",moveDown:"아래로 이동",removeSlot:"슬롯 제거",provider:"프로바이더",select:"(선택)",model:"모델",providerDefault:"(프로바이더 기본값)",custom:"사용자 지정…",modelPlaceholder:"모델",backToModelList:"← 모델 목록으로",thinking:"사고",thinkingDefault:"(기본값)",difficulty:"난이도 (비우면 = 전체)",capabilityTags:"역량 태그 (쉼표 구분)",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"}},vb={copyMessage:"메시지 복사"},wb={connectingToMachine:"머신에 연결 중",establishingP2P:"P2P 연결 설정 중",agentNotMonitored:"에이전트 모니터링 안 됨",clickToSwitchMonitoring:"이 에이전트로 모니터링 전환하려면 클릭하세요",agentPanelHidden:"에이전트 패널이 아직 표시되지 않습니다",openPanelHint:"사용 중인 앱에서 에이전트 패널이나 채팅 보기를 열어 메시지를 확인하세요",noMessagesYet:"아직 메시지가 없습니다",loadingChat:"채팅 불러오는 중...",openPanel:"{{label}} 패널 열기",switchingPanel:"전환 중...",openingPanel:"여는 중..."},kb={attachImage:"이미지 첨부",placeholder:"{{panel}}에 메시지 전송... (줄바꿈은 Shift+Enter)",sendMessage:"메시지 전송",dropImage:"여기에 이미지를 놓으세요"},jb={noConversations:"아직 대화가 없습니다",waitingForDaemon:"데몬을 기다리는 중",connectYourMachines:"머신을 연결하세요",daemonDescription:"ADHDev 데몬을 시작하여 이 대시보드에 연결하세요. 온라인이 되면 설치된 프로바이더로 세션을 실행할 수 있습니다.",installDescription:"머신에 ADHDev를 설치하고 로그인하면 여기에 표시됩니다.",newSession:"새 세션",newSessionDescription:"연결된 머신이 준비되었습니다. CLI, ACP, IDE 중 설치된 프로바이더로 새 세션을 시작하세요."},Sb={loadOlderOutput:"이전 터미널 출력 불러오기",loadingOlder:"이전 항목 불러오는 중...",debug:"디버그",copy:"복사",openControlKeys:"터미널 제어 키 열기",closeControlKeys:"터미널 제어 키 닫기"},Nb={muteThis:"이 채팅 음소거",unmuteThis:"이 채팅 음소거 해제",mutedTitle:"음소거됨 — 알림이 차단되었습니다. 클릭하여 해제하세요.",muteTitle:"이 채팅 알림 음소거"},Cb={switchToTerminal:"터미널 보기로 전환",switchToChat:"채팅 보기로 전환"},Mb={resumeSavedHistory:"저장된 기록 재개",startFresh:"새로 시작",resumingSavedHistory:"저장된 기록 재개 중…",startingFresh:"새로 시작 중…",startIde:"IDE 시작",startingIde:"IDE 시작 중…",startAcpSession:"ACP 세션 시작",startingAcpSession:"ACP 세션 시작 중…",recoverHostedRuntime:"호스팅 런타임 복구",hostedRuntimeRecoveryDescription:"중단 후 호스팅 런타임의 폴백 복구. 일반적인 연속성을 위해서는 저장된 기록을 여세요.",openSavedHistory:"저장된 기록 열기",savedHistoryTitle:"저장된 기록",savedHistoryHelper:"같은 프로바이더 대화의 연속성을 원할 때 저장된 기록을 사용하세요.",savedHistoryEmpty:"아직 저장된 기록이 없습니다.",refreshSavedHistory:"저장된 기록 새로고침",refreshingSavedHistory:"저장된 기록 새로고침 중…",startFreshWith:"{{label}}(으)로 새로 시작할까요?",restart:"{{label}}을(를) 재시작할까요?",startFreshReview:"새로 시작하기 전에 프로바이더와 대상 폴더를 확인하세요.",restartIdeReview:"IDE를 재시작하기 전에 대상 워크스페이스를 확인하거나 변경하세요.",restartStoppedReview:"중지된 세션을 재시작하기 전에 대상 워크스페이스를 확인하거나 변경하세요.",confirmStartFresh:"새로 시작",confirmRestart:"재시작",confirmStartingFresh:"새로 시작 중…",confirmRestarting:"재시작 중…",resumeWith:"{{label}}(으)로 저장된 기록을 재개할까요?",resumeReview:"저장된 기록을 재개하기 전에 대상 워크스페이스를 확인하거나 변경하세요."},Ab={nav:{dashboard:"대시보드",settings:"설정",docs:"문서",about:"정보"},layout:{expandSidebar:"사이드바 펼치기",collapseSidebar:"사이드바 접기",collapse:"접기"},auth:{loading:"스탠드얼론 대시보드 로드 중…",loadError:"스탠드얼론 인증 상태 로드 실패: {{error}}",signInTitle:"스탠드얼론 로그인",passwordProtected:"이 셀프호스트 대시보드는 로컬 비밀번호로 보호되어 있습니다.",tokenProtected:"이 스탠드얼론 서버는 토큰으로 보호되어 있습니다. 토큰이 포함된 URL로 접근하거나, 이미 인증된 세션에서 비밀번호를 설정하세요.",passwordPlaceholder:"스탠드얼론 비밀번호 입력",unlock:"대시보드 잠금 해제",signingIn:"로그인 중…",noPasswordEnabled:"이 서버에서는 비밀번호 로그인이 활성화되어 있지 않습니다."},machine:{loading:"⏳ 머신 로드 중...",awaitingInput:"입력을 기다리는 중 ↑"},settings:{title:"설정",subtitle:"로컬 데몬 구성, 외관 및 기기 내 환경설정",infoNotice:"스탠드얼론 설정은 이 머신에만 저장됩니다. 브라우저는 localhost 또는 셀프호스트 LAN 엔드포인트를 통해 로컬 데몬에만 연결합니다.",publicHostWarning:"이 스탠드얼론 서버가 현재 인증 없이 0.0.0.0에 바인딩되어 있습니다. 비밀번호나 토큰을 설정하기 전까지 같은 LAN의 누구나 대시보드에 접근할 수 있습니다.",daemonSection:"데몬",daemonDescription:"셀프호스트 런타임의 연결 상태 및 로컬 엔드포인트.",versionLabel:"버전",statusLabel:"상태",statusRunning:"● 실행 중",statusNotConnected:"○ 연결되지 않음",currentBindLabel:"현재 바인드",defaultBindLabel:"기본 바인드",authLabel:"인증",authPassword:"비밀번호 활성화됨",authToken:"토큰 활성화됨",authNone:"인증 미설정",networkSection:"네트워크 접근",networkDescription:"향후 스탠드얼론 실행에 사용할 기본 바인드 호스트를 선택하세요. CLI --host 플래그는 일회성 실행에 대해 이를 재정의합니다.",networkHint:"이 대시보드를 현재 머신에서만 사용하려면 localhost 전용을 선택하세요. 폰, 태블릿 또는 LAN의 다른 기기에서 접근하려면 모든 인터페이스를 선택하세요. 외부에 더 넓게 노출한다면 비밀번호나 토큰을 설정하세요.",localhostLabel:"Localhost 전용",localhostHint:"127.0.0.1에 바인딩. 이 머신에서만 대시보드를 열 때 적합합니다.",allInterfacesLabel:"모든 인터페이스",allInterfacesHint:"0.0.0.0에 바인딩. LAN 접근, 리버스 프록시, 또는 외부 진입점에 적합합니다.",saveNetworkMode:"기본 네트워크 모드 저장",saving:"저장 중…",networkRestartHint:"다음 스탠드얼론 재시작 시 적용됩니다. 현재 실행은 {{host}}에 바인딩된 상태로 유지됩니다.",networkSavedAll:"기본 스탠드얼론 네트워크 모드가 모든 인터페이스(0.0.0.0)로 설정되었습니다. 적용하려면 스탠드얼론을 재시작하세요.",networkSavedLocal:"기본 스탠드얼론 네트워크 모드가 localhost 전용으로 설정되었습니다. 적용하려면 스탠드얼론을 재시작하세요.",securitySection:"대시보드 보안",securityDescription:"이 스탠드얼론 대시보드를 사용하는 브라우저에 대한 셀프호스트 전용 비밀번호 보호.",passwordSet:"현재 브라우저 접근에 로컬 비밀번호가 필요합니다. 변경 시 기존 세션이 갱신됩니다.",passwordNotSet:"스탠드얼론 비밀번호가 아직 설정되지 않았습니다. --host로 실행하는 경우 비밀번호 설정을 강력히 권장합니다.",currentPasswordPlaceholder:"현재 비밀번호",currentPasswordFirstTimePlaceholder:"현재 비밀번호 (최초 설정 시 불필요)",newPasswordPlaceholder:"새 비밀번호",newPasswordFirstTimePlaceholder:"새 스탠드얼론 비밀번호",confirmPasswordPlaceholder:"새 비밀번호 확인",updatePassword:"비밀번호 변경",enablePassword:"비밀번호 활성화",disablePassword:"비밀번호 비활성화",passwordUpdated:"스탠드얼론 비밀번호가 변경되었습니다.",passwordEnabled:"스탠드얼론 비밀번호가 활성화되었습니다.",passwordDisabled:"스탠드얼론 비밀번호가 비활성화되었습니다.",passwordTooShort:"비밀번호는 최소 4자 이상이어야 합니다.",passwordMismatch:"새 비밀번호와 확인 비밀번호가 일치하지 않습니다.",detectedIdesSection:"감지된 IDE",detectedIdesDescription:"이 머신에서 로컬 데몬이 발견한 편집기.",noIdesDetected:"감지된 IDE가 없습니다. IDE를 시작하면 여기에 표시됩니다.",machineSection:"머신",machineDescription:"스탠드얼론 데몬이 노출하는 로컬 burrow.",daemonNotConnected:"데몬이 연결되지 않았습니다. 'adhdev-standalone'을 실행하여 시작하세요.",appearanceSection:"외관",appearanceDescription:"모드, 테마, 스탠드얼론 전용 폰트 재정의를 한 곳에서 관리합니다.",themeDescription:"스탠드얼론 UI에 맞는 프리셋을 선택하거나 서피스, 액센트, 채팅 팔레트를 직접 커스터마이즈하세요.",mobileDescription:"폰에서 대시보드를 채팅 앱 우선으로 열지, 전체 워크스페이스 레이아웃으로 열지 선택하세요.",fontsLabel:"폰트",fontsDescription:"채팅 텍스트, 마크다운 코드, 터미널 출력에 대한 스탠드얼론 전용 타이포그래피 재정의.",fontsSaved:"이 셀프호스트 대시보드에 스탠드얼론 채팅 폰트가 저장되었습니다.",notificationsSection:"알림",notificationsDescription:"에이전트 활동에 대한 브라우저 알림 및 로컬 사운드 신호.",soundEffectsLabel:"효과음",soundEffectsDescription:"에이전트가 완료되거나 승인이 필요할 때 소리 재생",profileSection:"프로필",profileDescription:"로컬 채팅 스레드 및 대시보드 뷰에 이름이 표시되는 방식.",displayNameLabel:"표시 이름",displayNameHint:"채팅 스레드 및 팀 대시보드에 표시되는 이름.",displayNamePlaceholder:"익명"},onboarding:{title:"ADHDev에 오신 것을 환영합니다",selectedCount_one:"{{count}}개 프로바이더 선택됨",selectedCount_other:"{{count}}개 프로바이더 선택됨",skip:"건너뛰기",installing:"설치 중…",done:"완료",installCount:"{{count}}개 설치",intro:"사용할 프로바이더를 선택하세요. 기본값은 공식 지원 CLI 프로바이더 4개입니다. 아래 탭에서 IDE, ACP, 익스텐션 프로바이더를 설치하거나 나중에 Burrow → Providers → Add provider에서 추가할 수 있습니다.",loadingRegistry:"레지스트리 로드 중…",loadError:"레지스트리 로드 실패: {{error}}",noProviders:"이 카테고리에 프로바이더가 없습니다.",installed:"✓ 설치됨",installFailed:"✗ {{error}}"},about:{title:"정보",subtitle:"셀프호스트 ADHDev 개요, 내장 서피스, Cloud와의 차이점",selfHostedEdition:"셀프호스트 에디션",headline:"런타임을 온디바이스에서 완전히 실행하면서 동일한 대시보드 경험을 유지하세요.",description:"Standalone은 브라우저, 데몬, 스크린샷, 제어 경로를 모두 본인 머신에 유지합니다. 원격 네트워킹과 팀 레이어 없이 Cloud와 동일한 핵심 제품 형태입니다.",docs:"문서 ↗",github:"GitHub ↗",tryCloud:"Cloud 체험 ↗",includedSection:"스탠드얼론 포함 기능",includedDescription:"Cloud 컨트롤 플레인 없이 사용 가능한 로컬 우선 기능 세트.",inventorySection:"내장 인벤토리",inventoryDescription:"스탠드얼론 대시보드에 노출된 번들 편집기 및 에이전트 서피스. 이 목록은 인벤토리를 설명하며 지원 여부를 보장하지 않습니다.",cloudExtrasSection:"Cloud 전용 추가 기능",cloudExtrasDescription:"호스트된 컨트롤 플레인 또는 팀 인프라가 필요한 기능.",comparisonSection:"셀프호스트 vs Cloud",comparisonDescription:"제품 분리 한눈에 보기.",featureHeader:"기능",selfhostHeader:"셀프호스트",cloudHeader:"Cloud",cloudOptional:"Cloud는 선택 사항입니다",cloudOptionalDescription:"Standalone에서 완전히 로컬로 유지하다가 나중에 대시보드 사용 방식을 바꾸지 않고 Cloud로 이전할 수 있습니다.",compareCloud:"Cloud 비교 ↗",discord:"Discord ↗"},fonts:{fontOverridesNotice:"스탠드얼론 전용 폰트 재정의. Cloud 대시보드에는 영향을 주지 않습니다. 채팅 버블, 마크다운 산문, 코드 블록, 툴 행, 터미널 출력은 모두 아래 환경설정을 따릅니다.",chat:"채팅 텍스트",chatDescription:"어시스턴트/사용자 산문, 마크다운 텍스트, 생각 카드, 시스템 메모.",code:"코드 블록",codeDescription:"마크다운 코드 펜스, 인라인 코드, 서식 있는 명령 출력.",terminal:"터미널",terminalDescription:"채팅 모드에서 터미널 트랜스크립트 카드 및 툴/명령 행.",livePreview:"라이브 미리보기",resolvedStack:"해결된 스택:",defaults:"기본값:",saveFontSettings:"폰트 설정 저장",revertToSaved:"저장된 값으로 되돌리기",resetToDefaults:"기본값으로 재설정",saving:"저장 중…"}},Ib={login:{eyebrow:"클라우드 로그인",title:"ADHDev에 로그인",subtitle:"머신을 연결하고, 승인·완료 알림을 받고, 자리를 비운 동안에도 코딩 에이전트를 계속 진행시키세요.",continueWith:"{{provider}}(으)로 계속하기",connecting:"연결 중...",devDivider:"개발",devLogin:"개발 로그인 (test_jwt_token)",providerNote:"GitHub와 Google은 인증 용도로만 사용됩니다.",errorUnverifiedEmail:"이 로그인 제공자가 인증된 이메일을 반환하지 않아 안전하게 로그인할 수 없었습니다.",termsPrefix:"계속 진행하면 ",termsLink:"서비스 약관",termsAnd:" 및 ",privacyLink:"개인정보 처리방침",termsSuffix:"에 동의하게 됩니다."},account:{title:"계정",subtitle:"프로필, 플랜 및 활동",tabAccount:"계정",tabBilling:"결제",tabActivity:"활동",profile:"프로필",noName:"이름 없음",displayName:"표시 이름",displayNameDesc:"대시보드와 팀 워크스페이스에 표시되는 이름입니다.",nicknamePlaceholder:"닉네임",save:"저장",saving:"...",cancel:"취소",saved:"저장됨",edit:"편집",failedToSave:"저장 실패",userId:"사용자 ID",loadingProfile:"프로필 불러오는 중...",planLimits:"플랜 한도",limitMachines:"머신",limitP2P:"P2P 연결",limitWebhooks:"웹훅",limitTurnRelay:"TURN 릴레이",enabled:"사용",disabled:"사용 안 함",frozen:"동결됨",session:"세션",logout:"로그아웃",logoutConfirm:"정말 로그아웃하시겠습니까?",logoutDesc:"이 기기에서 ADHDev 계정을 로그아웃합니다.",dangerZone:"위험 구역",dangerZoneDesc:"계정과 관련된 모든 데이터를 영구적으로 삭제합니다. 이 작업은 되돌릴 수 없습니다.",deleteAccount:"계정 삭제",deleteWillRemove:"다음 항목이 영구적으로 삭제됩니다:",deleteItemProfile:"프로필 및 로그인 자격 증명",deleteItemKeys:"모든 API 키 및 연결 토큰",deleteItemWebhooks:"웹훅 및 전송 기록",deleteItemPush:"푸시 알림 구독",deleteItemSessions:"공유 세션 및 감사 로그",deleteTypeConfirm:"{{keyword}}(을)를 입력하여 확인하세요:",deleting:"삭제 중...",permanentlyDelete:"영구 삭제",failedToDeleteAccount:"계정 삭제 실패",registeredMachines:"등록된 머신",machinesSummary:"{{count}}개 등록 · {{online}}개 온라인",machinesLimit:"(한도: {{limit}})",loadingMachines:"머신 불러오는 중...",noMachinesRegistered:"등록된 머신 없음",runSetupPrefix:"머신에서 ",runSetupMiddle:"을(를) 실행한 다음 ",runSetupSuffix:"을(를) 시작하면 여기에 등록됩니다.",removeMachineConfirm:"이 머신을 제거하시겠습니까? 다시 연결하려면 `adhdev setup`을 다시 실행해야 합니다.",failedToDeleteMachine:"머신 삭제 실패",failedToUpdate:"업데이트 실패",rename:"이름 변경",online:"온라인",connecting:"연결 중",lastSeen:"마지막 접속 {{time}}",removeMachine:"머신 제거",never:"없음",justNow:"방금 전",minutesAgo:"{{minutes}}분 전",hoursAgo:"{{hours}}시간 전",daysAgo:"{{days}}일 전"},billing:{currentPlan:"현재 플랜:",statusTrial:"체험판",statusActive:"활성",statusPastDue:"연체",statusCanceled:"취소됨",nextBilling:"다음 결제: {{date}}",trialEnds:"체험 종료: {{date}}",accessUntil:"이용 가능 기한: {{date}}",updatePayment:"결제 수단을 업데이트해 주세요",managePayment:"결제 및 청구서 관리",couldNotOpenPortal:"결제 포털을 열 수 없습니다",statMachines:"머신",statTeam:"팀",statTurnPerDay:"TURN 분/일",monthly:"월간",yearly:"연간",savePercent:"17% 절약",paddleLoading:"Paddle을 불러오는 중입니다. 다시 시도해 주세요.",cancelConfirm:"정말 구독을 취소하시겠습니까? 결제 기간이 끝날 때까지는 계속 이용할 수 있습니다.",teamSeats:"팀 좌석",seatsUsed:"{{total}}개 중 {{used}}개 사용 중",pricePerMonth:"${{price}}/월",cannotReduceSeats:"{{count}}개 미만으로 줄일 수 없습니다(현재 사용 중). 먼저 멤버를 제거하세요.",removeSeat:"− 좌석 제거",addSeat:"+ 좌석 추가",cancelSubscription:"구독 취소",cancelRetainAccess:"현재 결제 기간이 끝날 때까지 {{plan}} 기능을 계속 이용할 수 있습니다.",cancelTeamDowngrade:" 모든 팀 멤버는 개인 플랜으로 다운그레이드됩니다."},activity:{filterPlaceholder:"작업, 리소스 또는 소스로 필터...",refresh:"새로고침",loading:"불러오는 중...",noLogs:"로그 없음",noMatchingLogs:"일치하는 로그가 없습니다.",logsWillAppear:"작업이 발생하면 여기에 표시됩니다.",colAction:"작업",colResource:"리소스",colSource:"소스",colTime:"시간",logCount:"로그 {{count}}개",logCountFiltered:" ({{total}}개에서 필터됨)"},webhooks:{title:"웹훅",subtitle:"실시간 이벤트 알림",addWebhook:"+ 웹훅 추가",eventDaemonConnect:"데몬 연결됨",eventDaemonDisconnect:"데몬 연결 해제됨",eventAgentStatus:"에이전트 상태 변경",eventApprovalRequired:"승인 필요",failed:"실패",deleteConfirm:"이 웹훅을 삭제하시겠습니까?",testFailed:"테스트 실패",secretTitle:"웹훅 시크릿",secretShownOncePrefix:"",secretShownOnce:"한 번만",secretShownOnceSuffix:" 표시됩니다. 다음을 검증하는 데 사용하세요: ",copy:"복사",done:"완료",newWebhook:"새 웹훅",labelUrl:"URL",urlPlaceholder:"https://your-service.com/webhook",labelEvents:"이벤트",allEvents:"모든 이벤트 (*)",creating:"생성 중...",create:"생성",cancel:"취소",loading:"불러오는 중...",noWebhooks:"웹훅 없음",noWebhooksDesc:"이벤트에 대한 실시간 알림을 받으세요.",setupFirst:"첫 웹훅 설정",off:"꺼짐",autoDisabled:"자동 비활성화됨",autoDisabledTitle:"연속 10회 실패 후 자동 비활성화됨",failuresWarning:"⚠ 실패 {{count}}회",failuresTitle:"연속 {{count}}회 실패 — 10회에서 자동 비활성화됩니다",all:"전체",history:"기록",test:"테스트",delete:"삭제",deleting:"...",recentDeliveries:"최근 전송",refresh:"새로고침",noDeliveries:"아직 전송 내역이 없습니다. 🧪로 테스트를 보내세요.",request:"요청",response:"응답",securityTitle:"보안",securityVerifyPrefix:"",securityVerifySuffix:"을(를) 시크릿으로 검증하세요",securityHttps:"HTTPS 엔드포인트만 사용하세요",securityAsync:"즉시 2xx를 반환하고 비동기로 처리하세요",securityAutoDisable:"연속 10회 실패 후 자동 비활성화됨"},apiKeys:{title:"API 키",keyCount:"키 {{count}}개",playground:"플레이그라운드",create:"+ 생성",scopeDaemonRead:"데몬 읽기",scopeDaemonReadDesc:"데몬 목록 및 상태 조회",scopeDaemonControl:"데몬 제어",scopeDaemonControlDesc:"명령, 실행/중지, 연결 해제",scopeAgentRead:"에이전트 읽기",scopeAgentReadDesc:"상태 및 채팅 기록",scopeAgentControl:"에이전트 제어",scopeAgentControlDesc:"전송, 승인/거부",scopeTerminal:"터미널",scopeTerminalDesc:"명령 실행",scopeWebhooks:"웹훅",scopeWebhooksDesc:"훅 및 전송 관리",frozen:"동결됨",revokeConfirm:"이 API 키를 취소하시겠습니까? 되돌릴 수 없습니다.",failedToLoad:"불러오기 실패",failed:"실패",upgradePlan:"플랜 업그레이드 →",keyCreated:"키 생성됨!",copyNow:"지금 복사하세요 — 한 번만 표시됩니다.",copied:"복사됨",copy:"복사",testKey:"테스트",dismiss:"닫기",playgroundTitle:"API 플레이그라운드",enterKeyToTest:"테스트할 API 키를 입력하세요.",open:"열기",createKeyTitle:"API 키 생성",labelName:"이름",namePlaceholder:"예: Production Bot",permissions:"권한 ({{count}})",createBtn:"생성",cancel:"취소",loading:"불러오는 중...",noKeys:"API 키 없음",noKeysDesc:"외부 서비스와 연동할 키를 생성하세요.",createFirstKey:"첫 키 생성",usedDate:"{{date}} 사용",neverUsed:"사용 안 함",revoke:"취소",usageLabel:"사용법:",apiReference:"API 레퍼런스 →"},auditLogs:{title:"감사 로그",subtitle:"보안 이벤트 및 API 기록",refresh:"새로고침",filterPlaceholder:"작업, 리소스 또는 소스로 필터...",loading:"불러오는 중...",noLogs:"로그 없음",noMatchingLogs:"일치하는 로그가 없습니다.",logsWillAppear:"작업이 발생하면 여기에 표시됩니다.",colAction:"작업",colResource:"리소스",colSource:"소스",colTime:"시간",logCount:"로그 {{count}}개",logCountFiltered:" ({{total}}개에서 필터됨)"}},Tb={chatHistory:"채팅 기록",startNewChat:"+ 새 채팅 세션 시작",creating:"⌛ 생성 중...",searchPlaceholder:"제목 또는 미리보기 검색",filterWorkspace:"워크스페이스로 필터",filterModel:"모델로 필터",sortRecent:"최신순",sortOldest:"오래된순",sortMessages:"메시지 많은순",resumeReadyOnly:"재개 가능만",untitledSession:"제목 없는 세션",noSavedPreview:"저장된 미리보기 없음",workspaceUnknown:"워크스페이스 알 수 없음",selectedWorkspaceSuffix:" · 선택한 워크스페이스",msgCount:"메시지 {{count}}개",statusActive:"활성",statusMissingWorkspace:"워크스페이스 없음",statusResumeSelectedWorkspace:"선택한 워크스페이스에서 재개",statusResuming:"재개 중...",statusResume:"재개",noMatchingHistory:"이 필터와 일치하는 저장 기록이 없습니다.",noRecentChats:"최근 채팅 세션이 없습니다.",refreshHistory:"기록 새로고침",refreshing:"⌛ 새로고침 중..."},Pb={language:ib,common:lb,connection:cb,toast:db,notification:ub,event:pb,dashboard:hb,cliStop:mb,approval:fb,newSession:xb,mobileInbox:bb,meshGraph:gb,repoMesh:yb,chat:vb,chatPane:wb,chatInput:kb,paneGroup:jb,terminal:Sb,conversation:Nb,cliView:Cb,launch:Mb,standalone:Ab,cloud:Ib,historyModal:Tb},Db={copyMessage:"メッセージをコピー"},Lb={connectingToMachine:"マシンに接続しています",establishingP2P:"P2P接続を確立中",agentNotMonitored:"エージェントが監視されていません",clickToSwitchMonitoring:"クリックしてこのエージェントの監視に切り替えます",agentPanelHidden:"エージェントパネルがまだ表示されていません",openPanelHint:"使用しているアプリでエージェントパネルまたはチャットビューを開いてメッセージを表示してください",noMessagesYet:"まだメッセージはありません",loadingChat:"チャットを読み込み中...",openPanel:"{{label}}パネルを開く",switchingPanel:"切り替え中...",openingPanel:"開いています..."},Rb={attachImage:"画像を添付",placeholder:"{{panel}}にメッセージを送信...(改行はShift+Enter)",sendMessage:"メッセージを送信",dropImage:"ここに画像をドロップ"},_b={noConversations:"まだ会話はありません",waitingForDaemon:"デーモンを待っています",connectYourMachines:"マシンを接続してください",daemonDescription:"ADHDevデーモンを起動してこのダッシュボードに接続してください。オンラインになると、インストールされたプロバイダーでセッションを開始できます。",installDescription:"マシンにADHDevをインストールしてサインインすると、ここに表示されます。",newSession:"新しいセッション",newSessionDescription:"接続されたマシンの準備ができています。CLI、ACP、またはIDEのインストール済みプロバイダーで新しいセッションを開始してください。"},Eb={loadOlderOutput:"古いターミナル出力を読み込む",loadingOlder:"古いものを読み込み中...",debug:"デバッグ",copy:"コピー",openControlKeys:"ターミナル制御キーを開く",closeControlKeys:"ターミナル制御キーを閉じる"},$b={muteThis:"このチャットをミュート",unmuteThis:"このチャットのミュートを解除",mutedTitle:"ミュート中 — 通知はオフです。クリックで解除します。",muteTitle:"このチャットの通知をミュート"},Fb={switchToTerminal:"ターミナルビューに切り替え",switchToChat:"チャットビューに切り替え"},Bb={resumeSavedHistory:"保存済み履歴を再開",startFresh:"新しく開始",resumingSavedHistory:"保存済み履歴を再開中…",startingFresh:"新しく開始中…",startIde:"IDEを起動",startingIde:"IDEを起動中…",startAcpSession:"ACPセッションを開始",startingAcpSession:"ACPセッションを開始中…",recoverHostedRuntime:"ホストされたランタイムを復元",hostedRuntimeRecoveryDescription:"中断後のホストされたランタイムのフォールバック復元。通常の継続性のためには、保存済み履歴を開いてください。",openSavedHistory:"保存済み履歴を開く",savedHistoryTitle:"保存済み履歴",savedHistoryHelper:"同じプロバイダーの会話で継続性を保ちたい場合は、保存済み履歴を使用してください。",savedHistoryEmpty:"保存済み履歴がまだ見つかりません。",refreshSavedHistory:"保存済み履歴を更新",refreshingSavedHistory:"保存済み履歴を更新中…",startFreshWith:"{{label}}で新しく開始しますか?",restart:"{{label}}を再起動しますか?",startFreshReview:"新しく開始する前にプロバイダーとターゲットフォルダーを確認してください。",restartIdeReview:"このIDEを再起動する前にターゲットワークスペースを確認または変更してください。",restartStoppedReview:"この停止したセッションを再起動する前にターゲットワークスペースを確認または変更してください。",confirmStartFresh:"新しく開始",confirmRestart:"再起動",confirmStartingFresh:"新しく開始中…",confirmRestarting:"再起動中…",resumeWith:"{{label}}で保存済み履歴を再開しますか?",resumeReview:"保存済み履歴を再開する前にターゲットワークスペースを確認または変更してください。"},Hb={nav:{dashboard:"Dashboard",settings:"Settings",docs:"Docs",about:"About"},layout:{expandSidebar:"Expand sidebar",collapseSidebar:"Collapse sidebar",collapse:"Collapse"},auth:{loading:"Loading standalone dashboard…",loadError:"Failed to load standalone auth status: {{error}}",signInTitle:"Standalone sign-in",passwordProtected:"This self-hosted dashboard is protected by a local password.",tokenProtected:"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session.",passwordPlaceholder:"Enter standalone password",unlock:"Unlock dashboard",signingIn:"Signing in…",noPasswordEnabled:"Password login is not enabled on this server."},machine:{loading:"⏳ Loading machine...",awaitingInput:"Awaiting your input ↑"},settings:{title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",infoNotice:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint.",publicHostWarning:"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.",daemonSection:"Daemon",daemonDescription:"Connection health and local endpoints for the self-hosted runtime.",versionLabel:"Version",statusLabel:"Status",statusRunning:"● Running",statusNotConnected:"○ Not connected",currentBindLabel:"Current bind",defaultBindLabel:"Default bind",authLabel:"Auth",authPassword:"Password enabled",authToken:"Token enabled",authNone:"No auth configured",networkSection:"Network Access",networkDescription:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",networkHint:"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.",localhostLabel:"Localhost only",localhostHint:"Bind to 127.0.0.1. Best when only this machine should open the dashboard.",allInterfacesLabel:"All interfaces",allInterfacesHint:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points.",saveNetworkMode:"Save default network mode",saving:"Saving…",networkRestartHint:"Applies on next standalone restart. Current run stays bound to {{host}}.",networkSavedAll:"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.",networkSavedLocal:"Default standalone network mode set to localhost only. Restart standalone to apply it.",securitySection:"Dashboard Security",securityDescription:"Self-hosted-only password protection for browsers using this standalone dashboard.",passwordSet:"A local password is currently required for browser access. Existing sessions are rotated when you change it.",passwordNotSet:"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended.",currentPasswordPlaceholder:"Current password",currentPasswordFirstTimePlaceholder:"Current password (not needed for first setup)",newPasswordPlaceholder:"New password",newPasswordFirstTimePlaceholder:"New standalone password",confirmPasswordPlaceholder:"Confirm new password",updatePassword:"Update password",enablePassword:"Enable password",disablePassword:"Disable password",passwordUpdated:"Standalone password updated.",passwordEnabled:"Standalone password enabled.",passwordDisabled:"Standalone password disabled.",passwordTooShort:"Password must be at least 4 characters.",passwordMismatch:"New password and confirmation do not match.",detectedIdesSection:"Detected IDEs",detectedIdesDescription:"Editors discovered by the local daemon on this machine.",noIdesDetected:"No IDEs detected. Start an IDE to see it here.",machineSection:"Machine",machineDescription:"The local burrow exposed by your standalone daemon.",daemonNotConnected:"Daemon not connected. Run 'adhdev-standalone' to start.",appearanceSection:"Appearance",appearanceDescription:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",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.",fontsLabel:"Fonts",fontsDescription:"Standalone-only typography overrides for chat text, markdown code, and terminal output.",fontsSaved:"Standalone chat fonts saved for this self-hosted dashboard.",notificationsSection:"Notifications",notificationsDescription:"Browser prompts and local sound cues for agent activity.",soundEffectsLabel:"Sound Effects",soundEffectsDescription:"Play a sound when agent completes or needs approval",profileSection:"Profile",profileDescription:"How your name appears in local chat threads and dashboard views.",displayNameLabel:"Display Name",displayNameHint:"Your name shown in chat threads and on the team dashboard.",displayNamePlaceholder:"Anonymous"},onboarding:{title:"Welcome to ADHDev",selectedCount_one:"{{count}} provider selected",selectedCount_other:"{{count}} providers selected",skip:"Skip",installing:"Installing…",done:"Done",installCount:"Install {{count}}",intro:"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 Burrow → Providers → Add provider.",loadingRegistry:"Loading registry…",loadError:"Failed to load registry: {{error}}",noProviders:"No providers in this category.",installed:"✓ installed",installFailed:"✗ {{error}}"},about:{title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",selfHostedEdition:"Self-hosted edition",headline:"Keep the same dashboard experience, with the runtime fully on-device.",description:"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.",docs:"Docs ↗",github:"GitHub ↗",tryCloud:"Try Cloud ↗",includedSection:"Included in standalone",includedDescription:"The local-first feature set available without the cloud control plane.",inventorySection:"Built-in inventory",inventoryDescription:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",cloudExtrasSection:"Cloud-only extras",cloudExtrasDescription:"Capabilities that need the hosted control plane or team infrastructure.",comparisonSection:"Self-hosted vs Cloud",comparisonDescription:"The product split at a glance.",featureHeader:"Feature",selfhostHeader:"Selfhost",cloudHeader:"Cloud",cloudOptional:"Cloud is optional, not required",cloudOptionalDescription:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",compareCloud:"Compare Cloud ↗",discord:"Discord ↗"},fonts:{fontOverridesNotice:"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.",chat:"Chat text",chatDescription:"Assistant/user prose, markdown text, thought cards, and system notes.",code:"Code blocks",codeDescription:"Markdown code fences, inline code, and preformatted command output.",terminal:"Terminal",terminalDescription:"Terminal transcript cards and tool/command rows in chat mode.",livePreview:"Live preview",resolvedStack:"Resolved stack:",defaults:"Defaults:",saveFontSettings:"Save font settings",revertToSaved:"Revert to saved",resetToDefaults:"Reset to defaults",saving:"Saving…"}},Ob={panel:{selectNode:"Select a node to view details.",submoduleBadge:"Submodule",dirtyBadge:"Dirty",outOfSyncBadge:"Out of sync",conflictBadge:"Conflict",orphanBadge:"Orphan",fieldWorkspace:"Workspace",fieldBranch:"Branch",fieldUpstream:"Upstream",fieldUpstreamState:"Upstream state",fieldHead:"HEAD",fieldSubmodulePath:"Submodule path",fieldSubmoduleCommit:"Submodule commit",fieldParentNode:"Parent node",fieldAhead:"Ahead",fieldBehind:"Behind",fieldDirtyFiles:"Dirty files",fieldActiveSessions:"Active sessions",fieldProviders:"Providers",fieldConnection:"Connection",fieldLinkNote:"Link note",fieldError:"Error",orphanReasons:"Orphan reasons",attachedChats:"Attached chats",providerUnknown:"provider unknown",statusAwaiting:"awaiting approval",statusGenerating:"generating",statusIdle:"idle",statusCoordinator:"coordinator",statusWorker:"worker",runtimeAgeNotReported:"runtime age not reported",upstreamVerified:"verified",upstreamUnverifiedFetch:"unverified (fetch failed)",upstreamUnverified:"unverified",upstreamUnavailable:"unavailable",needsFollowUp:"needs follow-up",refined:"refined"},obs:{tabOverview:"Overview",tabStatus:"Status",tabGraph:"Graph",convergenceMergedToMain:"Merged to main",convergenceNeedsMerge:"Needs merge",convergenceBlockedReview:"Blocked — needs review",convergenceCleanup:"Ready to clean up",convergenceNotMergeable:"Not mergeable",followUpLabel:"Follow-up — {{status}}",selectedNode:"Selected node",selectedEdge:"Selected edge",activeSessions:"Active Sessions",ledger:"Ledger (mesh-wide)",queueTasks:"Queue tasks",keyWarning:"Key warning",healResult:"Heal result",healPreview:"Heal preview",noResultCode:"No result code returned.",health:"Health",legend:"Legend",checking:"Checking",heal:"Heal",loadingGraph:"Loading graph…",bootstrapBanner:"Awaiting live data — showing setup inventory until peer mesh_status probes succeed.",emptyGraph:"No live mesh graph is available for this coordinator yet.",fieldMachine:"Machine",fieldLocality:"Locality",fieldWorkspace:"Workspace",fieldHead:"HEAD",fieldDirtyAheadBehind:"Dirty/ahead/behind",fieldSessions:"Sessions",fieldUpstream:"Upstream",fieldSource:"Source",fieldTransport:"Transport",fieldMachineId:"Machine id",fieldDaemonId:"Daemon id",fieldFrom:"From",fieldTo:"To",fieldLabel:"Label",fieldCompleted:"Completed",fieldFailed:"Failed",fieldLaunched:"Launched",fieldRecentFailures:"Recent failures",meshConnecting:"mesh connecting...",connecting:"connecting...",providerUnknown:"provider unknown"}},Wb={login:{eyebrow:"クラウドサインイン",title:"ADHDev にサインイン",subtitle:"マシンを接続し、承認・完了の通知を受け取り、デスクを離れている間もコーディングエージェントを動かし続けましょう。",continueWith:"{{provider}} で続行",connecting:"接続中...",devDivider:"開発",devLogin:"開発ログイン (test_jwt_token)",providerNote:"GitHub と Google は認証のみに使用されます。",errorUnverifiedEmail:"このログインプロバイダーが確認済みのメールアドレスを返さなかったため、安全にサインインできませんでした。",termsPrefix:"続行することで、",termsLink:"利用規約",termsAnd:" および ",privacyLink:"プライバシーポリシー",termsSuffix:" に同意したものとみなされます。"},account:{title:"アカウント",subtitle:"プロフィール、プラン、アクティビティ",tabAccount:"アカウント",tabBilling:"請求",tabActivity:"アクティビティ",profile:"プロフィール",noName:"名前なし",displayName:"表示名",displayNameDesc:"ダッシュボードやチームワークスペースに表示される名前です。",nicknamePlaceholder:"ニックネーム",save:"保存",saving:"...",cancel:"キャンセル",saved:"保存しました",edit:"編集",failedToSave:"保存に失敗しました",userId:"ユーザー ID",loadingProfile:"プロフィールを読み込み中...",planLimits:"プラン上限",limitMachines:"マシン",limitP2P:"P2P 接続",limitWebhooks:"Webhook",limitTurnRelay:"TURN リレー",enabled:"有効",disabled:"無効",frozen:"凍結",session:"セッション",logout:"ログアウト",logoutConfirm:"本当にログアウトしますか?",logoutDesc:"このデバイスで ADHDev アカウントからサインアウトします。",dangerZone:"危険ゾーン",dangerZoneDesc:"アカウントと関連するすべてのデータを完全に削除します。この操作は元に戻せません。",deleteAccount:"アカウントを削除",deleteWillRemove:"以下が完全に削除されます:",deleteItemProfile:"プロフィールとログイン認証情報",deleteItemKeys:"すべての API キーと接続トークン",deleteItemWebhooks:"Webhook と配信履歴",deleteItemPush:"プッシュ通知の購読",deleteItemSessions:"共有セッションと監査ログ",deleteTypeConfirm:"{{keyword}} と入力して確認してください:",deleting:"削除中...",permanentlyDelete:"完全に削除",failedToDeleteAccount:"アカウントの削除に失敗しました",registeredMachines:"登録済みマシン",machinesSummary:"{{count}} 台登録 · {{online}} 台オンライン",machinesLimit:"(上限: {{limit}})",loadingMachines:"マシンを読み込み中...",noMachinesRegistered:"登録済みマシンなし",runSetupPrefix:"マシンで ",runSetupMiddle:" を実行し、次に ",runSetupSuffix:" を起動するとここに登録されます。",removeMachineConfirm:"このマシンを削除しますか?再接続するには `adhdev setup` を再実行する必要があります。",failedToDeleteMachine:"マシンの削除に失敗しました",failedToUpdate:"更新に失敗しました",rename:"名前を変更",online:"オンライン",connecting:"接続中",lastSeen:"最終接続 {{time}}",removeMachine:"マシンを削除",never:"なし",justNow:"たった今",minutesAgo:"{{minutes}} 分前",hoursAgo:"{{hours}} 時間前",daysAgo:"{{days}} 日前"},billing:{currentPlan:"現在のプラン:",statusTrial:"トライアル",statusActive:"有効",statusPastDue:"支払い延滞",statusCanceled:"キャンセル済み",nextBilling:"次回請求: {{date}}",trialEnds:"トライアル終了: {{date}}",accessUntil:"利用期限: {{date}}",updatePayment:"お支払い方法を更新してください",managePayment:"支払いと請求書の管理",couldNotOpenPortal:"請求ポータルを開けませんでした",statMachines:"マシン",statTeam:"チーム",statTurnPerDay:"TURN 分/日",monthly:"月払い",yearly:"年払い",savePercent:"17% お得",paddleLoading:"Paddle を読み込み中です。もう一度お試しください。",cancelConfirm:"本当にサブスクリプションをキャンセルしますか?請求期間の終了まではご利用いただけます。",teamSeats:"チームシート",seatsUsed:"{{used}} / {{total}} シート使用中",pricePerMonth:"${{price}}/月",cannotReduceSeats:"{{count}} シート未満には減らせません(現在使用中)。先にメンバーを削除してください。",removeSeat:"− シートを削除",addSeat:"+ シートを追加",cancelSubscription:"サブスクリプションをキャンセル",cancelRetainAccess:"現在の請求期間の終了まで {{plan}} 機能をご利用いただけます。",cancelTeamDowngrade:" すべてのチームメンバーは個人プランにダウングレードされます。"},activity:{filterPlaceholder:"アクション、リソース、ソースで絞り込み...",refresh:"更新",loading:"読み込み中...",noLogs:"ログなし",noMatchingLogs:"一致するログが見つかりません。",logsWillAppear:"アクションが発生するとここに表示されます。",colAction:"アクション",colResource:"リソース",colSource:"ソース",colTime:"時刻",logCount:"ログ {{count}} 件",logCountFiltered:" ({{total}} 件から絞り込み)"},webhooks:{title:"Webhook",subtitle:"リアルタイムイベント通知",addWebhook:"+ Webhook を追加",eventDaemonConnect:"デーモン接続",eventDaemonDisconnect:"デーモン切断",eventAgentStatus:"エージェント状態変更",eventApprovalRequired:"承認が必要",failed:"失敗",deleteConfirm:"この Webhook を削除しますか?",testFailed:"テストに失敗しました",secretTitle:"Webhook シークレット",secretShownOncePrefix:"",secretShownOnce:"一度だけ",secretShownOnceSuffix:"表示されます。次の検証に使用してください: ",copy:"コピー",done:"完了",newWebhook:"新しい Webhook",labelUrl:"URL",urlPlaceholder:"https://your-service.com/webhook",labelEvents:"イベント",allEvents:"すべてのイベント (*)",creating:"作成中...",create:"作成",cancel:"キャンセル",loading:"読み込み中...",noWebhooks:"Webhook なし",noWebhooksDesc:"イベントに関するリアルタイム通知を受け取ります。",setupFirst:"最初の Webhook を設定",off:"オフ",autoDisabled:"自動無効化",autoDisabledTitle:"連続 10 回失敗後に自動無効化されました",failuresWarning:"⚠ {{count}} 回失敗",failuresTitle:"連続 {{count}} 回失敗 — 10 回で自動無効化されます",all:"すべて",history:"履歴",test:"テスト",delete:"削除",deleting:"...",recentDeliveries:"最近の配信",refresh:"更新",noDeliveries:"まだ配信はありません。🧪 でテストを送信してください。",request:"リクエスト",response:"レスポンス",securityTitle:"セキュリティ",securityVerifyPrefix:"",securityVerifySuffix:" をシークレットで検証してください",securityHttps:"HTTPS エンドポイントのみを使用してください",securityAsync:"すぐに 2xx を返し、非同期で処理してください",securityAutoDisable:"連続 10 回失敗後に自動無効化されました"},apiKeys:{title:"API キー",keyCount:"キー {{count}} 個",playground:"プレイグラウンド",create:"+ 作成",scopeDaemonRead:"デーモン読み取り",scopeDaemonReadDesc:"デーモン一覧と状態",scopeDaemonControl:"デーモン制御",scopeDaemonControlDesc:"コマンド、起動/停止、切断",scopeAgentRead:"エージェント読み取り",scopeAgentReadDesc:"状態とチャット履歴",scopeAgentControl:"エージェント制御",scopeAgentControlDesc:"送信、承認/拒否",scopeTerminal:"ターミナル",scopeTerminalDesc:"コマンドを実行",scopeWebhooks:"Webhook",scopeWebhooksDesc:"フックと配信を管理",frozen:"凍結",revokeConfirm:"この API キーを取り消しますか?元に戻せません。",failedToLoad:"読み込みに失敗しました",failed:"失敗",upgradePlan:"プランをアップグレード →",keyCreated:"キーを作成しました!",copyNow:"今すぐコピー — 一度だけ表示されます。",copied:"コピーしました",copy:"コピー",testKey:"テスト",dismiss:"閉じる",playgroundTitle:"API プレイグラウンド",enterKeyToTest:"テストする API キーを入力してください。",open:"開く",createKeyTitle:"API キーを作成",labelName:"名前",namePlaceholder:"例: Production Bot",permissions:"権限 ({{count}})",createBtn:"作成",cancel:"キャンセル",loading:"読み込み中...",noKeys:"API キーなし",noKeysDesc:"外部サービスと連携するキーを作成してください。",createFirstKey:"最初のキーを作成",usedDate:"{{date}} に使用",neverUsed:"未使用",revoke:"取り消し",usageLabel:"使用法:",apiReference:"API リファレンス →"},auditLogs:{title:"監査ログ",subtitle:"セキュリティイベントと API 履歴",refresh:"更新",filterPlaceholder:"アクション、リソース、ソースで絞り込み...",loading:"読み込み中...",noLogs:"ログなし",noMatchingLogs:"一致するログが見つかりません。",logsWillAppear:"アクションが発生するとここに表示されます。",colAction:"アクション",colResource:"リソース",colSource:"ソース",colTime:"時刻",logCount:"ログ {{count}} 件",logCountFiltered:" ({{total}} 件から絞り込み)"}},Ub={chatHistory:"チャット履歴",startNewChat:"+ 新しいチャットセッションを開始",creating:"⌛ 作成中...",searchPlaceholder:"タイトルまたはプレビューを検索",filterWorkspace:"ワークスペースで絞り込み",filterModel:"モデルで絞り込み",sortRecent:"最新順",sortOldest:"古い順",sortMessages:"メッセージ数順",resumeReadyOnly:"再開可能のみ",untitledSession:"無題のセッション",noSavedPreview:"保存されたプレビューはありません",workspaceUnknown:"ワークスペース不明",selectedWorkspaceSuffix:" · 選択したワークスペース",msgCount:"{{count}} 件のメッセージ",statusActive:"アクティブ",statusMissingWorkspace:"ワークスペースなし",statusResumeSelectedWorkspace:"選択したワークスペースで再開",statusResuming:"再開中...",statusResume:"再開",noMatchingHistory:"これらのフィルターに一致する保存履歴はありません。",noRecentChats:"最近のチャットセッションが見つかりません。",refreshHistory:"履歴を更新",refreshing:"⌛ 更新中..."},Kb={chat:Db,chatPane:Lb,chatInput:Rb,paneGroup:_b,terminal:Eb,conversation:$b,cliView:Fb,launch:Bb,standalone:Hb,meshGraph:Ob,cloud:Wb,historyModal:Ub},Gb={copyMessage:"复制消息"},zb={connectingToMachine:"正在连接到您的机器",establishingP2P:"正在建立P2P连接",agentNotMonitored:"代理未被监控",clickToSwitchMonitoring:"点击切换到监控此代理",agentPanelHidden:"代理面板尚不可见",openPanelHint:"在您使用的应用中打开代理面板或聊天视图以开始查看消息",noMessagesYet:"暂无消息",loadingChat:"正在加载聊天...",openPanel:"打开{{label}}面板",switchingPanel:"切换中...",openingPanel:"正在打开..."},Vb={attachImage:"附加图片",placeholder:"向{{panel}}发送消息...(Shift+Enter换行)",sendMessage:"发送消息",dropImage:"将图片拖放到此处"},qb={noConversations:"还没有对话",waitingForDaemon:"等待守护进程",connectYourMachines:"连接您的机器",daemonDescription:"启动ADHDev守护进程以连接此仪表板。一旦在线,您可以使用任何已安装的提供商启动会话。",installDescription:"在机器上安装ADHDev并登录,它将显示在这里。",newSession:"新建会话",newSessionDescription:"已连接的机器已就绪。使用任何已安装的提供商(CLI、ACP或IDE)开始新会话。"},Yb={loadOlderOutput:"加载较旧的终端输出",loadingOlder:"正在加载较旧内容...",debug:"调试",copy:"复制",openControlKeys:"打开终端控制键",closeControlKeys:"关闭终端控制键"},Jb={muteThis:"静音此聊天",unmuteThis:"取消静音此聊天",mutedTitle:"已静音 — 通知已关闭。点击取消静音。",muteTitle:"静音此聊天的通知"},Xb={switchToTerminal:"切换到终端视图",switchToChat:"切换到聊天视图"},Qb={resumeSavedHistory:"恢复保存的历史记录",startFresh:"重新开始",resumingSavedHistory:"正在恢复保存的历史记录…",startingFresh:"正在重新开始…",startIde:"启动IDE",startingIde:"正在启动IDE…",startAcpSession:"开始ACP会话",startingAcpSession:"正在开始ACP会话…",recoverHostedRuntime:"恢复托管运行时",hostedRuntimeRecoveryDescription:"中断后托管运行时的回退恢复。要正常延续,请改为打开保存的历史记录。",openSavedHistory:"打开保存的历史记录",savedHistoryTitle:"保存的历史记录",savedHistoryHelper:"当您希望在同一提供商对话中保持连续性时,请使用保存的历史记录。",savedHistoryEmpty:"尚未找到保存的历史记录。",refreshSavedHistory:"刷新保存的历史记录",refreshingSavedHistory:"正在刷新保存的历史记录…",startFreshWith:"使用{{label}}重新开始?",restart:"重启{{label}}?",startFreshReview:"重新开始前请检查提供商和目标文件夹。",restartIdeReview:"重启此IDE前,请查看或更改目标工作区。",restartStoppedReview:"重启此已停止的会话前,请查看或更改目标工作区。",confirmStartFresh:"重新开始",confirmRestart:"重启",confirmStartingFresh:"正在重新开始…",confirmRestarting:"正在重启…",resumeWith:"使用{{label}}恢复保存的历史记录?",resumeReview:"恢复保存的历史记录前,请查看或更改目标工作区。"},Zb={nav:{dashboard:"Dashboard",settings:"Settings",docs:"Docs",about:"About"},layout:{expandSidebar:"Expand sidebar",collapseSidebar:"Collapse sidebar",collapse:"Collapse"},auth:{loading:"Loading standalone dashboard…",loadError:"Failed to load standalone auth status: {{error}}",signInTitle:"Standalone sign-in",passwordProtected:"This self-hosted dashboard is protected by a local password.",tokenProtected:"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session.",passwordPlaceholder:"Enter standalone password",unlock:"Unlock dashboard",signingIn:"Signing in…",noPasswordEnabled:"Password login is not enabled on this server."},machine:{loading:"⏳ Loading machine...",awaitingInput:"Awaiting your input ↑"},settings:{title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",infoNotice:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint.",publicHostWarning:"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.",daemonSection:"Daemon",daemonDescription:"Connection health and local endpoints for the self-hosted runtime.",versionLabel:"Version",statusLabel:"Status",statusRunning:"● Running",statusNotConnected:"○ Not connected",currentBindLabel:"Current bind",defaultBindLabel:"Default bind",authLabel:"Auth",authPassword:"Password enabled",authToken:"Token enabled",authNone:"No auth configured",networkSection:"Network Access",networkDescription:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",networkHint:"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.",localhostLabel:"Localhost only",localhostHint:"Bind to 127.0.0.1. Best when only this machine should open the dashboard.",allInterfacesLabel:"All interfaces",allInterfacesHint:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points.",saveNetworkMode:"Save default network mode",saving:"Saving…",networkRestartHint:"Applies on next standalone restart. Current run stays bound to {{host}}.",networkSavedAll:"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.",networkSavedLocal:"Default standalone network mode set to localhost only. Restart standalone to apply it.",securitySection:"Dashboard Security",securityDescription:"Self-hosted-only password protection for browsers using this standalone dashboard.",passwordSet:"A local password is currently required for browser access. Existing sessions are rotated when you change it.",passwordNotSet:"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended.",currentPasswordPlaceholder:"Current password",currentPasswordFirstTimePlaceholder:"Current password (not needed for first setup)",newPasswordPlaceholder:"New password",newPasswordFirstTimePlaceholder:"New standalone password",confirmPasswordPlaceholder:"Confirm new password",updatePassword:"Update password",enablePassword:"Enable password",disablePassword:"Disable password",passwordUpdated:"Standalone password updated.",passwordEnabled:"Standalone password enabled.",passwordDisabled:"Standalone password disabled.",passwordTooShort:"Password must be at least 4 characters.",passwordMismatch:"New password and confirmation do not match.",detectedIdesSection:"Detected IDEs",detectedIdesDescription:"Editors discovered by the local daemon on this machine.",noIdesDetected:"No IDEs detected. Start an IDE to see it here.",machineSection:"Machine",machineDescription:"The local burrow exposed by your standalone daemon.",daemonNotConnected:"Daemon not connected. Run 'adhdev-standalone' to start.",appearanceSection:"Appearance",appearanceDescription:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",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.",fontsLabel:"Fonts",fontsDescription:"Standalone-only typography overrides for chat text, markdown code, and terminal output.",fontsSaved:"Standalone chat fonts saved for this self-hosted dashboard.",notificationsSection:"Notifications",notificationsDescription:"Browser prompts and local sound cues for agent activity.",soundEffectsLabel:"Sound Effects",soundEffectsDescription:"Play a sound when agent completes or needs approval",profileSection:"Profile",profileDescription:"How your name appears in local chat threads and dashboard views.",displayNameLabel:"Display Name",displayNameHint:"Your name shown in chat threads and on the team dashboard.",displayNamePlaceholder:"Anonymous"},onboarding:{title:"Welcome to ADHDev",selectedCount_one:"{{count}} provider selected",selectedCount_other:"{{count}} providers selected",skip:"Skip",installing:"Installing…",done:"Done",installCount:"Install {{count}}",intro:"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 Burrow → Providers → Add provider.",loadingRegistry:"Loading registry…",loadError:"Failed to load registry: {{error}}",noProviders:"No providers in this category.",installed:"✓ installed",installFailed:"✗ {{error}}"},about:{title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",selfHostedEdition:"Self-hosted edition",headline:"Keep the same dashboard experience, with the runtime fully on-device.",description:"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.",docs:"Docs ↗",github:"GitHub ↗",tryCloud:"Try Cloud ↗",includedSection:"Included in standalone",includedDescription:"The local-first feature set available without the cloud control plane.",inventorySection:"Built-in inventory",inventoryDescription:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",cloudExtrasSection:"Cloud-only extras",cloudExtrasDescription:"Capabilities that need the hosted control plane or team infrastructure.",comparisonSection:"Self-hosted vs Cloud",comparisonDescription:"The product split at a glance.",featureHeader:"Feature",selfhostHeader:"Selfhost",cloudHeader:"Cloud",cloudOptional:"Cloud is optional, not required",cloudOptionalDescription:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",compareCloud:"Compare Cloud ↗",discord:"Discord ↗"},fonts:{fontOverridesNotice:"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.",chat:"Chat text",chatDescription:"Assistant/user prose, markdown text, thought cards, and system notes.",code:"Code blocks",codeDescription:"Markdown code fences, inline code, and preformatted command output.",terminal:"Terminal",terminalDescription:"Terminal transcript cards and tool/command rows in chat mode.",livePreview:"Live preview",resolvedStack:"Resolved stack:",defaults:"Defaults:",saveFontSettings:"Save font settings",revertToSaved:"Revert to saved",resetToDefaults:"Reset to defaults",saving:"Saving…"}},eg={panel:{selectNode:"Select a node to view details.",submoduleBadge:"Submodule",dirtyBadge:"Dirty",outOfSyncBadge:"Out of sync",conflictBadge:"Conflict",orphanBadge:"Orphan",fieldWorkspace:"Workspace",fieldBranch:"Branch",fieldUpstream:"Upstream",fieldUpstreamState:"Upstream state",fieldHead:"HEAD",fieldSubmodulePath:"Submodule path",fieldSubmoduleCommit:"Submodule commit",fieldParentNode:"Parent node",fieldAhead:"Ahead",fieldBehind:"Behind",fieldDirtyFiles:"Dirty files",fieldActiveSessions:"Active sessions",fieldProviders:"Providers",fieldConnection:"Connection",fieldLinkNote:"Link note",fieldError:"Error",orphanReasons:"Orphan reasons",attachedChats:"Attached chats",providerUnknown:"provider unknown",statusAwaiting:"awaiting approval",statusGenerating:"generating",statusIdle:"idle",statusCoordinator:"coordinator",statusWorker:"worker",runtimeAgeNotReported:"runtime age not reported",upstreamVerified:"verified",upstreamUnverifiedFetch:"unverified (fetch failed)",upstreamUnverified:"unverified",upstreamUnavailable:"unavailable",needsFollowUp:"needs follow-up",refined:"refined"},obs:{tabOverview:"Overview",tabStatus:"Status",tabGraph:"Graph",convergenceMergedToMain:"Merged to main",convergenceNeedsMerge:"Needs merge",convergenceBlockedReview:"Blocked — needs review",convergenceCleanup:"Ready to clean up",convergenceNotMergeable:"Not mergeable",followUpLabel:"Follow-up — {{status}}",selectedNode:"Selected node",selectedEdge:"Selected edge",activeSessions:"Active Sessions",ledger:"Ledger (mesh-wide)",queueTasks:"Queue tasks",keyWarning:"Key warning",healResult:"Heal result",healPreview:"Heal preview",noResultCode:"No result code returned.",health:"Health",legend:"Legend",checking:"Checking",heal:"Heal",loadingGraph:"Loading graph…",bootstrapBanner:"Awaiting live data — showing setup inventory until peer mesh_status probes succeed.",emptyGraph:"No live mesh graph is available for this coordinator yet.",fieldMachine:"Machine",fieldLocality:"Locality",fieldWorkspace:"Workspace",fieldHead:"HEAD",fieldDirtyAheadBehind:"Dirty/ahead/behind",fieldSessions:"Sessions",fieldUpstream:"Upstream",fieldSource:"Source",fieldTransport:"Transport",fieldMachineId:"Machine id",fieldDaemonId:"Daemon id",fieldFrom:"From",fieldTo:"To",fieldLabel:"Label",fieldCompleted:"Completed",fieldFailed:"Failed",fieldLaunched:"Launched",fieldRecentFailures:"Recent failures",meshConnecting:"mesh connecting...",connecting:"connecting...",providerUnknown:"provider unknown"}},tg={login:{eyebrow:"云端登录",title:"登录 ADHDev",subtitle:"连接你的机器,接收审批和完成通知,让你的编码代理在你离开电脑时也能持续运行。",continueWith:"使用 {{provider}} 继续",connecting:"连接中...",devDivider:"开发",devLogin:"开发登录 (test_jwt_token)",providerNote:"GitHub 和 Google 仅用于身份验证。",errorUnverifiedEmail:"此登录提供方未返回已验证的邮箱,因此我们无法安全地为你登录。",termsPrefix:"继续即表示你同意我们的",termsLink:"服务条款",termsAnd:" 和 ",privacyLink:"隐私政策",termsSuffix:"。"},account:{title:"账户",subtitle:"个人资料、套餐和活动",tabAccount:"账户",tabBilling:"账单",tabActivity:"活动",profile:"个人资料",noName:"无名称",displayName:"显示名称",displayNameDesc:"在仪表板和团队工作区中显示的名称。",nicknamePlaceholder:"昵称",save:"保存",saving:"...",cancel:"取消",saved:"已保存",edit:"编辑",failedToSave:"保存失败",userId:"用户 ID",loadingProfile:"正在加载个人资料...",planLimits:"套餐限额",limitMachines:"机器",limitP2P:"P2P 连接",limitWebhooks:"Webhook",limitTurnRelay:"TURN 中继",enabled:"已启用",disabled:"已禁用",frozen:"已冻结",session:"会话",logout:"退出登录",logoutConfirm:"确定要退出登录吗?",logoutDesc:"在此设备上退出你的 ADHDev 账户。",dangerZone:"危险区域",dangerZoneDesc:"永久删除你的账户及所有相关数据。此操作无法撤销。",deleteAccount:"删除账户",deleteWillRemove:"这将永久删除:",deleteItemProfile:"你的个人资料和登录凭据",deleteItemKeys:"所有 API 密钥和连接令牌",deleteItemWebhooks:"Webhook 和投递历史",deleteItemPush:"推送通知订阅",deleteItemSessions:"共享会话和审计日志",deleteTypeConfirm:"输入 {{keyword}} 以确认:",deleting:"正在删除...",permanentlyDelete:"永久删除",failedToDeleteAccount:"删除账户失败",registeredMachines:"已注册的机器",machinesSummary:"已注册 {{count}} 台 · {{online}} 台在线",machinesLimit:"(上限: {{limit}})",loadingMachines:"正在加载机器...",noMachinesRegistered:"没有已注册的机器",runSetupPrefix:"在机器上运行 ",runSetupMiddle:",然后启动 ",runSetupSuffix:" 即可在此注册。",removeMachineConfirm:"移除此机器?重新连接时需再次运行 `adhdev setup`。",failedToDeleteMachine:"删除机器失败",failedToUpdate:"更新失败",rename:"重命名",online:"在线",connecting:"连接中",lastSeen:"最后在线 {{time}}",removeMachine:"移除机器",never:"从未",justNow:"刚刚",minutesAgo:"{{minutes}} 分钟前",hoursAgo:"{{hours}} 小时前",daysAgo:"{{days}} 天前"},billing:{currentPlan:"当前套餐:",statusTrial:"试用",statusActive:"有效",statusPastDue:"逾期",statusCanceled:"已取消",nextBilling:"下次扣款: {{date}}",trialEnds:"试用结束: {{date}}",accessUntil:"可用至: {{date}}",updatePayment:"请更新你的付款方式",managePayment:"管理付款和发票",couldNotOpenPortal:"无法打开账单门户",statMachines:"机器",statTeam:"团队",statTurnPerDay:"TURN 分钟/天",monthly:"按月",yearly:"按年",savePercent:"省 17%",paddleLoading:"Paddle 正在加载,请重试。",cancelConfirm:"确定要取消订阅吗?在计费周期结束前你仍可继续使用。",teamSeats:"团队席位",seatsUsed:"已使用 {{used}} / {{total}} 个席位",pricePerMonth:"${{price}}/月",cannotReduceSeats:"无法减少到 {{count}} 个席位以下(当前正在使用)。请先移除成员。",removeSeat:"− 移除席位",addSeat:"+ 添加席位",cancelSubscription:"取消订阅",cancelRetainAccess:"在当前计费周期结束前,你仍可使用 {{plan}} 功能。",cancelTeamDowngrade:" 所有团队成员将被降级为各自的个人套餐。"},activity:{filterPlaceholder:"按操作、资源或来源筛选...",refresh:"刷新",loading:"加载中...",noLogs:"无日志",noMatchingLogs:"未找到匹配的日志。",logsWillAppear:"操作发生时将显示在此处。",colAction:"操作",colResource:"资源",colSource:"来源",colTime:"时间",logCount:"{{count}} 条日志",logCountFiltered:" (从 {{total}} 条中筛选)"},webhooks:{title:"Webhook",subtitle:"实时事件通知",addWebhook:"+ 添加 Webhook",eventDaemonConnect:"守护进程已连接",eventDaemonDisconnect:"守护进程已断开",eventAgentStatus:"代理状态变更",eventApprovalRequired:"需要审批",failed:"失败",deleteConfirm:"删除此 Webhook?",testFailed:"测试失败",secretTitle:"Webhook 密钥",secretShownOncePrefix:"",secretShownOnce:"仅显示一次",secretShownOnceSuffix:"。用于验证 ",copy:"复制",done:"完成",newWebhook:"新建 Webhook",labelUrl:"URL",urlPlaceholder:"https://your-service.com/webhook",labelEvents:"事件",allEvents:"所有事件 (*)",creating:"创建中...",create:"创建",cancel:"取消",loading:"加载中...",noWebhooks:"无 Webhook",noWebhooksDesc:"接收有关事件的实时通知。",setupFirst:"设置第一个 Webhook",off:"关闭",autoDisabled:"已自动禁用",autoDisabledTitle:"连续 10 次失败后自动禁用",failuresWarning:"⚠ 失败 {{count}} 次",failuresTitle:"连续失败 {{count}} 次 — 将在 10 次时自动禁用",all:"全部",history:"历史",test:"测试",delete:"删除",deleting:"...",recentDeliveries:"最近投递",refresh:"刷新",noDeliveries:"暂无投递。使用 🧪 发送测试。",request:"请求",response:"响应",securityTitle:"安全",securityVerifyPrefix:"",securityVerifySuffix:" 与你的密钥进行验证",securityHttps:"仅使用 HTTPS 端点",securityAsync:"立即返回 2xx,异步处理",securityAutoDisable:"连续 10 次失败后自动禁用"},apiKeys:{title:"API 密钥",keyCount:"{{count}} 个密钥",playground:"调试台",create:"+ 创建",scopeDaemonRead:"守护进程读取",scopeDaemonReadDesc:"列出守护进程和状态",scopeDaemonControl:"守护进程控制",scopeDaemonControlDesc:"命令、启动/停止、断开",scopeAgentRead:"代理读取",scopeAgentReadDesc:"状态和聊天记录",scopeAgentControl:"代理控制",scopeAgentControlDesc:"发送、批准/拒绝",scopeTerminal:"终端",scopeTerminalDesc:"执行命令",scopeWebhooks:"Webhook",scopeWebhooksDesc:"管理钩子和投递",frozen:"已冻结",revokeConfirm:"撤销此 API 密钥?此操作无法撤销。",failedToLoad:"加载失败",failed:"失败",upgradePlan:"升级你的套餐 →",keyCreated:"密钥已创建!",copyNow:"立即复制 — 仅显示一次。",copied:"已复制",copy:"复制",testKey:"测试",dismiss:"关闭",playgroundTitle:"API 调试台",enterKeyToTest:"输入要测试的 API 密钥。",open:"打开",createKeyTitle:"创建 API 密钥",labelName:"名称",namePlaceholder:"例如 Production Bot",permissions:"权限 ({{count}})",createBtn:"创建",cancel:"取消",loading:"加载中...",noKeys:"无 API 密钥",noKeysDesc:"创建密钥以与外部服务集成。",createFirstKey:"创建第一个密钥",usedDate:"于 {{date}} 使用",neverUsed:"从未使用",revoke:"撤销",usageLabel:"用法:",apiReference:"API 参考 →"},auditLogs:{title:"审计日志",subtitle:"安全事件和 API 历史",refresh:"刷新",filterPlaceholder:"按操作、资源或来源筛选...",loading:"加载中...",noLogs:"无日志",noMatchingLogs:"未找到匹配的日志。",logsWillAppear:"操作发生时将显示在此处。",colAction:"操作",colResource:"资源",colSource:"来源",colTime:"时间",logCount:"{{count}} 条日志",logCountFiltered:" (从 {{total}} 条中筛选)"}},sg={chatHistory:"聊天记录",startNewChat:"+ 开始新聊天会话",creating:"⌛ 创建中...",searchPlaceholder:"搜索标题或预览",filterWorkspace:"按工作区筛选",filterModel:"按模型筛选",sortRecent:"最新",sortOldest:"最早",sortMessages:"消息最多",resumeReadyOnly:"仅可恢复",untitledSession:"无标题会话",noSavedPreview:"暂无保存的预览",workspaceUnknown:"工作区未知",selectedWorkspaceSuffix:" · 选定的工作区",msgCount:"{{count}} 条消息",statusActive:"活动",statusMissingWorkspace:"缺少工作区",statusResumeSelectedWorkspace:"在选定的工作区中恢复",statusResuming:"恢复中...",statusResume:"恢复",noMatchingHistory:"没有符合这些筛选条件的保存记录。",noRecentChats:"未找到最近的聊天会话。",refreshHistory:"刷新记录",refreshing:"⌛ 刷新中..."},ng={chat:Gb,chatPane:zb,chatInput:Vb,paneGroup:qb,terminal:Yb,conversation:Jb,cliView:Xb,launch:Qb,standalone:Zb,meshGraph:eg,cloud:tg,historyModal:sg},rg={copyMessage:"Copiar mensaje"},ag={connectingToMachine:"Conectando con tu máquina",establishingP2P:"Estableciendo conexión P2P",agentNotMonitored:"Agente no supervisado",clickToSwitchMonitoring:"Haz clic para cambiar la supervisión a este agente",agentPanelHidden:"El panel del agente aún no es visible",openPanelHint:"Abre el panel del agente o la vista de chat en la aplicación que estás usando para ver los mensajes",noMessagesYet:"Todavía no hay mensajes",loadingChat:"Cargando chat...",openPanel:"Abrir panel de {{label}}",switchingPanel:"Cambiando...",openingPanel:"Abriendo..."},og={attachImage:"Adjuntar imagen",placeholder:"Enviar mensaje a {{panel}}... (Shift+Enter para nueva línea)",sendMessage:"Enviar mensaje",dropImage:"Suelta la imagen aquí"},ig={noConversations:"Todavía no hay conversaciones",waitingForDaemon:"Esperando tu daemon",connectYourMachines:"Conecta tus máquinas",daemonDescription:"Inicia el daemon de ADHDev para conectar este panel. Una vez en línea, puedes iniciar sesiones con cualquier proveedor instalado.",installDescription:"Instala ADHDev en una máquina, inicia sesión y aparecerá aquí.",newSession:"Nueva sesión",newSessionDescription:"Una máquina conectada está lista. Inicia una nueva sesión con cualquier proveedor instalado — CLI, ACP o IDE."},lg={loadOlderOutput:"Cargar salida de terminal anterior",loadingOlder:"Cargando anteriores...",debug:"Depurar",copy:"Copiar",openControlKeys:"Abrir teclas de control del terminal",closeControlKeys:"Cerrar teclas de control del terminal"},cg={muteThis:"Silenciar este chat",unmuteThis:"Activar sonido de este chat",mutedTitle:"Silenciado — notificaciones desactivadas. Clic para reactivar.",muteTitle:"Silenciar notificaciones de este chat"},dg={switchToTerminal:"Cambiar a vista Terminal",switchToChat:"Cambiar a vista Chat"},ug={resumeSavedHistory:"Reanudar historial guardado",startFresh:"Empezar de nuevo",resumingSavedHistory:"Reanudando historial guardado…",startingFresh:"Empezando de nuevo…",startIde:"Iniciar IDE",startingIde:"Iniciando IDE…",startAcpSession:"Iniciar sesión ACP",startingAcpSession:"Iniciando sesión ACP…",recoverHostedRuntime:"Recuperar runtime alojado",hostedRuntimeRecoveryDescription:"Recuperación de respaldo para runtimes alojados tras interrupciones. Para continuidad normal, abre el historial guardado.",openSavedHistory:"Abrir historial guardado",savedHistoryTitle:"Historial guardado",savedHistoryHelper:"Usa el historial guardado cuando quieras continuidad en la misma conversación del proveedor.",savedHistoryEmpty:"Todavía no se encontró historial guardado.",refreshSavedHistory:"Actualizar historial guardado",refreshingSavedHistory:"Actualizando historial guardado…",startFreshWith:"¿Empezar de nuevo con {{label}}?",restart:"¿Reiniciar {{label}}?",startFreshReview:"Revisa el proveedor y la carpeta de destino antes de empezar de nuevo.",restartIdeReview:"Revisa o cambia el espacio de trabajo de destino antes de reiniciar este IDE.",restartStoppedReview:"Revisa o cambia el espacio de trabajo de destino antes de reiniciar esta sesión detenida.",confirmStartFresh:"Empezar de nuevo",confirmRestart:"Reiniciar",confirmStartingFresh:"Empezando de nuevo…",confirmRestarting:"Reiniciando…",resumeWith:"¿Reanudar el historial guardado con {{label}}?",resumeReview:"Revisa o cambia el espacio de trabajo de destino antes de reanudar el historial guardado."},pg={nav:{dashboard:"Dashboard",settings:"Settings",docs:"Docs",about:"About"},layout:{expandSidebar:"Expand sidebar",collapseSidebar:"Collapse sidebar",collapse:"Collapse"},auth:{loading:"Loading standalone dashboard…",loadError:"Failed to load standalone auth status: {{error}}",signInTitle:"Standalone sign-in",passwordProtected:"This self-hosted dashboard is protected by a local password.",tokenProtected:"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session.",passwordPlaceholder:"Enter standalone password",unlock:"Unlock dashboard",signingIn:"Signing in…",noPasswordEnabled:"Password login is not enabled on this server."},machine:{loading:"⏳ Loading machine...",awaitingInput:"Awaiting your input ↑"},settings:{title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",infoNotice:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint.",publicHostWarning:"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.",daemonSection:"Daemon",daemonDescription:"Connection health and local endpoints for the self-hosted runtime.",versionLabel:"Version",statusLabel:"Status",statusRunning:"● Running",statusNotConnected:"○ Not connected",currentBindLabel:"Current bind",defaultBindLabel:"Default bind",authLabel:"Auth",authPassword:"Password enabled",authToken:"Token enabled",authNone:"No auth configured",networkSection:"Network Access",networkDescription:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",networkHint:"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.",localhostLabel:"Localhost only",localhostHint:"Bind to 127.0.0.1. Best when only this machine should open the dashboard.",allInterfacesLabel:"All interfaces",allInterfacesHint:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points.",saveNetworkMode:"Save default network mode",saving:"Saving…",networkRestartHint:"Applies on next standalone restart. Current run stays bound to {{host}}.",networkSavedAll:"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.",networkSavedLocal:"Default standalone network mode set to localhost only. Restart standalone to apply it.",securitySection:"Dashboard Security",securityDescription:"Self-hosted-only password protection for browsers using this standalone dashboard.",passwordSet:"A local password is currently required for browser access. Existing sessions are rotated when you change it.",passwordNotSet:"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended.",currentPasswordPlaceholder:"Current password",currentPasswordFirstTimePlaceholder:"Current password (not needed for first setup)",newPasswordPlaceholder:"New password",newPasswordFirstTimePlaceholder:"New standalone password",confirmPasswordPlaceholder:"Confirm new password",updatePassword:"Update password",enablePassword:"Enable password",disablePassword:"Disable password",passwordUpdated:"Standalone password updated.",passwordEnabled:"Standalone password enabled.",passwordDisabled:"Standalone password disabled.",passwordTooShort:"Password must be at least 4 characters.",passwordMismatch:"New password and confirmation do not match.",detectedIdesSection:"Detected IDEs",detectedIdesDescription:"Editors discovered by the local daemon on this machine.",noIdesDetected:"No IDEs detected. Start an IDE to see it here.",machineSection:"Machine",machineDescription:"The local burrow exposed by your standalone daemon.",daemonNotConnected:"Daemon not connected. Run 'adhdev-standalone' to start.",appearanceSection:"Appearance",appearanceDescription:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",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.",fontsLabel:"Fonts",fontsDescription:"Standalone-only typography overrides for chat text, markdown code, and terminal output.",fontsSaved:"Standalone chat fonts saved for this self-hosted dashboard.",notificationsSection:"Notifications",notificationsDescription:"Browser prompts and local sound cues for agent activity.",soundEffectsLabel:"Sound Effects",soundEffectsDescription:"Play a sound when agent completes or needs approval",profileSection:"Profile",profileDescription:"How your name appears in local chat threads and dashboard views.",displayNameLabel:"Display Name",displayNameHint:"Your name shown in chat threads and on the team dashboard.",displayNamePlaceholder:"Anonymous"},onboarding:{title:"Welcome to ADHDev",selectedCount_one:"{{count}} provider selected",selectedCount_other:"{{count}} providers selected",skip:"Skip",installing:"Installing…",done:"Done",installCount:"Install {{count}}",intro:"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 Burrow → Providers → Add provider.",loadingRegistry:"Loading registry…",loadError:"Failed to load registry: {{error}}",noProviders:"No providers in this category.",installed:"✓ installed",installFailed:"✗ {{error}}"},about:{title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",selfHostedEdition:"Self-hosted edition",headline:"Keep the same dashboard experience, with the runtime fully on-device.",description:"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.",docs:"Docs ↗",github:"GitHub ↗",tryCloud:"Try Cloud ↗",includedSection:"Included in standalone",includedDescription:"The local-first feature set available without the cloud control plane.",inventorySection:"Built-in inventory",inventoryDescription:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",cloudExtrasSection:"Cloud-only extras",cloudExtrasDescription:"Capabilities that need the hosted control plane or team infrastructure.",comparisonSection:"Self-hosted vs Cloud",comparisonDescription:"The product split at a glance.",featureHeader:"Feature",selfhostHeader:"Selfhost",cloudHeader:"Cloud",cloudOptional:"Cloud is optional, not required",cloudOptionalDescription:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",compareCloud:"Compare Cloud ↗",discord:"Discord ↗"},fonts:{fontOverridesNotice:"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.",chat:"Chat text",chatDescription:"Assistant/user prose, markdown text, thought cards, and system notes.",code:"Code blocks",codeDescription:"Markdown code fences, inline code, and preformatted command output.",terminal:"Terminal",terminalDescription:"Terminal transcript cards and tool/command rows in chat mode.",livePreview:"Live preview",resolvedStack:"Resolved stack:",defaults:"Defaults:",saveFontSettings:"Save font settings",revertToSaved:"Revert to saved",resetToDefaults:"Reset to defaults",saving:"Saving…"}},hg={panel:{selectNode:"Select a node to view details.",submoduleBadge:"Submodule",dirtyBadge:"Dirty",outOfSyncBadge:"Out of sync",conflictBadge:"Conflict",orphanBadge:"Orphan",fieldWorkspace:"Workspace",fieldBranch:"Branch",fieldUpstream:"Upstream",fieldUpstreamState:"Upstream state",fieldHead:"HEAD",fieldSubmodulePath:"Submodule path",fieldSubmoduleCommit:"Submodule commit",fieldParentNode:"Parent node",fieldAhead:"Ahead",fieldBehind:"Behind",fieldDirtyFiles:"Dirty files",fieldActiveSessions:"Active sessions",fieldProviders:"Providers",fieldConnection:"Connection",fieldLinkNote:"Link note",fieldError:"Error",orphanReasons:"Orphan reasons",attachedChats:"Attached chats",providerUnknown:"provider unknown",statusAwaiting:"awaiting approval",statusGenerating:"generating",statusIdle:"idle",statusCoordinator:"coordinator",statusWorker:"worker",runtimeAgeNotReported:"runtime age not reported",upstreamVerified:"verified",upstreamUnverifiedFetch:"unverified (fetch failed)",upstreamUnverified:"unverified",upstreamUnavailable:"unavailable",needsFollowUp:"needs follow-up",refined:"refined"},obs:{tabOverview:"Overview",tabStatus:"Status",tabGraph:"Graph",convergenceMergedToMain:"Merged to main",convergenceNeedsMerge:"Needs merge",convergenceBlockedReview:"Blocked — needs review",convergenceCleanup:"Ready to clean up",convergenceNotMergeable:"Not mergeable",followUpLabel:"Follow-up — {{status}}",selectedNode:"Selected node",selectedEdge:"Selected edge",activeSessions:"Active Sessions",ledger:"Ledger (mesh-wide)",queueTasks:"Queue tasks",keyWarning:"Key warning",healResult:"Heal result",healPreview:"Heal preview",noResultCode:"No result code returned.",health:"Health",legend:"Legend",checking:"Checking",heal:"Heal",loadingGraph:"Loading graph…",bootstrapBanner:"Awaiting live data — showing setup inventory until peer mesh_status probes succeed.",emptyGraph:"No live mesh graph is available for this coordinator yet.",fieldMachine:"Machine",fieldLocality:"Locality",fieldWorkspace:"Workspace",fieldHead:"HEAD",fieldDirtyAheadBehind:"Dirty/ahead/behind",fieldSessions:"Sessions",fieldUpstream:"Upstream",fieldSource:"Source",fieldTransport:"Transport",fieldMachineId:"Machine id",fieldDaemonId:"Daemon id",fieldFrom:"From",fieldTo:"To",fieldLabel:"Label",fieldCompleted:"Completed",fieldFailed:"Failed",fieldLaunched:"Launched",fieldRecentFailures:"Recent failures",meshConnecting:"mesh connecting...",connecting:"connecting...",providerUnknown:"provider unknown"}},mg={login:{eyebrow:"Inicio de sesión en la nube",title:"Inicia sesión en ADHDev",subtitle:"Conecta tus máquinas, recibe notificaciones de aprobación y finalización, y mantén tus agentes de programación en marcha cuando estés lejos de tu escritorio.",continueWith:"Continuar con {{provider}}",connecting:"Conectando...",devDivider:"dev",devLogin:"Inicio de sesión dev (test_jwt_token)",providerNote:"GitHub y Google se usan solo para autenticación.",errorUnverifiedEmail:"Este proveedor de inicio de sesión no devolvió un correo verificado, por lo que no pudimos iniciar tu sesión de forma segura.",termsPrefix:"Al continuar, aceptas nuestros ",termsLink:"Términos de servicio",termsAnd:" y la ",privacyLink:"Política de privacidad",termsSuffix:"."},account:{title:"Cuenta",subtitle:"Perfil, plan y actividad",tabAccount:"Cuenta",tabBilling:"Facturación",tabActivity:"Actividad",profile:"Perfil",noName:"Sin nombre",displayName:"Nombre para mostrar",displayNameDesc:"Tu nombre mostrado en el panel y los espacios de equipo.",nicknamePlaceholder:"Apodo",save:"Guardar",saving:"...",cancel:"Cancelar",saved:"Guardado",edit:"Editar",failedToSave:"Error al guardar",userId:"ID de usuario",loadingProfile:"Cargando perfil...",planLimits:"Límites del plan",limitMachines:"Máquinas",limitP2P:"Conexiones P2P",limitWebhooks:"Webhooks",limitTurnRelay:"Relé TURN",enabled:"Activado",disabled:"Desactivado",frozen:"Congelado",session:"Sesión",logout:"Cerrar sesión",logoutConfirm:"¿Seguro que quieres cerrar sesión?",logoutDesc:"Cierra la sesión de tu cuenta de ADHDev en este dispositivo.",dangerZone:"Zona de peligro",dangerZoneDesc:"Elimina permanentemente tu cuenta y todos los datos asociados. Esta acción no se puede deshacer.",deleteAccount:"Eliminar cuenta",deleteWillRemove:"Esto eliminará permanentemente:",deleteItemProfile:"Tu perfil y credenciales de inicio de sesión",deleteItemKeys:"Todas las claves API y tokens de conexión",deleteItemWebhooks:"Webhooks e historial de entregas",deleteItemPush:"Suscripciones de notificaciones push",deleteItemSessions:"Sesiones compartidas y registros de auditoría",deleteTypeConfirm:"Escribe {{keyword}} para confirmar:",deleting:"Eliminando...",permanentlyDelete:"Eliminar permanentemente",failedToDeleteAccount:"Error al eliminar la cuenta",registeredMachines:"Máquinas registradas",machinesSummary:"{{count}} registradas · {{online}} en línea",machinesLimit:"(límite: {{limit}})",loadingMachines:"Cargando máquinas...",noMachinesRegistered:"No hay máquinas registradas",runSetupPrefix:"Ejecuta ",runSetupMiddle:" y luego inicia ",runSetupSuffix:" en una máquina para registrarla aquí.",removeMachineConfirm:"¿Quitar esta máquina? Deberá ejecutar `adhdev setup` de nuevo para reconectarse.",failedToDeleteMachine:"Error al eliminar la máquina",failedToUpdate:"Error al actualizar",rename:"Renombrar",online:"En línea",connecting:"Conectando",lastSeen:"Última conexión {{time}}",removeMachine:"Quitar máquina",never:"Nunca",justNow:"Justo ahora",minutesAgo:"hace {{minutes}} min",hoursAgo:"hace {{hours}} h",daysAgo:"hace {{days}} d"},billing:{currentPlan:"Plan actual:",statusTrial:"Prueba",statusActive:"Activo",statusPastDue:"Vencido",statusCanceled:"Cancelado",nextBilling:"Próximo cobro: {{date}}",trialEnds:"La prueba termina: {{date}}",accessUntil:"Acceso hasta: {{date}}",updatePayment:"Actualiza tu método de pago",managePayment:"Gestionar pagos y facturas",couldNotOpenPortal:"No se pudo abrir el portal de facturación",statMachines:"Máquinas",statTeam:"Equipo",statTurnPerDay:"min TURN/día",monthly:"Mensual",yearly:"Anual",savePercent:"Ahorra 17%",paddleLoading:"Paddle se está cargando, inténtalo de nuevo.",cancelConfirm:"¿Seguro que quieres cancelar tu suscripción? Conservarás el acceso hasta el final de tu período de facturación.",teamSeats:"Asientos del equipo",seatsUsed:"{{used}} / {{total}} asientos usados",pricePerMonth:"${{price}}/mes",cannotReduceSeats:"No se puede reducir por debajo de {{count}} asientos (en uso). Quita miembros primero.",removeSeat:"− Quitar asiento",addSeat:"+ Añadir asiento",cancelSubscription:"Cancelar suscripción",cancelRetainAccess:"Conservarás el acceso a las funciones de {{plan}} hasta el final de tu período de facturación actual.",cancelTeamDowngrade:" Todos los miembros del equipo pasarán a sus planes personales."},activity:{filterPlaceholder:"Filtrar por acción, recurso u origen...",refresh:"Actualizar",loading:"Cargando...",noLogs:"Sin registros",noMatchingLogs:"No se encontraron registros coincidentes.",logsWillAppear:"Las acciones aparecerán aquí a medida que sucedan.",colAction:"Acción",colResource:"Recurso",colSource:"Origen",colTime:"Hora",logCount:"{{count}} registros",logCountFiltered:" (filtrado de {{total}})"},webhooks:{title:"Webhooks",subtitle:"Notificaciones de eventos en tiempo real",addWebhook:"+ Añadir webhook",eventDaemonConnect:"Daemon conectado",eventDaemonDisconnect:"Daemon desconectado",eventAgentStatus:"Cambio de estado del agente",eventApprovalRequired:"Aprobación requerida",failed:"Error",deleteConfirm:"¿Eliminar este webhook?",testFailed:"Error en la prueba",secretTitle:"Secreto del webhook",secretShownOncePrefix:"Se muestra ",secretShownOnce:"solo una vez",secretShownOnceSuffix:". Úsalo para verificar ",copy:"Copiar",done:"Listo",newWebhook:"Nuevo webhook",labelUrl:"URL",urlPlaceholder:"https://tu-servicio.com/webhook",labelEvents:"Eventos",allEvents:"Todos los eventos (*)",creating:"Creando...",create:"Crear",cancel:"Cancelar",loading:"Cargando...",noWebhooks:"Sin webhooks",noWebhooksDesc:"Recibe notificaciones en tiempo real sobre eventos.",setupFirst:"Configurar el primer webhook",off:"OFF",autoDisabled:"Autodesactivado",autoDisabledTitle:"Autodesactivado tras 10 fallos consecutivos",failuresWarning:"⚠ {{count}} fallos",failuresTitle:"{{count}} fallos consecutivos — se autodesactivará a los 10",all:"TODOS",history:"Historial",test:"Probar",delete:"Eliminar",deleting:"...",recentDeliveries:"Entregas recientes",refresh:"Actualizar",noDeliveries:"Aún no hay entregas. Usa 🧪 para enviar una prueba.",request:"SOLICITUD",response:"RESPUESTA",securityTitle:"Seguridad",securityVerifyPrefix:"Verifica ",securityVerifySuffix:" con tu secreto",securityHttps:"Usa solo endpoints HTTPS",securityAsync:"Devuelve 2xx de inmediato, procesa de forma asíncrona",securityAutoDisable:"Autodesactivado tras 10 fallos consecutivos"},apiKeys:{title:"Claves API",keyCount:"{{count}} claves",playground:"Área de pruebas",create:"+ Crear",scopeDaemonRead:"Lectura de daemon",scopeDaemonReadDesc:"Listar daemons y estado",scopeDaemonControl:"Control de daemon",scopeDaemonControlDesc:"Comandos, iniciar/detener, desconectar",scopeAgentRead:"Lectura de agente",scopeAgentReadDesc:"Estado e historial de chat",scopeAgentControl:"Control de agente",scopeAgentControlDesc:"Enviar, aprobar/rechazar",scopeTerminal:"Terminal",scopeTerminalDesc:"Ejecutar comandos",scopeWebhooks:"Webhooks",scopeWebhooksDesc:"Gestionar hooks y entregas",frozen:"Congelado",revokeConfirm:"¿Revocar esta clave API? Esto no se puede deshacer.",failedToLoad:"Error al cargar",failed:"Error",upgradePlan:"Mejora tu plan →",keyCreated:"¡Clave creada!",copyNow:"Copia ahora — se muestra solo una vez.",copied:"Copiado",copy:"Copiar",testKey:"Probar",dismiss:"Descartar",playgroundTitle:"Área de pruebas API",enterKeyToTest:"Introduce una clave API para probar.",open:"Abrir",createKeyTitle:"Crear clave API",labelName:"Nombre",namePlaceholder:"p. ej. Production Bot",permissions:"Permisos ({{count}})",createBtn:"Crear",cancel:"Cancelar",loading:"Cargando...",noKeys:"Sin claves API",noKeysDesc:"Crea una clave para integrarla con servicios externos.",createFirstKey:"Crear la primera clave",usedDate:"Usada {{date}}",neverUsed:"Nunca usada",revoke:"Revocar",usageLabel:"Uso:",apiReference:"Referencia API →"},auditLogs:{title:"Registros de auditoría",subtitle:"Eventos de seguridad e historial de API",refresh:"Actualizar",filterPlaceholder:"Filtrar por acción, recurso u origen...",loading:"Cargando...",noLogs:"Sin registros",noMatchingLogs:"No se encontraron registros coincidentes.",logsWillAppear:"Las acciones aparecerán aquí a medida que sucedan.",colAction:"Acción",colResource:"Recurso",colSource:"Origen",colTime:"Hora",logCount:"{{count}} registros",logCountFiltered:" (filtrado de {{total}})"}},fg={chatHistory:"Historial de chat",startNewChat:"+ Iniciar nueva sesión de chat",creating:"⌛ Creando...",searchPlaceholder:"Buscar título o vista previa",filterWorkspace:"Filtrar por workspace",filterModel:"Filtrar por modelo",sortRecent:"Más recientes",sortOldest:"Más antiguos primero",sortMessages:"Más mensajes",resumeReadyOnly:"Solo reanudables",untitledSession:"Sesión sin título",noSavedPreview:"Aún no hay vista previa guardada",workspaceUnknown:"Workspace desconocido",selectedWorkspaceSuffix:" · workspace seleccionado",msgCount:"{{count}} mensajes",statusActive:"ACTIVA",statusMissingWorkspace:"FALTA WORKSPACE",statusResumeSelectedWorkspace:"REANUDAR EN WORKSPACE SELECCIONADO",statusResuming:"REANUDANDO...",statusResume:"REANUDAR",noMatchingHistory:"Ningún historial guardado coincide con estos filtros.",noRecentChats:"No se encontraron sesiones de chat recientes.",refreshHistory:"Actualizar historial",refreshing:"⌛ Actualizando..."},xg={chat:rg,chatPane:ag,chatInput:og,paneGroup:ig,terminal:lg,conversation:cg,cliView:dg,launch:ug,standalone:pg,meshGraph:hg,cloud:mg,historyModal:fg},zo="lang",Wl="common",bg={en:{common:ob},ko:{common:Pb},ja:{common:Kb},"zh-CN":{common:ng},es:{common:xg}};function gg(){try{const e=localStorage.getItem(zo);if(un(e))return e}catch{}return null}function mu(){const e=gg();return e||(typeof navigator<"u"?_x(navigator.language):Xn)}function Vo(e){typeof document>"u"||document.documentElement.setAttribute("lang",e)}let Ul=!1;function yg(){if(Ul)return wt;Ul=!0;const e=mu();return wt.use(Sm).init({resources:bg,lng:e,fallbackLng:Xn,supportedLngs:hu,ns:[Wl],defaultNS:Wl,interpolation:{escapeValue:!1},returnEmptyString:!1}),Vo(e),wt}var vg=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function wg(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function Zt(e,t){if(wg(t==null?void 0:t.activeModal))return"waiting_approval";const n=String(e||"idle").trim().toLowerCase();return n==="waiting_approval"?"waiting_approval":n==="waiting_choice"?"waiting_choice":vg.has(n)?"generating":n==="error"?"error":n==="stopped"?"stopped":n==="starting"?"starting":n==="panel_hidden"?"panel_hidden":n==="not_monitored"?"not_monitored":n==="disconnected"?"disconnected":"idle"}function qo(e){return Zt(e)==="generating"}function Kl(e,t){return Zt(e,t)==="waiting_approval"}function ft(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Pe(...e){for(const t of e){if(typeof t!="string")continue;const n=t.trim();if(n)return n}}function zt(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function Et(...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 kg(e,t){const n=typeof e=="string"?e.trim().replace(/[\\/]+$/,""):"",r=typeof t=="string"?t.trim():"";if(r){if(/^(?:[A-Za-z]:[\\/]|\/)/.test(r))return r;if(n)return`${n}/${r.replace(/^[\\/]+/,"")}`}}function Ri(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 jg(e,t){if(!Array.isArray(e))return;const n=e.map(r=>{const a=ft(r),o=Pe(a.path),i=Pe(a.commit),u=Pe(a.repoPath,a.repo_root)??kg(t,o);if(!o||!i)return null;const c={path:o,commit:i,dirty:Et(a.dirty)??!1,outOfSync:Et(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:zt(a.lastCheckedAt,a.last_checked_at)??Date.now()};u&&(c.repoPath=u);const p=Pe(a.error);return p&&(c.error=p),c}).filter(r=>r!==null);return n.length>0?n:void 0}function Sg(e){return Et(e.isGitRepo)!==void 0||!!Pe(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||!!Pe(e.repoRoot,e.repo_root,e.workspace)||zt(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 Wr(e,t,n){const r=Et(e.isGitRepo);if(!Object.keys(e).length||!Sg(e))return;const a=r??!0,o=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(w=>typeof w=="string"):[],i=zt(e.conflicts)??o.length,u=Et(e.hasConflicts)??i>0,c=Pe(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,p=jg(e.submodules,c),d=Pe(e.upstreamStatus,e.upstream_status),m=zt(e.upstreamFetchedAt,e.upstream_fetched_at),h=Pe(e.upstreamFetchError,e.upstream_fetch_error),g=Pe(e.error),v=zt(e.staged)??0,f=zt(e.modified)??0,y=zt(e.untracked)??0,j=zt(e.deleted)??0,x=zt(e.renamed)??0;return{workspace:Pe(e.workspace,t.workspace)||"",repoRoot:c??null,isGitRepo:a,branch:Pe(e.branch)??null,headCommit:Pe(e.headCommit)??null,headMessage:Pe(e.headMessage)??null,upstream:Pe(e.upstream)??null,upstreamStatus:d??"unchecked",...m!==void 0?{upstreamFetchedAt:m}:{},...h?{upstreamFetchError:h}:{},ahead:zt(e.ahead)??0,behind:zt(e.behind)??0,staged:v,modified:f,untracked:y,deleted:j,renamed:x,dirty:Et(e.dirty,e.isDirty,e.is_dirty)??(v+f+y+j+x>0||u),hasConflicts:u,conflictFiles:o,stashCount:zt(e.stashCount,e.stash_count)??0,lastCheckedAt:(n==null?void 0:n.lastCheckedAt)??zt(e.lastCheckedAt,e.last_checked_at)??Date.now(),...p?{submodules:p}:{},...g?{error:g}:{}}}function Ng(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+=Ri(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 Cg(e,t){const n=ft(e.lastGit??e.last_git),r=ft(n.result),a=ft(n.status),o=ft(r.status),i=ft(e.lastProbe??e.last_probe),u=ft(i.git),c=ft(u.result),p=ft(u.status),d=ft(c.status),m=t==null?void 0:t.lastCheckedAt;let h=null;for(const g of[a,o,p,d]){const v=Wr(g,e,{lastCheckedAt:m??Date.now()});if(!v)continue;const f=Ng(v);(!h||f>h.score)&&(h={git:v,score:f})}return h==null?void 0:h.git}function Mg(e){const t=[Pe(e.workspace),Pe(e.providerType,e.provider),Pe(e.role),Pe(e.state,e.status),Pe(e.title),Pe(e.createdAt,e.created_at),Pe(e.startedAt,e.started_at)].filter(n=>!!n);if(t.length!==0)return`synthetic:${t.join("|")}`}function Yo(e){const t=ft(e),n=Pe(t.sessionId,t.session_id,t.id)??Mg(t);return n?{sessionId:n,...Pe(t.providerType,t.provider)?{providerType:Pe(t.providerType,t.provider)}:{},...Pe(t.state,t.status)?{state:Pe(t.state,t.status)}:{},...Pe(t.chatStatus,t.chat_status)?{chatStatus:Pe(t.chatStatus,t.chat_status)}:{},...Pe(t.lifecycle)?{lifecycle:Pe(t.lifecycle)}:{},...Pe(t.surfaceKind,t.surface_kind)?{surfaceKind:Pe(t.surfaceKind,t.surface_kind)}:{},...Pe(t.recoveryState,t.recovery_state)?{recoveryState:Pe(t.recoveryState,t.recovery_state)}:{},...Pe(t.workspace)?{workspace:Pe(t.workspace)}:{},...Pe(t.title)?{title:Pe(t.title)}:{},...Pe(t.role)?{role:Pe(t.role)}:{},...Et(t.isSelfCoordinator,t.is_self_coordinator)!==void 0?{isSelfCoordinator:Et(t.isSelfCoordinator,t.is_self_coordinator)}:{},...Pe(t.statusNote,t.status_note)?{statusNote:Pe(t.statusNote,t.status_note)}:{},...Pe(t.createdAt,t.created_at)?{createdAt:Pe(t.createdAt,t.created_at)}:{},...Pe(t.startedAt,t.started_at)?{startedAt:Pe(t.startedAt,t.started_at)}:{},...Pe(t.lastActivityAt,t.last_activity_at)?{lastActivityAt:Pe(t.lastActivityAt,t.last_activity_at)}:{},...Et(t.isCached,t.is_cached)!==void 0?{isCached:Et(t.isCached,t.is_cached)}:{}}:null}function Ag(e){const t=e&&typeof e=="object"?e:{};return Pe(t.id,t.nodeId,t.node_id)}function Ig(e,t){if(!t)return!1;const n=t.trim();return n?Ag(e)===n:!1}var Tg=["daemon_","standalone_"];function Gl(e){const t=Pe(e);if(t){for(const n of Tg)if(t.startsWith(n))return t.slice(n.length).trim()||void 0;return t}}function Os(e,t){const n=Gl(e),r=Gl(t);return!n||!r?!1:n===r}var Pg=["easy","medium","difficult","freeform"];function _t(e){return(typeof e=="string"?e.trim():"")||void 0}function ws(e,t){const n=_t(t);return n?`${e}:${n}`:void 0}function Ms(e,t,n){const r=ws(t,n),a=_t(n);r&&e.push(r),a&&e.push(a)}function pn(e){const t=[],n=new Set;for(const r of e)!r||n.has(r)||(n.add(r),t.push(r));return t}function fu(e){return _t(e.providerSessionId)||_t(e.sessionId)||_t(e.tabKey)||_t(e.routeId)}function Ca(e){return pn([_t(e.historySessionId),_t(e.providerSessionId),_t(e.sessionId)])}function Qn(e){const t=[];return Ms(t,"provider",e.providerSessionId),Ms(t,"session",e.sessionId),Ms(t,"tab",e.tabKey),Ms(t,"route",e.routeId),pn(t)}function Dg(e){const t=[];return _t(e.providerSessionId)?(Ms(t,"provider",e.providerSessionId),pn(t)):_t(e.sessionId)?(Ms(t,"session",e.sessionId),pn(t)):_t(e.tabKey)?(Ms(t,"tab",e.tabKey),pn(t)):_t(e.routeId)?(Ms(t,"route",e.routeId),pn(t)):[]}function xu(e){return ws("provider",e.providerSessionId)||ws("session",e.sessionId)||ws("tab",e.tabKey)||ws("route",e.routeId)||"unknown:"}function Ma(e){return Ca(e)[0]}function Aa(e){const t=_t(e.sessionId),n=Ma(e);if(n&&!(t&&n===t))return n}function Lg(e){const t=_t(e.providerSessionId),n=_t(e.sessionId),r=_t(e.tabKey),a=_t(e.routeId),o=[ws("provider",t),ws("session",n),ws("tab",r),ws("route",a)].filter(c=>typeof c=="string"),i=Qn({providerSessionId:t,sessionId:n,tabKey:r,routeId:a}),u=xu({providerSessionId:t,sessionId:n,tabKey:r,routeId:a});return{providerSessionId:t,sessionId:n,tabKey:r,routeId:a,canonicalKey:u,targetKey:u,targetValue:fu({providerSessionId:t,sessionId:n,tabKey:r,routeId:a}),historySessionId:Ma({providerSessionId:t,sessionId:n}),runtimeSessionId:n,allKeys:o,lookupKeys:i}}function Jo(e,t){const n=Lg(e);return Dg(t).some(r=>n.lookupKeys.includes(r))}function bu(e){const t=String(e.daemonId||"").trim(),n=String(e.id||"").trim();return t&&n.startsWith(`${t}:`)?n.slice(t.length+1):n}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 Rg(e,t){const n=String(e.daemonId||"").trim(),r=String(e.id||"").trim(),a=bu(e);if(a&&t.has(a))return`mesh:${a}`;const o=String(e.ownerDaemonId||"").trim()||n;return o?a?`${o}:${a}`:o:r}function Ja(e,t){return t||e||"unknown"}function _g(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 Eg(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const n=Math.floor(t/60),r=t%60;if(n<24)return r>0?`${n}h ${r}m`:`${n}h`;const a=Math.floor(n/24),o=n%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 n=typeof t=="string"?t.trim():"";if(n)return n;const r=typeof e=="string"?e.trim():"";if(!r)return"";const a=r.replace(/[\\/]+$/,""),o=a.split(/[\\/]/).filter(Boolean);return o[o.length-1]||a}function $g(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const t=e.split("_"),n=t[t.length-1];return n.length>12?`Machine-${n.substring(0,8)}`:n}return e}function Fg(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function Bg(e){return $g(e.trim().replace(/\.local$/i,""))}function Hg(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function yu(e,t={}){var a,o;const n=[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&&!Fg(i));if(n&&n!=="Unknown")return Bg(n);const r=t.fallbackId||e.id;return r?`Machine-${r.substring(0,8)}`:t.fallbackLabel||"Machine"}function ts(e,t={}){return Hg(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,n={}){const r=String(t).trim();if(!e||!Array.isArray(e.items)||!r)return"";const a=e.items.find(o=>String((o==null?void 0:o.id)||"").trim()===r);return a?String(n.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function Js(e,t){return vu(e).join(" · ")}function ir(e){return e.transport==="pty"}function hn(e){return e.transport==="acp"}function Og(e,t){var n,r;return(n=t==null?void 0:t.providerLabels)!=null&&n[e]?t.providerLabels[e]:(r=t==null?void 0:t.providerLabels)!=null&&r[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,n){const r=(e||"").trim().toLowerCase();if(!r)return!0;const a=(t||"").trim().toLowerCase(),o=(n||"").trim().toLowerCase(),i=$t(n||"").trim().toLowerCase();return r===a||r===o||r===i}function Wg(e,t=[],n=[]){var c,p,d,m;const r=Zt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal});if(r==="waiting_approval")return"waiting_approval";if(r==="waiting_choice")return"waiting_choice";if(r==="generating")return"generating";const a=t.find(h=>Kl(h.status,{activeModal:h.activeModal})||qo(h.status));if(a)return Zt(a.status,{activeModal:a.activeModal});const o=n.find(h=>Kl(h.status,{activeModal:h.activeModal})||qo(h.status));if(o)return Zt(o.status,{activeModal:o.activeModal});if(r&&r!=="idle")return r;const i=Zt((c=t[0])==null?void 0:c.status,{activeModal:(p=t[0])==null?void 0:p.activeModal});if(i!=="idle")return i;const u=Zt((d=n[0])==null?void 0:d.status,{activeModal:(m=n[0])==null?void 0:m.activeModal});return u!=="idle"?u:"idle"}function Ug(e){return Zt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Kg(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,n=["generating","waiting_approval","waiting_choice","connected","idle","panel_hidden"];for(const r of e){const a=(r.name||r.id||"").toLowerCase().replace(/\s+/g,"-"),o=t.get(a),i=Zt(r.status);if(!o){t.set(a,{...r,status:i});continue}const u=n.indexOf(o.status||"idle"),c=n.indexOf(i||"idle");c>=0&&(u<0||c<u)&&t.set(a,{...r,status:i})}return Array.from(t.values())}function Gg(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 zg(e){var n,r;const t=(r=(n=e==null?void 0:e.messages)==null?void 0:n.at)==null?void 0:r.call(n,-1);return t&&Gg(t.receivedAt)||0}function Vg(e){return(e.recentLaunches||[]).reduce((n,r)=>Math.max(n,r.lastLaunchedAt||0),0)}function Qo(e){return Math.max(Vg(e),zg(e.activeChat))}function qg(e,t,n,r,a,o){const i=t-e;if(i!==0)return i;const u=n.localeCompare(r);return u!==0?u:a.localeCompare(o)}function _i(e,t){return qg(Qo(e),Qo(t),ts(e,{fallbackId:e.id}),ts(t,{fallbackId:t.id}),e.id,t.id)}const ku="adhdev_notification_prefs",Vl={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Yg(){try{const e=localStorage.getItem(ku);if(e){const t=JSON.parse(e);return{...Vl,...t}}}catch{}return{...Vl}}function Jg(e){try{localStorage.setItem(ku,JSON.stringify(e))}catch{}}let vs=Yg(),Ur=[];function Xg(){Ur.forEach(e=>e())}function Qg(e){vs={...vs,...e},Jg(vs),Xg()}function Zg(){const[,e]=l.useState(0);l.useEffect(()=>{const n=()=>e(r=>r+1);return Ur.push(n),()=>{Ur=Ur.filter(r=>r!==n)}},[]);const t=l.useCallback(n=>{Qg(n)},[]);return[{...vs},t]}function Zn(e){if(!vs.globalEnabled)return!1;switch(e){case"disconnect":return vs.disconnectAlert;case"completion":return vs.completionAlert;case"approval":return vs.approvalAlert;case"browser":return vs.browserNotifications;default:return!0}}const ey={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function ju(){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 ty(e){return e!==!1}async function sy(){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,n){if(Su())try{const r=new Notification(e,{body:t,icon:"/otter-logo.png",tag:n||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>r.close(),8e3),r.onclick=()=>{window.focus(),r.close()}}catch{}}function ny(e,t={}){const n={...ey,...t},r=l.useRef(new Map),a=l.useRef(0),[o,i]=l.useState(null);l.useEffect(()=>{let c=!1;return sy().then(p=>{c||i(p)}),()=>{c=!0}},[]);const u=l.useCallback((c,p,d)=>{const m=Date.now();m-a.current<n.throttleMs||(a.current=m,Zo(c,p,d))},[n.throttleMs]);l.useEffect(()=>{var c;if(!(!n.enabled||!Su())&&Zn("browser")&&!ty(o)){if(document.hasFocus()){for(const p of e)r.current.set(p.id,Zt(p.status,{activeModal:p.activeModal}));return}for(const p of e){const d=r.current.get(p.id),m=Zt(p.status,{activeModal:p.activeModal}),h=p.name||p.id;if(p.muted){r.current.set(p.id,m);continue}if(n.onApproval&&Zn("approval")&&m==="waiting_approval"&&d!=="waiting_approval"){const g=((c=p.activeModal)==null?void 0:c.message)||"Action requires your approval";u(`🔔 ${h} — Approval needed`,g.slice(0,120),`approval-${p.id}`)}n.onComplete&&Zn("completion")&&qo(d)&&m==="idle"&&u(`✅ ${h} — Task complete`,"Agent has finished generating",`complete-${p.id}`),n.onError&&m==="error"&&d!=="error"&&u(`⚠️ ${h} — Error`,"Agent encountered an error",`error-${p.id}`),r.current.set(p.id,m)}}},[e,n.enabled,n.onApproval,n.onComplete,n.onError,o,u])}const ry=/^(run|approve|accept|yes|allow|always)/,ay=/^(run|approve|accept|yes|allow|always|proceed|save)/,oy=/^(reject|deny|delete|remove|abort|cancel|no)/;function Ei(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function iy(e){const t=Ei(e).toLowerCase();return ry.test(t)?"primary":oy.test(t)?"danger":"default"}function ly(e){return ay.test(Ei(e).toLowerCase())?"approve":"reject"}function cy(e){return e.map((t,n)=>({label:Ei(t),variant:iy(t),action:ly(t),button:t,buttonIndex:n}))}function dy(e,t,n){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:n}function uy(e,t,n,r){return[{label:"Approve",variant:"primary",onClick:()=>{n(e,t,"approve").catch(a=>r==null?void 0:r("approve",a))}},{label:"Decline",variant:"danger",onClick:()=>{n(e,t,"reject").catch(a=>r==null?void 0:r("reject",a))}}]}class py{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(n=>n!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(n=>n!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const n of this.toastCallbacks)n(t)}showToast(t,n="info",r){const a=(r==null?void 0:r.id)||Date.now();this.emitToast({id:a,message:t,type:n,timestamp:a,duration:5e3,...r})}isDuplicate(t){const n=Date.now(),r=this.dedupMap.get(t)||0;if(n-r<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,n),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,o]of this.dedupMap)n-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 n=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(n){const a=n.daemonId;if(a){const o=this.ides.find(i=>i.id===a&&i.type==="adhdev-daemon");if(o)return o}}const r=this.ides.filter(a=>a.type==="adhdev-daemon");return r.length===1?r[0]:null}findOwningSession(t){for(const n of this.ides)if(n.id===t||n.sessionId===t||(Array.isArray(n.childSessions)?n.childSessions:[]).some(a=>(a==null?void 0:a.id)===t))return n;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const n=this.findOwningSession(t.targetSessionId);return(n==null?void 0:n.id)||(n==null?void 0:n.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}isConversationEventMuted(t){const n=t.targetSessionId;if(!n)return!1;for(const r of this.ides){if(r.id===n||r.sessionId===n)return!!r.muted;const o=(Array.isArray(r.childSessions)?r.childSessions:[]).find(i=>(i==null?void 0:i.id)===n);if(o)return!!o.muted}return!1}handleRawEvent(t,n){var f;const r=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),o=r||t.daemonId||"",i=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),u=`${o}:${t.event}:${i}`;if(this.isDuplicate(u))return;for(const y of this.statusEventCallbacks)y(t);const c=this.isConversationEventMuted(t),p=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,d=(p==null?void 0:p.type)||"";let m=$t(d);const h=this.resolveOwningDaemon(t);if(h){const y=ts(h,{fallbackId:h.id});y&&(m=!d||d==="adhdev-daemon"?y:`${y}/${m}`)}let g="",v="info";if(t.event==="agent:generating_completed"){if(g=t.duration?`✅ ${wt.t("event.taskCompletedWithDuration",{label:m,duration:t.duration})}`:`✅ ${wt.t("event.taskCompleted",{label:m})}`,v="success",!c)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=`⚡ ${wt.t("event.approvalNeeded",{label:m})}`,v="warning",c)g="";else if((f=t.modalButtons)!=null&&f.length&&this.resolveActionFn){const y=this.resolveActionRouteTarget(t);if(!y)return;const j=this.resolveActionFn,x=cy(t.modalButtons).map(k=>({label:k.label,variant:k.variant,onClick:()=>{j(y,"resolve_action",{action:k.action,button:k.button,buttonIndex:k.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),w=dy(m,t.modalMessage,g),N=Date.now();this.emitToast({id:N,message:w,type:v,timestamp:N,targetKey:r||y,actions:x,duration:15e3}),g=""}}else if(t.event==="monitor:no_progress"||t.event==="monitor:long_generating"){const y=t.elapsedSec?Math.round(t.elapsedSec/60):0;g=y?`⚠️ ${wt.t("event.noProgressWithDuration",{label:m,minutes:y})}`:`⚠️ ${wt.t("event.noProgress",{label:m})}`,v="warning",!c&&Zn("browser")&&!document.hasFocus()&&Zo(`⚠️ ${wt.t("event.noProgressTitle",{label:m})}`,wt.t("event.noProgressBody",{duration:y?`${y}m`:""}),`no-progress-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const y=t.requesterName||wt.t("event.someoneRequester"),j=t.requestId,x=t.orgId;if(g=`👁️ ${wt.t("event.viewRequest",{requester:y})}`,v="warning",j&&x&&this.viewRequestRespondFn){const w=Date.now(),N=uy(x,j,this.viewRequestRespondFn,(k,b)=>console.error(`[EventManager] ${k} view request failed:`,b));this.emitToast({id:w,message:g,type:v,timestamp:w,actions:N,duration:3e4}),g=""}Zn("browser")&&!document.hasFocus()&&Zo(`👁️ ${wt.t("event.viewRequestTitle")}`,wt.t("event.viewRequest",{requester:y}),`view-request-${j}`)}else if(t.event==="team:view_request_approved")g=`✅ ${wt.t("event.viewRequestApproved")}`,v="success";else if(t.event==="team:view_request_rejected"){const y=t.targetName||wt.t("event.someoneTarget");g=`❌ ${wt.t("event.viewRequestDeclined",{target:y})}`,v="warning"}}if(g&&!c){const y=Date.now();this.emitToast({id:y,message:g,type:v,timestamp:y,targetKey:r||t.daemonId,duration:5e3})}}}const ht=new py,ql=new Map;function na(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function mn(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Ia(e){return na(e)?na(e.result)?e.result:e:null}function hy(e){const t=Ia(e);return!t||!na(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function jr(e){const t=Ia(e);return!t||!na(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function _n(e){const t=Ia(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function Sr(e){const t=Ia(e);return!!t&&t.success===!1}function my(e){var t,n;for(const r of e||[]){if(r.type==="toast"&&((t=r.toast)!=null&&t.message)){const a=r.toast.level==="warning"?"warning":r.toast.level==="success"?"success":"info";ht.showToast(r.toast.message,a);continue}if(r.type==="notification"&&((n=r.notification)!=null&&n.body)){const a=r.notification.level==="warning"?"warning":r.notification.level==="success"?"success":"info";ht.showToast(r.notification.body,a)}}}function fy(e,t){return e&&mn(e.currentValue)?e.currentValue:t}function xy(e,t){const n=Object.keys(e).filter(a=>t[a]!==void 0);if(n.length===0)return e;const r={...e};for(const a of n)delete r[a];return r}function by(e,t){return mn(t)?mn(e)?typeof e=="string"&&e.trim()==="":!0:!1}function gy(e,t){var o,i;if((t.now??Date.now())<t.localOverrideUntil){const u=t.localValues[e];if(mn(u))return u}const r=(o=t.controlValues)==null?void 0:o[e];if(mn(r))return r;const a=(i=t.defaultValues)==null?void 0:i[e];return mn(a)?a:void 0}function Kr(e,t){return e.options||t[e.id]||[]}const yy={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 vy(e,t,n){var r;return((r=yy[t])==null?void 0:r.has(n.id))===!0}function wy(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 ky(e,t){const n=e.visibleWhenState;if(!n||n.length===0)return!0;const r=wy(t);return r?r.some(a=>n.includes(a)):!0}function $i(e,t){return(e||[]).filter(n=>n.placement==="bar"&&n.hidden!==!0&&!vy(t.hostIdeType,t.providerType,n)&&ky(n,t.currentStatus)).sort((n,r)=>(n.order??50)-(r.order??50))}function Qa(e,t){return{value:t}}function jy(e,t,n){var a;return n?((a=Kr(e,t).find(o=>o.value===n))==null?void 0:a.label)||n:""}const Sy={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Ny({routeId:e,sessionId:t,hostIdeType:n,providerType:r,displayLabel:a,controls:o,controlValues:i,currentStatus:u,coordinatorHint:c}){const{sendCommand:p}=yt(),d=`${e}:${t||r}`,m=Sy[r]||"#94a3b8",[h,g]=l.useState({}),v=l.useRef({}),f=l.useRef(i);v.current=h,f.current=i;const y=l.useRef(0),j={};for(const E of o||[])E.defaultValue!==void 0&&(j[E.id]=E.defaultValue);const x={...j,...i||{},...Date.now()<y.current?h:{}};l.useEffect(()=>{i&&Date.now()>y.current&&g(E=>xy(E,i))},[i]);const[w,N]=l.useState(ql.get(d)||{}),[k,b]=l.useState(null),[C,S]=l.useState(null),M=l.useCallback(async(E,D={})=>{const $={...D,...t&&{targetSessionId:t},...c??{}};return await p(e,E,$)},[e,t,p,c]),A=l.useCallback(async(E,D={})=>{const $=t?{targetSessionId:t}:{agentType:r,...n?{ideType:n}:{}};return await M("invoke_provider_script",{...$,scriptName:E,...D})},[M,r,n,t]),T=l.useCallback((E,D,$)=>{const I=fy($,D);g(G=>({...G,[E.id]:I})),my($==null?void 0:$.effects)},[]),L=l.useCallback((E,D)=>{g($=>{const I={...$};return D===void 0?delete I[E.id]:I[E.id]=D,I}),y.current=0},[]);if(!o||o.length===0)return null;const P=$i(o,{hostIdeType:n,providerType:r,currentStatus:u});if(P.length===0)return null;const B=async E=>{if(k===E.id){b(null);return}if(Kr(E,w).length>0){b(E.id);return}if(E.dynamic&&E.listScript){S(E.id);try{const $=await A(E.listScript,{}),I=hy($);if(!I){const Z=_n($);Z&&ht.showToast(Z,"warning");return}const G=I.options;N(Z=>{const q={...Z,[E.id]:G};return ql.set(d,q),q});const Y=gy(E.id,{localOverrideUntil:y.current,localValues:v.current,controlValues:f.current,defaultValues:j});if(by(Y,I.currentValue)){const Z=I.currentValue;g(q=>({...q,[E.id]:Z}))}b(E.id)}catch($){const I=$ instanceof Error?$.message:`Could not load ${E.label}`;ht.showToast(I,"warning")}finally{S(null)}}},z=async(E,D)=>{b(null);const $=(i==null?void 0:i[E.id])??j[E.id];g(I=>({...I,[E.id]:D})),y.current=Date.now()+5e3;try{if(!E.setScript)return;const I=await A(E.setScript,Qa(E,D)),G=jr(I);if(G&&!G.ok||Sr(I))throw new Error((G==null?void 0:G.error)||_n(I)||`Could not update ${E.label}`);T(E,D,G)}catch(I){L(E,$);const G=I instanceof Error?I.message:`Could not update ${E.label}`;ht.showToast(G,"warning")}},R=async E=>{const D=Kr(E,w).map(q=>q.value);if(D.length===0)return;const $=String(x[E.id]||""),G=(D.indexOf($)+1)%D.length,Y=D[G];if(typeof Y!="string")return;const Z=(i==null?void 0:i[E.id])??j[E.id];g(q=>({...q,[E.id]:Y})),y.current=Date.now()+5e3;try{if(!E.setScript)return;const q=await A(E.setScript,Qa(E,Y)),ne=jr(q);if(ne&&!ne.ok||Sr(q))throw new Error((ne==null?void 0:ne.error)||_n(q)||`Could not update ${E.label}`);T(E,Y,ne)}catch(q){L(E,Z);const ne=q instanceof Error?q.message:`Could not update ${E.label}`;ht.showToast(ne,"warning")}},_=async E=>{const $=!x[E.id],I=(i==null?void 0:i[E.id])??j[E.id];g(G=>({...G,[E.id]:$})),y.current=Date.now()+5e3;try{if(!E.setScript)return;const G=await A(E.setScript,Qa(E,$)),Y=jr(G);if(Y&&!Y.ok||Sr(G))throw new Error((Y==null?void 0:Y.error)||_n(G)||`Could not update ${E.label}`);T(E,$,Y)}catch(G){L(E,I);const Y=G instanceof Error?G.message:`Could not update ${E.label}`;ht.showToast(Y,"warning")}},K=async E=>{if(!E.invokeScript)return;if(E.confirmMessage){const $=[E.confirmTitle,E.confirmMessage,E.confirmLabel].filter(G=>typeof G=="string"&&G.trim().length>0);if(!window.confirm($.join(`
32
-
33
- `)))return}const D=(i==null?void 0:i[E.id])??j[E.id];try{const $=await A(E.invokeScript),I=jr($);if(I&&!I.ok||Sr($))throw new Error((I==null?void 0:I.error)||_n($)||`Could not run ${E.label}`);I&&T(E,D??!0,I)}catch($){L(E,D);const I=$ instanceof Error?$.message:`Could not run ${E.label}`;ht.showToast(I,"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(E=>{const D=String(x[E.id]||""),$=jy(E,w,D),I=k===E.id,G=C===E.id,Y=Kr(E,w),Z="inline-flex h-7 max-w-full items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium transition-colors whitespace-nowrap";switch(E.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${Z} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:I?`${m}55`:"var(--border-default)",background:I?`${m}10`:"var(--surface-tertiary)",color:D?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void B(E),title:E.label,children:[E.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:E.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:G?"Loading…":$||E.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),I&&Y.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:E.label}),Y.map(q=>s.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-[12px] transition-colors",style:{background:q.value===D?`${m}14`:"transparent",color:q.value===D?"var(--text-primary)":"var(--text-secondary)",borderLeft:q.value===D?`2px solid ${m}`:"2px solid transparent"},title:q.description||q.label,onMouseEnter:ne=>{ne.currentTarget.style.background=`${m}10`},onMouseLeave:ne=>{ne.currentTarget.style.background=q.value===D?`${m}14`:"transparent"},onClick:()=>void z(E,q.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:q.label}),q.value===D&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},q.value))]})]})]},E.id);case"cycle":return s.jsxs("button",{type:"button",className:`${Z} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:D?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void R(E),title:`Click to cycle: ${Y.map(q=>q.label).join(" → ")}`,children:[E.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:E.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:$||E.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},E.id);case"toggle":return s.jsxs("button",{type:"button",className:`${Z} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:D?`${m}44`:"var(--border-default)",background:D?`${m}14`:"var(--surface-tertiary)",color:D?m:"var(--text-muted)"},onClick:()=>void _(E),"aria-pressed":!!D,children:[E.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:E.icon}),E.label]},E.id);case"action":return s.jsxs("button",{type:"button",className:`${Z} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void K(E),children:[E.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:E.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:E.resultDisplay==="inline"&&D?`${E.label}: ${D}`:E.label})]},E.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:D?"var(--text-primary)":"var(--text-muted)"},children:[E.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:E.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:D?`${E.label}: ${D}`:E.label})]},E.id);default:return null}})]})})}function Cy({isActive:e=!0,isCliTerminal:t=!1,routeId:n,sessionId:r,hostIdeType:a,providerType:o,displayLabel:i,controls:u,controlValues:c,currentStatus:p,coordinatorHint:d}){const{isVisible:m}=Li(),h=$i(u,{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(Ny,{routeId:n,sessionId:r,hostIdeType:a,providerType:o,displayLabel:i,controls:h,controlValues:c,currentStatus:p,coordinatorHint:d})})}const En=5,Nu=10*1024*1024;function My({hasDraft:e,isBusy:t=!1}){return!e||t}function Ay(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}async function Iy(e){if(e.size>Nu)return null;const t=await Ay(e),n=t.indexOf(",");if(n<0)return null;const r=t.slice(n+1);return{mimeType:e.type||"image/png",data:r,name:e.name,previewUrl:t}}function Ty(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const Cu=l.memo(function({contextKey:t,panelLabel:n,isSending:r,isBusy:a=!1,statusMessage:o=null,inlineStatusMessage:i=null,onSend:u,onForceSend:c,canForceSend:p=!1,isActive:d=!0,showControlsToggle:m=!1,animateVisibility:h=!0,onControlsToggle:g,messageInput:v}){const{t:f}=Xe("common"),y=l.useRef(null),j=l.useRef(null),[x,w]=l.useState(""),[N,k]=l.useState([]),[b,C]=l.useState(null),[S,M]=l.useState(!1),A=l.useRef(!1),{isVisible:T,toggleVisibility:L}=Li(),P=Ty(v),B=!!x.trim()||N.length>0;l.useEffect(()=>{w(""),k([]),C(null)},[t]),l.useEffect(()=>{var I;d&&((I=y.current)==null||I.focus({preventScroll:!0}))},[t,d]),l.useEffect(()=>{const I=y.current;I&&(I.style.height="auto",I.style.height=`${Math.min(I.scrollHeight,160)}px`)},[x]);const z=l.useCallback(async I=>{C(null);const G=Array.from(I).filter(ae=>ae.type.startsWith("image/"));if(G.length===0)return;const Y=En-N.length;if(Y<=0){C(`Max ${En} images`);return}const Z=G.slice(0,Y);if(Z.filter(ae=>ae.size>Nu).length>0){C("Image too large (max 10 MB)");return}const ue=(await Promise.all(Z.map(Iy))).filter(ae=>ae!==null);k(ae=>[...ae,...ue])},[N.length]),R=l.useCallback(I=>{k(G=>G.filter((Y,Z)=>Z!==I))},[]),_=l.useCallback(async()=>{const I=x.trim();if(!I&&N.length===0||a||A.current)return;A.current=!0;const G=N.length>0?[...N]:void 0;try{await u(I,G)!==!1&&(w(""),k([]),C(null))}finally{A.current=!1}},[x,N,a,u]),K=l.useCallback(async()=>{if(!p||!c)return;const I=x.trim();if(!I&&N.length===0||A.current)return;A.current=!0;const G=N.length>0?[...N]:void 0;try{await c(I,G)!==!1&&(w(""),k([]),C(null))}finally{A.current=!1}},[N,p,x,c]),E=l.useCallback(I=>{P&&(I.preventDefault(),M(!0))},[P]),D=l.useCallback(()=>M(!1),[]),$=l.useCallback(I=>{P&&(I.preventDefault(),M(!1),I.dataTransfer.files.length>0&&z(I.dataTransfer.files))},[P,z]);return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",h?"transition-all duration-200 ease-out":"",S?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:d?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:d?200:0,opacity:d?1:0,transform:d?"translateY(0)":"translateY(10px)",padding:d?"10px 12px":"0 12px",pointerEvents:d?"auto":"none"},"aria-hidden":!d,onDragOver:E,onDragLeave:D,onDrop:$,children:[N.length>0&&s.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:N.map((I,G)=>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:I.previewUrl,alt:I.name,className:"w-full h-full object-cover"}),s.jsx("button",{type:"button",onClick:()=>R(G),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 ${I.name}`,children:"✕"})]},G))}),s.jsxs("div",{className:"flex gap-2 items-center",title:d?`Send message to ${n}`:void 0,children:[m&&s.jsx("button",{type:"button",onClick:()=>{L(),g==null||g()},"aria-label":T?"Hide controls":"Show controls","aria-pressed":T,title:T?"Hide controls":"Show controls",className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:s.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[s.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),P&&s.jsxs(s.Fragment,{children:[s.jsx("input",{ref:j,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:I=>{I.target.files&&z(I.target.files),I.target.value=""}}),s.jsx("button",{type:"button",onClick:()=>{var I;return(I=j.current)==null?void 0:I.click()},disabled:N.length>=En,title:N.length>=En?`Max ${En} images`:f("chatInput.attachImage"),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":f("chatInput.attachImage"),children:s.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"})})})]}),s.jsx("div",{className:"flex-1 relative",children:s.jsx("textarea",{ref:y,rows:1,placeholder:o||(P&&N.length>0?"Add a message (optional)...":f("chatInput.placeholder",{panel:n})),value:x,onChange:I=>w(I.target.value),onPaste:I=>{if(P&&I.clipboardData.files.length>0&&Array.from(I.clipboardData.files).some(se=>se.type.startsWith("image/"))){I.preventDefault(),z(I.clipboardData.files);return}const G=I.clipboardData.getData("text/plain"),Y=Vm(G);if(Y===G)return;I.preventDefault();const Z=y.current,q=(Z==null?void 0:Z.selectionStart)??x.length,ne=(Z==null?void 0:Z.selectionEnd)??x.length,ue=x.slice(0,q)+Y+x.slice(ne);w(ue);const ae=q+Y.length;requestAnimationFrame(()=>{Z==null||Z.setSelectionRange(ae,ae)})},onKeyDown:I=>{I.key==="Enter"&&(I.nativeEvent.isComposing||I.shiftKey||(I.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:My({hasDraft:B,isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${B&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:B&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,"aria-label":f("chatInput.sendMessage"),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:B?"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:()=>{K()},disabled:!B,className:`h-10 px-3 rounded-full text-[11px] font-medium border border-border-subtle shrink-0 transition-colors ${B?"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"})]}),(b||P&&S)&&s.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${b?"text-red-400":"text-[var(--accent-primary)]"}`,children:b||f("chatInput.dropImage")}),i&&!b&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),Py=l.createContext(null);function Fi(){return l.useContext(Py)}function Dy(e){return Cg(e,{lastCheckedAt:Date.now()})}function Ly(e){const t=Array.isArray(e==null?void 0:e.submodules)?e.submodules:[];let n=!1,r=!1;for(const a of t)a!=null&&a.outOfSync&&(r=!0),a!=null&&a.dirty&&(n=!0);return{dirty:n,outOfSync:r}}function Ry(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 ra(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=Ly(e);return t.outOfSync?"degraded":t.dirty||Ry(e)?"dirty":"online"}function _y(e,t){const n=t?ra(t):void 0;return!e||e==="unknown"?n:e}function Ey(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 n=ft(e.activeSession??e.active_session),r={...n,sessionId:Pe(n.sessionId,n.id,n.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id)},a=Yo(r);return a?[a]:void 0}function $y(e){const t=ft(e.connection);return Object.keys(t).length>0?t:void 0}function Fy(e){const t=e==null?void 0:e.source,n=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:n&&n!=="unknown"?n:"direct",reported:!0,reason:"Live peer git snapshot reported by the selected coordinator."}}function Bi(e){var n;const t=e.git;return!!(t&&(t.isGitRepo===!0||t.isGitRepo===!1||t.branch||t.upstream||t.headCommit||typeof t.lastCheckedAt=="number"||(((n=t.submodules)==null?void 0:n.length)??0)>0))}function Yl(e){var r,a,o,i,u,c;let t=0;const n=e.git;return Bi(e)&&(t+=80,(n==null?void 0:n.isGitRepo)===!0&&(t+=20),(n==null?void 0:n.isGitRepo)===!1&&(t+=5),n!=null&&n.branch&&(t+=20),n!=null&&n.upstream&&(t+=12),n!=null&&n.headCommit&&(t+=12),t+=Ri(n==null?void 0:n.upstreamStatus),typeof(n==null?void 0:n.lastCheckedAt)=="number"&&(t+=6),t+=(((r=n==null?void 0:n.submodules)==null?void 0:r.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),((u=e.connection)==null?void 0:u.transport)==="direct"&&(t+=4),((c=e.connection)==null?void 0:c.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 By(e,t){var v,f,y,j;const n=Yl(e),a=Yl(t)>n?t:e,o=a===t?e:t,i=a.git??o.git,u=(((v=a.providers)==null?void 0:v.length)??0)>0?a.providers:o.providers,c=(((f=a.activeSessions)==null?void 0:f.length)??0)>0?a.activeSessions:o.activeSessions,p=(((y=a.activeSessionDetails)==null?void 0:y.length)??0)>0?a.activeSessionDetails:o.activeSessionDetails,d=(((j=a.providerPriority)==null?void 0:j.length)??0)>0?a.providerPriority:o.providerPriority,m=a.connection??o.connection,h={...o,...a,machineLabel:a.machineLabel||o.machineLabel,workspace:a.workspace||o.workspace,...a.repoRoot||o.repoRoot?{repoRoot:a.repoRoot||o.repoRoot}:{},...a.daemonId||o.daemonId?{daemonId:a.daemonId||o.daemonId}:{},...a.machineId||o.machineId?{machineId:a.machineId||o.machineId}:{},...a.machineStatus||o.machineStatus?{machineStatus:a.machineStatus||o.machineStatus}:{},health:i&&(!a.health||a.health==="unknown")?ra(i):a.health,providers:u??[],activeSessions:c??[],...p&&p.length>0?{activeSessionDetails:p}:{},...d&&d.length>0?{providerPriority:d}:{},...m?{connection:m}:{},...i?{git:i}:{}},g=ft(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 Mu(e){const t=ft(e),n=Pe(t.nodeId,t.id);if(!n)return null;const r=ft(t.cachedStatus),a=Dy(t),o=a?void 0:Wr(ft(t.git),t)??Wr(t,t),i=a??o,u=i?void 0:Wr(ft(r.git),t),c=i??u,p=Pe(t.machineStatus,t.machine_status,r.machineStatus,r.machine_status),d=Pe(t.health),m=a?ra(c):_y(d,i)||(c?ra(c):void 0)||Pe(r.health)||p||Pe(t.status)||"unknown",g=(a?void 0:Pe(t.error))??(i?void 0:Pe(r.error)),v=Ey(t),f=Ya(t.activeSessions),y=(v==null?void 0:v.map(S=>S.sessionId))??[],j=Ya(t.providerPriority),x=Et(t.gitProbePending,t.git_probe_pending),w=i?void 0:x,N=$y(t),k=ft(t.branchConvergence??t.branch_convergence),b=N==null?void 0:N.state,C=a&&(!(N!=null&&N.reported)||b==="unknown")?Fy(N):N;return{nodeId:n,machineLabel:Pe(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,n)||n,workspace:Pe(t.workspace,c==null?void 0:c.workspace)||"",...Pe(t.repoRoot,t.repo_root,c==null?void 0:c.repoRoot)?{repoRoot:Pe(t.repoRoot,t.repo_root,c==null?void 0:c.repoRoot)}:{},...Pe(t.daemonId,t.daemon_id)?{daemonId:Pe(t.daemonId,t.daemon_id)}:{},...Pe(t.machineId,t.machine_id)?{machineId:Pe(t.machineId,t.machine_id)}:{},...p?{machineStatus:p}:{},...Et(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:Et(t.isLocalWorktree,t.is_local_worktree)}:{},...Pe(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:Pe(t.worktreeBranch,t.worktree_branch)}:{},...Pe(t.clonedFromNodeId,t.cloned_from_node_id)?{clonedFromNodeId:Pe(t.clonedFromNodeId,t.cloned_from_node_id)}:{},health:m,...c?{git:c}:{},...w!==void 0?{gitProbePending:w}:{},providers:Ya(t.providers),activeSessions:f.length>0?f:y,...v&&v.length>0?{activeSessionDetails:v}:{},...j.length>0?{providerPriority:j}:{},...Et(t.launchReady)!==void 0?{launchReady:Et(t.launchReady)}:a?{launchReady:!0}:{},...Pe(t.lastSeenAt,t.last_seen_at,r.lastSeenAt,r.last_seen_at)?{lastSeenAt:Pe(t.lastSeenAt,t.last_seen_at,r.lastSeenAt,r.last_seen_at)}:{},...Pe(t.updatedAt,t.updated_at,r.updatedAt,r.updated_at)?{updatedAt:Pe(t.updatedAt,t.updated_at,r.updatedAt,r.updated_at)}:{},...C?{connection:C}:{},...Object.keys(k).length>0?{branchConvergence:k}:{},...t.scheduling&&typeof t.scheduling=="object"?{scheduling:t.scheduling}:{},...Et(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}:{},...Pe(t.daemonBuildVersion,t.daemon_build_version)?{daemonBuildVersion:Pe(t.daemonBuildVersion,t.daemon_build_version)}:{},...g?{error:g}:{}}}function Jl(e){const t=new Map;for(const n of e){const r=t.get(n.sessionId);t.set(n.sessionId,r?{...r,...n}:n)}return[...t.values()]}function Au(e,t){const n=Array.isArray(e.coordinatorSessions)?e.coordinatorSessions:Array.isArray(e.coordinator_sessions)?e.coordinator_sessions:[],r=n.map(Yo).filter(a=>a!==null);return r.length===0?t:t.map(a=>{const o=r.filter(u=>{const c=ft(n.find(h=>{const g=ft(h);return Pe(g.sessionId,g.session_id,g.id)===u.sessionId})),p=Pe(c.nodeId,c.node_id),d=Pe(c.daemonId,c.daemon_id),m=Pe(c.workspace);return p&&p===a.nodeId?!0:Os(d,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(u=>({sessionId:u}))]).map(u=>u.sessionId)}})}function Hy(e){const t=ft(e);return Array.isArray(t.sessions)||Array.isArray(t.active_session_details)||Pe(t.daemon_id,t.machine_id,t.repo_root,t.worktree_branch,t.cloned_from_node_id)!==void 0||Et(t.is_local_worktree)!==void 0}function Iu(e){const t=new Map,n=[];for(const r of e){const a=Hy(r)?Mu(r)??r:r;if(!(a!=null&&a.nodeId))continue;const o=t.get(a.nodeId);if(!o){t.set(a.nodeId,a),n.push(a);continue}const i=By(o,a);t.set(a.nodeId,i);const u=n.findIndex(c=>c.nodeId===a.nodeId);u>=0&&(n[u]=i)}return n}function Tu(e){const t=e??{},n=Iu(t.nodes??[]);return{...t,nodes:Au(t,n)}}function Oy(e){var n;const t=e==null?void 0:e.git;return{nodeId:(e==null?void 0:e.nodeId)??null,chosenSource:t?"live_git":e!=null&&e.gitProbePending?"pending_git":"no_git",hasLiveGit:Bi(e??{git:void 0}),branch:(t==null?void 0:t.branch)??null,upstream:(t==null?void 0:t.upstream)??null,headCommit:(t==null?void 0:t.headCommit)??null,submoduleCount:((n=t==null?void 0:t.submodules)==null?void 0:n.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 Wy(e){const t=Pe(e.meshId,e.mesh_id,e.id),n=e.nodes,r=Array.isArray(n)?n.map(c=>Mu(c)).filter(c=>c!==null):null;if(!t||!r)return null;const a=Au(e,Iu(r)),o=Pe(e.meshName,e.mesh_name,e.name),i=Pe(e.repoIdentity,e.repo_identity),u=Pe(e.refreshedAt,e.refreshed_at,e.updatedAt,e.updated_at);return!o||!i||!u?null:{...e,meshId:t,meshName:o,repoIdentity:i,refreshedAt:u,nodes:a}}function Uy(e){var o;let t=0;const n=ft(e.sourceOfTruth),r=ft(n.directPeerTruth);Pe(n.currentStatus)==="live_git_and_session_probes"&&(t+=100),n.coordinatorOwnsLiveTruth===!0&&(t+=25),r.satisfied===!0&&(t+=15);for(const i of e.nodes){const u=i.git;if(!u){i.gitProbePending&&(t-=8);continue}t+=10,u.isGitRepo===!0&&(t+=5),u.isGitRepo===!1&&(t+=1),u.branch&&(t+=4),u.upstream&&(t+=3),u.headCommit&&(t+=3),t+=Ri(u.upstreamStatus),typeof u.ahead=="number"&&(t+=1),typeof u.behind=="number"&&(t+=1),typeof u.lastCheckedAt=="number"&&(t+=2),t+=(((o=u.submodules)==null?void 0:o.length)??0)*2}return t}function Ky(e){const t=e.refreshedAt;if(typeof t!="string"||t.length===0)return 0;const n=Date.parse(t);return Number.isFinite(n)?n:0}const Gy=20;function Xl(e){let t=null;for(const n of e){const r=Wy(ft(n));if(!r)continue;const a=Uy(r),o=Ky(r);if(!t){t={status:r,score:a,refreshedAt:o};continue}(Math.abs(a-t.score)<=Gy?o>t.refreshedAt||o===t.refreshedAt&&a>t.score:a>t.score)&&(t={status:r,score:a,refreshedAt:o})}return(t==null?void 0:t.status)??null}function Hi(e){const n=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,r=Xl([n==null?void 0:n.status,n]);return r||Xl([e==null?void 0:e.status,e])}function zy(e){var r;if(!e)return null;const t=(r=e.coordinator)==null?void 0:r.meshId;if(typeof t=="string"&&t.trim())return t.trim();const n=e.settings||{};for(const a of["meshNodeFor","meshCoordinatorFor"]){const o=n[a];if(typeof o=="string"&&o.trim())return o.trim()}return null}function Vy(e){const t=(e==null?void 0:e.settings)||{};for(const n of["meshNodeId","nodeId"]){const r=t[n];if(typeof r=="string"&&r.trim())return r.trim()}return null}function qy(e,t){var a;if(!t)return null;const n=Hi(e),r=(a=n==null?void 0:n.nodes)==null?void 0:a.find(o=>Ig(o,t));return r?{nodeId:r.nodeId,workspace:r.workspace,repoRoot:r.repoRoot,daemonId:r.daemonId,role:r.role,machineStatus:r.machineStatus,health:r.health,isLocalWorktree:r.isLocalWorktree,worktreeBranch:r.worktreeBranch,launchReady:r.launchReady,providers:r.providers,providerPriority:r.providerPriority,git:r.git?{branch:r.git.branch,headCommit:r.git.headCommit,ahead:r.git.ahead,behind:r.git.behind,dirty:r.git.dirty,upstream:r.git.upstream}:void 0,connection:r.connection?{transport:r.connection.transport,state:r.connection.state,rttMs:r.connection.rttMs}:void 0}:null}const Yy={sm:"max-w-md",md:"max-w-lg",lg:"max-w-3xl"};function Pu({open:e,onClose:t,size:n="md",title:r,footer:a,children:o,showClose:i=!0,closeOnBackdrop:u=!0,closeOnEsc:c=!0,ariaLabel:p,className:d,contentClassName:m}){l.useEffect(()=>{if(!e||!c)return;const f=y=>{y.key==="Escape"&&t()};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[e,c,t]);const h=l.useCallback(f=>{u&&f.target===f.currentTarget&&t()},[u,t]);if(!e)return null;const g=r!=null||i,v=s.jsx("div",{className:Ht("fixed inset-0 flex items-center justify-center bg-black/60 p-4",d),style:{zIndex:"var(--z-modal-backdrop)"},onClick:h,children:s.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":r==null?p:void 0,className:Ht("relative flex max-h-[calc(100dvh-2rem)] w-full flex-col overflow-hidden","rounded-xl border border-border-default bg-surface-primary shadow-2xl",Yy[n],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 r=="string"||typeof r=="number"?s.jsx("h2",{className:"truncate text-lg font-bold text-text-primary",children:r}):r}),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(Mt,{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"?v:fn.createPortal(v,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 n=Math.floor(t/1e3);if(n<60)return`${n}s ago`;const r=Math.floor(n/60);if(r<60)return`${r}m ago`;const a=Math.floor(r/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function Jy({sessionId:e,daemonId:t,conv:n,onClose:r}){var k,b;const{sendCommand:a}=yt(),o=Fi(),[i,u]=l.useState(!0),[c,p]=l.useState(null),[d,m]=l.useState(null),[h,g]=l.useState(null),[v,f]=l.useState(null),y=l.useMemo(()=>zy(n),[n]),j=l.useMemo(()=>Vy(n),[n]),x=l.useCallback(async()=>{u(!0),m(null);try{const C=await a(t,"get_session_info",{targetSessionId:e}),S=C&&typeof C=="object"?C:{},M=S.result&&typeof S.result=="object"?S.result:S;M!=null&&M.success?p(M):(m((M==null?void 0:M.error)||"Failed to load session info"),p(null))}catch(C){m((C==null?void 0:C.message)||String(C)),p(null)}finally{u(!1)}},[a,t,e]);l.useEffect(()=>{x()},[x]);const w=l.useCallback(async()=>{if(g(null),f(null),!(!y||!j||!(o!=null&&o.loadMeshStatus)))try{const C=await o.loadMeshStatus(t,y,{refresh:!1}),S=qy(C,j);if(!S){f("This session is stamped to a mesh node that the coordinator no longer reports.");return}g(S)}catch(C){f((C==null?void 0:C.message)||"Failed to load mesh node info")}},[o,t,y,j]);l.useEffect(()=>{w()},[w]);const N=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:r,className:"px-3 py-1 text-sm rounded bg-accent text-white hover:opacity-90",children:"Close"})]});return s.jsx(Pu,{open:!0,onClose:r,title:"Session info",size:"lg",footer:N,children:s.jsxs("div",{className:"text-sm space-y-4",children:[i&&s.jsx("div",{className:"text-text-secondary",children:"Loading…"}),d&&s.jsx("div",{className:"text-red-500",children:d}),(c==null?void 0:c.session)&&s.jsxs(an,{title:"Session",children:[s.jsx(nt,{k:"Session ID",v:s.jsx(Tt,{children:c.session.sessionId})}),s.jsx(nt,{k:"Provider",v:`${c.session.providerName||c.session.providerType} (${c.session.providerType})`}),c.session.transport&&s.jsx(nt,{k:"Transport",v:c.session.transport}),c.session.workspace&&s.jsx(nt,{k:"Workspace",v:s.jsx(Tt,{children:c.session.workspace})}),s.jsx(nt,{k:"Spawned at",v:s.jsxs(s.Fragment,{children:[Ql(c.session.spawnedAtMs),c.session.spawnedAtMs?s.jsx("span",{className:"text-text-secondary ml-2",children:Zl(c.session.spawnedAtMs)}):null]})}),c.session.providerSessionId&&s.jsx(nt,{k:"Provider session ID",v:s.jsx(Tt,{children:c.session.providerSessionId})}),!c.session.workspace&&(n==null?void 0:n.workspacePath)&&s.jsx(nt,{k:"Workspace",v:s.jsx(Tt,{children:n.workspacePath})}),(n==null?void 0:n.machineName)&&s.jsx(nt,{k:"Machine",v:n.machineName}),(n==null?void 0:n.connectionState)&&s.jsx(nt,{k:"Connection",v:n.connectionState}),(n==null?void 0:n.git)&&s.jsx(nt,{k:"Workspace git",v:s.jsxs("span",{children:[n.git.branch||"(detached)",n.git.ahead?` ↑${n.git.ahead}`:"",n.git.behind?` ↓${n.git.behind}`:"",n.git.dirty?" · dirty":" · clean"]})})]}),((k=c==null?void 0:c.session)==null?void 0:k.launch)&&s.jsxs(an,{title:"Launch",children:[c.session.launch.command&&s.jsx(nt,{k:"Command",v:s.jsx(Tt,{children:c.session.launch.command})}),c.session.launch.cwd&&s.jsx(nt,{k:"Working directory",v:s.jsx(Tt,{children:c.session.launch.cwd})}),Array.isArray(c.session.launch.args)&&c.session.launch.args.length>0&&s.jsx(nt,{k:"Args",v:s.jsx(Tt,{children:c.session.launch.args.join(" ")})}),Array.isArray(c.session.launch.extraArgs)&&c.session.launch.extraArgs.length>0&&s.jsx(nt,{k:"Extra args",v:s.jsx(Tt,{children:c.session.launch.extraArgs.join(" ")})}),Array.isArray(c.session.launch.extraEnvKeys)&&c.session.launch.extraEnvKeys.length>0&&s.jsx(nt,{k:"Extra env",v:s.jsx(Tt,{children:c.session.launch.extraEnvKeys.join(", ")})})]}),h&&s.jsxs(an,{title:"Mesh node",children:[h.nodeId&&s.jsx(nt,{k:"Node ID",v:s.jsx(Tt,{children:h.nodeId})}),h.workspace&&s.jsx(nt,{k:"Workspace",v:s.jsx(Tt,{children:h.workspace})}),h.repoRoot&&h.repoRoot!==h.workspace&&s.jsx(nt,{k:"Repo root",v:s.jsx(Tt,{children:h.repoRoot})}),h.daemonId&&s.jsx(nt,{k:"Daemon ID",v:s.jsx(Tt,{children:h.daemonId})}),h.role&&s.jsx(nt,{k:"Role",v:h.role}),h.machineStatus&&s.jsx(nt,{k:"Machine status",v:h.machineStatus}),h.health&&s.jsx(nt,{k:"Health",v:h.health}),h.isLocalWorktree&&s.jsx(nt,{k:"Worktree",v:h.worktreeBranch?s.jsx(Tt,{children:h.worktreeBranch}):"yes"}),typeof h.launchReady=="boolean"&&s.jsx(nt,{k:"Launch ready",v:h.launchReady?"yes":"no"}),h.git&&s.jsx(nt,{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(nt,{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(nt,{k:"Providers",v:s.jsx(Tt,{children:h.providers.join(", ")})}),Array.isArray(h.providerPriority)&&h.providerPriority.length>0&&s.jsx(nt,{k:"Provider priority",v:s.jsx(Tt,{children:h.providerPriority.join(" › ")})})]}),!h&&v&&(y||j)&&s.jsx(an,{title:"Mesh node",children:s.jsx("div",{className:"text-text-secondary italic",children:v})}),(c==null?void 0:c.coordinator)&&s.jsxs(an,{title:"Mesh coordinator",children:[s.jsx(nt,{k:"Mesh ID",v:s.jsx(Tt,{children:c.coordinator.meshId})}),c.coordinator.cliType&&s.jsx(nt,{k:"Coordinator CLI",v:c.coordinator.cliType}),s.jsx(nt,{k:"Started at",v:s.jsxs(s.Fragment,{children:[Ql(c.coordinator.startedAt),c.coordinator.startedAt?s.jsx("span",{className:"text-text-secondary ml-2",children:Zl(c.coordinator.startedAt)}):null]})}),c.coordinator.injection&&s.jsx(nt,{k:"Prompt injection",v:`${c.coordinator.injection.mode}${c.coordinator.injection.target?` → ${c.coordinator.injection.target}`:""}`}),c.coordinator.mcpConfigPath&&s.jsx(nt,{k:"MCP config",v:s.jsx(Tt,{children:c.coordinator.mcpConfigPath})}),c.coordinator.extraSystemPrompt&&s.jsx(ei,{title:"Per-launch extra prompt",body:c.coordinator.extraSystemPrompt,defaultOpen:!0}),c.coordinator.systemPrompt&&s.jsx(ei,{title:"Final system prompt (click to expand)",body:c.coordinator.systemPrompt})]}),((b=c==null?void 0:c.session)==null?void 0:b.runtimeMetadata)!=null&&s.jsx(Xy,{meta:c.session.runtimeMetadata}),c&&!c.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 an({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 nt({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 Tt({children:e}){return s.jsx("code",{className:"font-mono text-xs",children:e})}function Xy({meta:e}){if(!e||typeof e!="object")return null;const t=e,n=c=>typeof c=="string"&&c.trim()?c:null,r=n(t.runtimeId),a=n(t.lifecycle),o=n(t.surfaceKind),i=n(t.recoveryState),u=Array.isArray(t.attachedClients)?t.attachedClients.length:null;return s.jsxs(an,{title:"Runtime",children:[r&&s.jsx(nt,{k:"Runtime ID",v:s.jsx(Tt,{children:r})}),a&&s.jsx(nt,{k:"Lifecycle",v:a}),o&&s.jsx(nt,{k:"Surface",v:o}),i&&s.jsx(nt,{k:"Recovery state",v:i}),typeof t.restoredFromStorage=="boolean"&&s.jsx(nt,{k:"Restored from storage",v:t.restoredFromStorage?"yes":"no"}),u!=null&&s.jsx(nt,{k:"Attached clients",v:String(u)}),s.jsx(ei,{title:"Raw runtime metadata (click to expand)",body:Qy(e)})]})}function Qy(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function ei({title:e,body:t,defaultOpen:n=!1}){const[r,a]=l.useState(n);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:[r?"▾":"▸"," ",e]}),r&&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 Zy({sessionId:e,daemonId:t,conv:n}){const[r,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:"ⓘ"}),r&&s.jsx(Jy,{sessionId:e,daemonId:t,conv:n,onClose:()=>a(!1)})]})}const ev=8e3;function tv({sessionId:e,daemonId:t,muted:n,sendDaemonCommand:r}){const{t:a}=Xe("common"),[o,i]=l.useState(null),u=l.useRef(null);if(l.useEffect(()=>{o!==null&&n===o&&i(null)},[n,o]),l.useEffect(()=>()=>{u.current&&clearTimeout(u.current)},[]),!e||!t)return null;const c=o!==null?o:n,p=()=>{const d=!c;i(d),u.current&&clearTimeout(u.current),u.current=setTimeout(()=>i(null),ev),r(t,"set_conversation_prefs",{sessionId:e,muted:d}).catch(m=>{console.warn("[conversation-prefs] toggle mute failed",m),i(null)})};return s.jsx("button",{type:"button",onClick:p,"aria-label":a(c?"conversation.unmuteThis":"conversation.muteThis"),"aria-pressed":c,title:a(c?"conversation.mutedTitle":"conversation.muteTitle"),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(Cn,{size:13})})}function Du(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}function Lu(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function sv(e){const t=String(e.role||"").toLowerCase();if(t!=="user"&&t!=="assistant")return!1;const n=String(e.kind||"standard").toLowerCase();return n===""||n==="standard"}function Za(e){return sv(e)?String(e.role||"").toLowerCase():""}const nv=4;function rv(e,t){if(e.length===0)return[];for(let o=t.length-1;o>=0;o-=1)if(Za(t[o])==="assistant")return[];const n=t.some(o=>Za(o)==="user"),r=[];let a=!1;for(let o=e.length-1;o>=0&&r.length<nv;o-=1){const i=e[o],u=Za(i);if(u){if(!a&&u==="assistant"){r.unshift(i),a=!0;continue}if(a&&u==="user"){n||r.unshift(i);break}}}return r}function av(e){return e.map((t,n)=>({message:t,index:n,ts:Du(t)})).sort((t,n)=>t.ts-n.ts||t.index-n.index).map(t=>t.message)}function ov(e){const{historyMessages:t,liveMessages:n,visibleLiveCount:r}=e,a=Math.max(0,n.length-r),o=a>0?n.slice(0,a):[],i=a>0?n.slice(-r):n,u=rv(o,i),c=u.length>0?[...u,...i]:i,p=t.length===0?c:[...t,...c];return av(p)}const ct=e=>e.transport==="pty",An=(e,t)=>ct(e)&&e.mode||"chat",Ru=(e,t)=>ct(e)&&An(e)==="terminal",lt=e=>e.transport==="acp",iv=180;function Ts(e){return e.streamSource!=="agent-stream"}function Ds(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function Ta(e){var n;const t=typeof((n=e.settings)==null?void 0:n.meshCoordinatorDaemonId)=="string"?e.settings.meshCoordinatorDaemonId:void 0;return t?{meshCoordinatorDaemonId:t}:{}}function _u(e){return e.machineName||""}function en(e){return Ds(e)}function xs(e){return e.agentType||""}function aa(e){return e.hostIdeType||""}function Oi(e){return e.displayPrimary||e.agentName||"Agent"}function Eu(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function lv(e,t){const n=Lu(e,t);return[...n].reverse().find(r=>!(r!=null&&r._localId))||n[n.length-1]}function $u(e,t){const n=lv(e,t),r=bn(n==null?void 0:n.content),a=bn(e.lastMessagePreview);return a&&e.lastMessageRole==="assistant"&&(n==null?void 0:n.role)==="user"?a:r||a||""}function cv(e,t=iv){const n=bn(e);if(!n||t<=0)return"";const r=Array.from(n);return r.length<=t?n:`${r.slice(0,Math.max(0,t-1)).join("").trimEnd()}…`}function dv(e){return cv($u(e)||e.displaySecondary||"")}function Fu(e){return[e.displaySecondary,_u(e)].filter(Boolean)}function yn(e){return e.agentName||$t(xs(e))}function uv(e){var t,n;if(!Ts(e)){const r=(n=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:n.trim();if(r)return r}return $t(aa(e)||xs(e))}function Bu(e){return Ts(e)?e.sessionId:e.nativeSessionId}function ec(e){return Ts(e)?"native":e.tabKey}function pv(e){return e.sessionId}function hv(e,t){if(t)return Ts(e)||!t.childSessions?t:t.childSessions.find(n=>n.id===e.sessionId||n.providerType===e.agentType)||t}function mv(e,t){const n=xs(e),r=Ts(e),a=ct(e)||lt(e),o=r?a?yn(e)||(t==null?void 0:t.cliName)||$t(aa(e)||n):t!=null&&t.type?$t(t.type):$t(aa(e)||n):yn(e);return{isNativeConversation:r,isCli:ct(e),isAcp:lt(e),isCliTerminal:Ru(e),providerType:n,displayLabel:o,targetEntry:hv(e,t)}}function Ws(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:ct(e)||lt(e)?{agentType:xs(e)}:e.streamSource==="agent-stream"?{agentType:xs(e)}:t}function Us(e){return e?en(e):""}function on(e,t){e(n=>[...n,{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||""),n=t.toLowerCase();return n.includes("still processing the previous prompt")?"Message queued and will send after the current reply finishes.":n.includes("awaiting confirmation")?"Resolve the pending approval prompt before sending another message.":n.includes("not ready")?"Wait for the runtime to finish starting up before sending a message.":n.includes("not running")?"Runtime is not available right now.":t||"Unable to send message right now."}function Hu(){return"select_session"}function fv(){return"open_panel"}function xv({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function sc(e,t,n=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<n:!1}function Nr(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function er(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Ui(e){return e instanceof Error?e.message:String(e||"")}function nc(e){const t=Ui(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function rc(e,t){const n=Ui(t);return n?n.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${n}`:`⚠️ **${e}** unavailable`}function ac(e,t,n,r={}){const a=Ws(n);if(!t||t.length===0)return{message:e,...r.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},...r.force?{force:!0}:{},...a}}function Pa({sendDaemonCommand:e,activeConv:t,setActionLogs:n,isStandalone:r}){const[a,o]=l.useState(!1),[i,u]=l.useState(!1),[c,p]=l.useState(null),d=l.useRef(!1),m=l.useRef(null);l.useEffect(()=>{p(null)},[t==null?void 0:t.tabKey]);const h=l.useCallback(async(j,x)=>{if(!t||d.current)return!1;const w=j.trim(),N=Wi(t);if(xv({hasMessage:!!w,blockedMessage:N,sendInFlight:d.current}))return N&&p(N),!1;const k=Date.now(),b={tabKey:t.tabKey,message:w,timestamp:k};if(sc(m.current,b))return p(null),!0;d.current=!0,u(!0),p(null),m.current=b;try{const C=Us(t);if(!C)return m.current=Nr(m.current,b),p("Unable to send message right now."),!1;const S=await e(C,"send_chat",ac(w,x,t)),M=er(S);if(M!=null&&M.deduplicated)return p(null),!0;if((M==null?void 0:M.sent)===!1)throw new Error((M==null?void 0:M.error)||"Send failed");if((M==null?void 0:M.success)===!1)throw new Error((M==null?void 0:M.error)||"Send failed");return p(null),!0}catch(C){const S=Ui(C);return S.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",S):console.warn("Send blocked/failed",C),m.current=Nr(m.current,b),p(tc(C)),!1}finally{d.current=!1,u(!1)}},[t,e]),g=l.useCallback(async(j,x)=>{if(!t||d.current)return!1;const w=j.trim();if(!w&&(!x||x.length===0))return!1;const N=Date.now(),k={tabKey:t.tabKey,message:`force:${w}`,timestamp:N};if(sc(m.current,k))return p(null),!0;d.current=!0,u(!0),p(null),m.current=k;try{const b=Us(t);if(!b)return m.current=Nr(m.current,k),p("Unable to send message right now."),!1;const C=await e(b,"send_chat",ac(w,x,t,{force:!0})),S=er(C);if((S==null?void 0:S.success)===!1||(S==null?void 0:S.sent)===!1)throw new Error((S==null?void 0:S.error)||"Send failed");return p(null),!0}catch(b){return console.warn("Force send blocked/failed",b),m.current=Nr(m.current,k),p(tc(b)),!1}finally{d.current=!1,u(!1)}},[t,e]),v=l.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(j){console.error("Relaunch failed",j)}},[t,e]),f=l.useCallback(async j=>{if(t)try{const w=(t.modalButtons||[]).indexOf(j),N=j.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(N),b=Us(t);if(!b)return;const C=await e(b,"resolve_action",{button:j,action:k?"approve":"reject",...w>=0&&{buttonIndex:w},...Ws(t),...Ta(t)}),S=er(C);S.success||n(M=>[...M,{routeId:t.tabKey,text:rc(j,S==null?void 0:S.error),timestamp:Date.now()}])}catch(x){nc(x)||console.error("[ModalButton] Error:",x),n(w=>[...w,{routeId:t.tabKey,text:nc(x)?rc(j,x):`❌ **${j}** error`,timestamp:Date.now()}])}},[t,e,n]),y=l.useCallback(async()=>{if(!(!t||a)){o(!0);try{await e(t.routeId,fv(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(j){console.error("Focus agent failed",j)}finally{o(!1)}}},[t,a,e]);return{isSendingChat:i,sendFeedbackMessage:c,isFocusingAgent:a,handleSendChat:h,handleForceSendChat:g,handleRelaunch:v,handleModalButton:f,handleFocusAgent:y}}const bv=10,gv=8e3,yv=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function vv(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="",n=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(yv.test(t)&&e.trim())return"[REDACTED:secret-field]";const r=vv(e);return r.length>8e3?`${r.slice(0,8e3)}…[truncated ${r.length-8e3} chars]`:r}if(typeof e!="object")return String(e);if(n>=6)return"[MaxDepth]";if(Array.isArray(e)){const r=e.slice(-20).map(a=>ti(a,t,n+1));return e.length>20?[{truncatedBefore:e.length-20},...r]:r}return Object.fromEntries(Object.entries(e).slice(0,80).map(([r,a])=>[r,ti(a,r,n+1)]))}function $n(e,t){return Array.isArray(e)?e.slice(-t):[]}function wv(e,t=Date.now()){const n=e&&t-e.firstAt<=gv,r=n?e.count+1:1;return r>=bv?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:r,firstAt:n?e.firstAt:t},shouldCollect:!1}}function Ou(e){var r,a;const{activeConv:t}=e,n={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:((r=e.chatTailState.liveMessages)==null?void 0:r.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:$n(e.chatTailState.liveMessages??t.messages,10),activeConversationMessagesTail:$n(t.messages,10),visibleMessagesTail:$n(e.visibleMessages,5),historyMessagesTail:$n(e.chatTailState.historyMessages,5),actionLogsTail:$n(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(n)}function Wu(e,t={}){const n=e&&typeof e=="object"?e:{},r=t.locatorCopyStatus??(t.locatorCopied===!1?"failed":"copied"),a=r==="copied"?"locator copied":r==="manual"?"locator shown for manual copy":"locator copy failed";return n.delivery==="daemon_file"?`Chat debug signal sent${typeof n.bundleId=="string"&&n.bundleId.trim()?` (${n.bundleId})`:""}; saved on daemon, ${a}.`:`Chat debug signal sent; ${a}.`}async function Uu(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(n){console.warn("[chat-debug-bundle] clipboard API failed, trying execCommand fallback",n)}if(typeof document<"u"&&document.body){let n=null;try{if(n=document.createElement("textarea"),n.value=e,n.setAttribute("readonly","true"),n.style.cssText="position:fixed;left:-9999px;top:0",document.body.appendChild(n),n.focus(),n.select(),document.execCommand("copy"))return"copied"}catch{}finally{n==null||n.remove()}}if(typeof window<"u"&&typeof window.prompt=="function")try{return window.prompt("Copy ADHDev chat debug locator:",e),"manual"}catch{}return"failed"}function Ku(e){const t=e&&typeof e=="object"?e:{};if(t.delivery==="daemon_file"){const n=["# 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"&&n.push("","summary:",JSON.stringify(t.summary,null,2)),Array.isArray(t.warnings)&&t.warnings.length>0&&n.push("","warnings:",...t.warnings.map(r=>`- ${String(r)}`)),n.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 kv(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function jv(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function sn(e,t){jv()&&console.debug(`[subscription-manager] ${e}`,t)}class Sv{constructor(){st(this,"active",new Map);st(this,"retryTimers",new Map)}subscribe(t,n,r,a,o){var d,m;const i=eo(r.topic,r.key),u=this.active.get(i);let c=!0;if(u)u.handlers.add(a),(!kv(u.request,r)||u.daemonId!==n)&&(u.daemonId=n,u.request=r,c=((d=t.sendData)==null?void 0:d.call(t,n,r))??!1,!c&&(o!=null&&o.retryIntervalMs)?this.scheduleRetry(i,t,o.retryIntervalMs):c&&this.clearRetry(i),sn("subscribe_update",{daemonId:n,topic:r.topic,key:r.key,accepted:c})),u.lastUpdate&&a(u.lastUpdate);else{const h={daemonId:n,request:r,handlers:new Set([a])};this.active.set(i,h),sn("subscribe",{daemonId:n,topic:r.topic,key:r.key}),c=((m=t.sendData)==null?void 0:m.call(t,n,r))??!1,!c&&(o!=null&&o.retryIntervalMs)&&this.scheduleRetry(i,t,o.retryIntervalMs)}const p=()=>{var v;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:r.topic,key:r.key};sn("unsubscribe",{daemonId:n,topic:r.topic,key:r.key}),(v=t.sendData)==null||v.call(t,n,g)};return p.initialSendAccepted=c,p}publish(t){const n=eo(t.topic,t.key),r=this.active.get(n);r&&(this.clearRetry(n),r.lastUpdate=t,xn.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.publish",topic:t.topic,payload:{key:t.key}}),r.handlers.forEach(a=>{a(t),xn.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.handler_invoked",topic:t.topic,payload:{key:t.key}})}))}updateParams(t,n,r){const a=eo(t,n),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...r}})}resubscribeAll(t){var n;sn("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(r=>({daemonId:r.daemonId,topic:r.request.topic,key:r.request.key}))});for(const r of this.active.values())(n=t.sendData)==null||n.call(t,r.daemonId,r.request)}resubscribeForDaemon(t,n){var a;const r=Array.from(this.active.values()).filter(o=>o.daemonId===t);sn("resubscribe_daemon",{daemonId:t,count:r.length,subscriptions:r.map(o=>({topic:o.request.topic,key:o.request.key}))});for(const o of r)(a=n.sendData)==null||a.call(n,o.daemonId,o.request)}scheduleRetry(t,n,r){if(this.retryTimers.has(t))return;const a=setTimeout(()=>{var u;this.retryTimers.delete(t);const o=this.active.get(t);if(!o)return;const i=((u=n.sendData)==null?void 0:u.call(n,o.daemonId,o.request))??!1;sn("subscribe_retry",{id:t,accepted:i,topic:o.request.topic,key:o.request.key}),i||this.scheduleRetry(t,n,r)},r);this.retryTimers.set(t,a)}clearRetry(t){const n=this.retryTimers.get(t);n!==void 0&&(clearTimeout(n),this.retryTimers.delete(t))}}const ls=new Sv;function Nv(e,t){const n=new Map;for(const r of e||[])if((r.daemonId||r.id.includes(":")&&r.id.split(":")[0]||"")===t&&r.sessionId){n.set(r.sessionId,{parentSessionId:r.parentSessionId,providerSessionId:r.providerSessionId,workspace:r.workspace??null,sessionCapabilities:r.sessionCapabilities,cdpConnected:r.cdpConnected,activeChat:r.activeChat,controlValues:r.controlValues,providerControls:r.providerControls,summaryMetadata:r.summaryMetadata,runtimeWriteOwner:r.runtimeWriteOwner,runtimeAttachedClients:r.runtimeAttachedClients,cliName:r.cliName,type:r.type,mode:r.mode,status:r.status,lastMessagePreview:r.lastMessagePreview,lastMessageRole:r.lastMessageRole,lastMessageAt:r.lastMessageAt,lastMessageHash:r.lastMessageHash,completionMarker:r.completionMarker,seenCompletionMarker:r.seenCompletionMarker,settings:r.settings,activeInteractivePrompt:r.activeInteractivePrompt});for(const o of r.childSessions||[]){if(!(o!=null&&o.id))continue;const i=n.get(o.id)||{};n.set(o.id,{...i,...o})}}return n}function Cv(e){const t=[],n=new Map;for(const r of e)if(r.parentId){const a=n.get(r.parentId)||[];a.push(r),n.set(r.parentId,a)}else t.push(r);return{topLevel:t,childrenByParent:n}}function to(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function Mv(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function Av(e){Mv()&&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 n=[],{daemonId:r,existingDaemon:a,existingEntries:o,timestamp:i}=t,u=i||e.timestamp||Date.now(),c=e.sessions||[],{topLevel:p,childrenByParent:d}=Cv(c),m=Nv(o,r),h=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,g=p.filter(y=>y.kind==="workspace"&&y.transport==="cdp-page"),v=p.filter(y=>y.kind==="agent"&&y.transport==="pty"),f=p.filter(y=>y.kind==="agent"&&y.transport==="acp");n.push({...a||{},id:r,type:"adhdev-daemon",status:"online",timestamp:u,...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(y=>!!y.cdpConnected)});for(const y of g){const j=m.get(y.id),x=zn(y,j),w=(d.get(y.id)||[]).map(N=>zn(N,m.get(N.id)));n.push({id:`${r}:ide:${y.id}`,sessionId:y.id,providerSessionId:y.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,status:x.cdpConnected?"online":"detected",daemonId:r,instanceId:to(r,y.id),workspace:x.workspace,terminals:0,childSessions:w,agents:w.map(N=>({id:N.id,name:N.providerName||N.providerType,type:N.providerType,status:N.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:u})}for(const y of v){const j=m.get(y.id),x=zn(y,j);n.push({id:`${r}:cli:${y.id}`,sessionId:y.id,providerSessionId:y.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,agentType:x.providerType,status:x.status||"running",daemonId:r,instanceId:to(r,y.id),cliName:x.providerName||x.providerType,mode:x.mode||(j==null?void 0:j.mode)||"terminal",workspace:x.workspace||"",...y.ownerDaemonId&&{ownerDaemonId:y.ownerDaemonId},...y.ownerMachineName&&{ownerMachineName:y.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:u,_isCli:!0})}for(const y of f){const j=m.get(y.id),x=zn(y,j);n.push({id:`${r}:acp:${y.id}`,sessionId:y.id,providerSessionId:y.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,agentType:x.providerType,status:x.status||"running",daemonId:r,instanceId:to(r,y.id),cliName:x.providerName||x.providerType,mode:"chat",workspace:x.workspace||"",...y.ownerDaemonId&&{ownerDaemonId:y.ownerDaemonId},...y.ownerMachineName&&{ownerMachineName:y.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:u,_isAcp:!0})}return Av(n),n}const Iv=15e3,Tv=15e3,Pv=6e4,oc=12,Dv=8e3,Lv=4e3;function Rv(e){const{force:t,hasSubscription:n,loadedAt:r,now:a,minFreshMs:o}=e;return t||r<=0?!0:n?!1:a-r>=o}const so=new Map,no=new Map,Cr=new Set;function _v(e){if(!e||typeof e!="object")return null;const t=e,n=t.status;if(n&&typeof n=="object")return n;const r=t.result;if(r&&typeof r=="object"&&"status"in r){const a=r.status;if(a&&typeof a=="object")return a}return t}function In(){const{sendCommand:e,sendData:t}=yt(),{injectEntries:n,getIdes:r}=ar();return l.useCallback(async(a,o)=>{if(!a)return;const i=(o==null?void 0:o.minFreshMs)??Pv;if(!Rv({force:o==null?void 0:o.force,hasSubscription:Cr.has(a),loadedAt:no.get(a)||0,now:Date.now(),minFreshMs:i}))return;const u=so.get(a);if(u)return u;const c=(async()=>{t&&!Cr.has(a)&&(ls.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},f=>{const y=r(),j=y.find(w=>w.id===a),x=oa(f.status,{daemonId:a,existingDaemon:j,existingEntries:y,timestamp:f.timestamp});x.length>0&&n(x),no.set(a,Date.now())}).initialSendAccepted?Cr.add(a):Cr.delete(a));const p=await e(a,"get_status_metadata"),d=_v(p);if(!d)return;const m=r(),h=m.find(v=>v.id===a),g=oa(d,{daemonId:a,existingDaemon:h,existingEntries:m,timestamp:d.timestamp||Date.now()});g.length>0&&n(g,{authoritativeDaemonIds:[a]}),no.set(a,Date.now())})().finally(()=>{so.delete(a)});return so.set(a,c),c},[r,n,e,t])}const Ev=60,$v=50;function Gu(e={}){return e.isCliLike?$v:Ev}function Fv(e={}){return Gu(e)}const fr=60,Bv=1e3,Hv=750,ic=500,Da=12e4,zu=new Set(["generating","waiting_approval","starting","streaming","working"]),lr=new Map;let Vu=0;const si=new Set;function Ov(){Vu+=1;for(const e of si)e()}function Wv(e){return si.add(e),()=>{si.delete(e)}}function lc(){return Vu}function xr(e,t,n){return`${e}::${t}::${n||t}`}function ia(e=fr){return{liveMessages:[],hasLiveSnapshot:!1,cursor:Uv([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Uv(e,t=fr){return{tailLimit:t}}function cc(e,t){const n=e[e.length-1];if(!n)return"empty:";let r="";try{r=JSON.stringify(n.content??"")}catch{r=String(n.content??"")}return["",e.length,String(n.id||""),String(n.index??""),String(n.receivedAt??n.timestamp??""),r].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 Ki(e){return la(e.content).replace(/[─━═│┃┄┅┈┉┌┐└┘├┤┬┴┼╭╮╰╯╴╶╷╵\s]+/g,"").length===0}function Kv(e){return e.length===0||e.every(Ki)}function dc(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t],r=typeof(n==null?void 0:n.role)=="string"?n.role:"",a=typeof(n==null?void 0:n.kind)=="string"?n.kind:"";if(!(r==="system"||a==="system")&&!(a==="tool"||a==="thought"||a==="terminal"||a==="activity")&&!Ki(e[t]))return r}return""}function uc(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t],r=typeof(n==null?void 0:n.role)=="string"?n.role:"",a=typeof(n==null?void 0:n.kind)=="string"?n.kind:"";if(r==="system"||a==="system"||a==="tool"||a==="thought"||a==="terminal"||a==="activity"||Ki(e[t]))continue;if(r!=="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 n=Array.isArray(e.liveMessages)?e.liveMessages:[];return dc(n)!=="assistant"}function Gv(e){return!!e&&typeof e=="object"&&e.selected==="native-history"}function zv(e,t,n){return Gv(n)?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 Vv(e,t,n,r,a,o){const i=Ju(r)||Yu(r),u=o&&e.hasLiveSnapshot;if(!i&&!u)return!1;const c=i?Xu(e,t):Array.isArray(e.liveMessages)?e.liveMessages.length:0;if(c<=0)return!1;if(Kv(n))return!0;if(u&&!i&&qu(e,n))return!1;if(a&&typeof a=="object"){const p=a.selected,d=a.fallbackReason;if(p==="native-history"||typeof d=="string"&&d!==""&&!d.startsWith("native_history_"))return!1}return n.length<c}function qv(e,t,n,r){if(n.length!==0||Xu(e,t)<=0||e.hasLiveSnapshot&&e.liveMessages.length===0||!r||typeof r!="object")return!1;const o=r.selected,i=r.fallbackReason,u=r.nativeSource;return o==="native-history"?!1:u==="native-unavailable"?!0:typeof i=="string"&&i.startsWith("native_history_")}function Yv(e,t,n,r,a,o){return Vv(e,t,n,r,a,o)?"defer-busy-shrink":qv(e,t,n,a)?"skip-transient-empty":"apply"}function Jv(e){if(Array.isArray(e.messages))return e.messages;const t=e.messagesTail;return Array.isArray(t)?t:[]}function pc(e,t){const n=e[t];return typeof n=="string"?n:""}class Xv{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||ls,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??fr))}updateOptions(t){const n=this.sendData,r=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&&(n!==this.sendData||r!==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 n=(async()=>{try{const r=this.snapshot.hasLiveSnapshot,a=r?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:[],u=!r&&i.length===0&&o.hasMore!==!0&&this.fallbackRecentCount>0,c=[...i,...this.snapshot.historyMessages],p=c.length>ic?c.slice(c.length-ic):c;this.snapshot={...this.snapshot,historyMessages:p,historyOffset:this.snapshot.historyOffset+i.length,hasMoreHistory:u?!0:o.hasMore===!0,historyError:null}}catch(r){this.snapshot={...this.snapshot,historyError:r instanceof Error?r.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=n,n}refreshAuthoritativeTail(t,n={}){if(this.authoritativeRefreshPromise)return this.authoritativeRefreshPromise;const r=this.now();if(!n.force&&this.lastAuthoritativeRefreshAt>0&&r-this.lastAuthoritativeRefreshAt<Hv)return Promise.resolve();this.lastAuthoritativeRefreshAt=r;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:Bv}))}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 n=pc(t,"sessionId");if(n&&n!==this.sessionId)return;const r=pc(t,"historySessionId");if(r&&this.historySessionId&&r!==this.historySessionId)return;const a=Jv(t),o=t.messageSource,i=this.now(),u=this.lastActiveStatusAt>0&&i-this.lastActiveStatusAt<=Da;(Ju(t.status)||Yu(t.status))&&(this.lastActiveStatusAt=i);const c=zv(this.snapshot,a,o);if(!c&&Yv(this.snapshot,this.fallbackRecentCount,a,t.status,o,u)!=="apply")return;const p={tailLimit:this.snapshot.cursor.tailLimit};!c&&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=xr(e.daemonId,e.sessionId,e.historySessionId),n=lr.get(t);if(n)return n.updateOptions(e),n;const r=new Xv(e);return lr.set(t,r),Ov(),r}function Qv(e,t,n){if(!e||!t)return;const r=`${e}::${t}::`,a=xr(e,t,n);for(const[o,i]of lr.entries())(o===a||o.startsWith(r))&&i.clearLiveSnapshot()}function Zu(e){const t=en(e),n=e.sessionId||"";if(!t||!n)return;const r=Aa(e),a=xr(t,n,r||n),o=lr.get(a);if(!o)return;const i=o.getSnapshot();return i.hasLiveSnapshot?i:void 0}function Zv(e,t){return{...e,loadHistoryPage:t}}function e0(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||(e.historySessionId||"").localeCompare(t.historySessionId||"")}function t0(e,t={}){const n=String(e.status||"").trim().toLowerCase();if(zu.has(n)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const r=t.now??Date.now(),a=Math.max(0,Number(t.recentActivityMs??Da)),o=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return o>0?r-o<=a:Array.isArray(e.messages)&&e.messages.length>0}function s0(e=Da){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function n0(e,t={}){const n=new Set,r=[];for(const a of e){if(!t0(a,t))continue;const o=en(a),i=a.sessionId||"";if(!o||!i)continue;const u=Aa(a),c=xr(o,i,u||i);n.has(c)||(n.add(c),r.push({daemonId:o,sessionId:i,historySessionId:u,subscriptionKey:`daemon:${o}:session:${i}`}))}return r.sort(e0),{descriptors:r,signature:r.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function r0(e,t){const{sendData:n,sendCommand:r,isConnected:a}=yt(),o=(t==null?void 0:t.enabled)!==!1,i=en(e),u=e.sessionId||"",c=Aa(e),p=`daemon:${i}:session:${u}`,d=Math.max(0,(t==null?void 0:t.tailLimit)??fr),m=e.messages.length,h=l.useMemo(()=>!o||!i||!u?null:Qu({daemonId:i,sessionId:u,historySessionId:c,subscriptionKey:p,sendData:n,tailLimit:d,fallbackRecentCount:m}),[i,o,c,n,u,p,d]);l.useEffect(()=>{h==null||h.updateOptions({fallbackRecentCount:m})},[h,m]);const[g,v]=l.useState(()=>(h==null?void 0:h.getSnapshot())||ia(d));l.useEffect(()=>{if(!h){v(ia(d));return}h.retain(),v(h.getSnapshot());const j=h.subscribe(x=>{v(x)});return()=>{j(),h.release()}},[h,d]);const f=l.useCallback(async()=>{!h||!i||!u||await h.loadHistoryPage(async({offset:j,excludeRecentCount:x})=>{const w=e.agentType,N=await r(i,"chat_history",{agentType:w,offset:j,limit:30,targetSessionId:u,historySessionId:c,excludeRecentCount:x}),k=N&&typeof N=="object"&&"result"in N?N.result||{}:N||{};return{messages:Array.isArray(k.messages)?k.messages:[],hasMore:k.hasMore===!0}})},[e.agentType,h,i,c,r,u]),y=l.useCallback((j=!1)=>!h||!i||!u?Promise.resolve():h.refreshAuthoritativeTail(async()=>{const x=await r(i,"read_chat",{agentType:e.agentType,targetSessionId:u,historySessionId:c,...d>0?{tailLimit:d}:{}}),w=x&&typeof x=="object"&&"result"in x?x.result:x;if(!w||typeof w!="object"||w.success===!1)return null;const N=Array.isArray(w.messages)?w.messages:Array.isArray(w.messagesTail)?w.messagesTail:[];return{topic:"session.chat_tail",key:p,sessionId:u,historySessionId:c,seq:0,timestamp:0,messages:N,status:typeof w.status=="string"?w.status:"idle",...w.messageSource&&typeof w.messageSource=="object"?{messageSource:w.messageSource}:{}}},{force:j}),[e.agentType,h,i,c,r,u,p,d]);return l.useEffect(()=>{if(!h||!o||!i||!u)return;y(!0);const j=()=>{typeof document<"u"&&document.visibilityState==="visible"&&y()};typeof document<"u"&&document.addEventListener("visibilitychange",j);let x=a?a(i):!0;const w=setInterval(()=>{if(!a)return;const N=a(i);N&&!x&&y(),x=N},2e3);return()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",j),clearInterval(w)}},[h,i,o,u,c]),l.useMemo(()=>Zv(g,f),[f,g])}function a0(e,t){const{sendData:n}=yt(),r=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??fr),o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Da)),i=s0(o),[u,c]=l.useState(0);l.useEffect(()=>{if(!r||e.length===0)return;const d=setInterval(()=>{c(m=>m+1)},i);return()=>{clearInterval(d)}},[e.length,r,i]);const p=l.useMemo(()=>n0(e,{recentActivityMs:o}),[e,o,u]);l.useEffect(()=>{if(!r||!n||p.descriptors.length===0)return;const d=p.descriptors.map(m=>Qu({...m,sendData:n,tailLimit:a}));return d.forEach(m=>{m.retain()}),()=>{d.forEach(m=>m.release())}},[p.signature,r,n,a])}function o0(e){const[t,n]=l.useState(0),r=l.useMemo(()=>{const i=[];for(const u of e){const c=en(u),p=u.sessionId||"";if(!c||!p)continue;const d=Aa(u);i.push(xr(c,p,d||p))}return i},[e]),a=r.join("|"),o=l.useSyncExternalStore(Wv,lc,lc);return l.useEffect(()=>{if(r.length===0)return;const i=[];for(const u of r){const c=lr.get(u);if(!c)continue;let p=!1;i.push(c.subscribe(()=>{if(!p){p=!0;return}n(d=>d+1)}))}return()=>{for(const u of i)u()}},[a,o]),t}function i0(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function l0(e){return i0(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Gr=new Map,ni=new Set;function hc(e,t){!e||Gr.get(e)===t||(t?Gr.set(e,!0):Gr.delete(e),ni.forEach(r=>r(e,t)))}function c0(e){return e?Gr.get(e)===!0:!1}function d0(e){return ni.add(e),()=>{ni.delete(e)}}function u0(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function p0(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function h0(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 m0(e){return ep(e)?!1:e.inboxBucket==="task_complete"&&tp(e).length>0}function mc(e){return e.branch||"detached HEAD"}function f0(e){if(e.error)return`${mc(e)} · Git error: ${e.error}`;const t=[mc(e)];return e.changedFiles>0?t.push(u0(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 x0(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${f0(t)}`}function b0(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function g0(e,t={}){if(t.enabled===!1)return[];if(!h0(e))return[];const n=ep(e)?"working":m0(e)?"complete":null;if(!n)return[];const r=n==="complete"?tp(e):"";return[{id:n==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${p0(r)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:x0(n,e.git),timestamp:b0(e,e.git),meta:{source:"git-system-bubble",phase:n,workspace:e.workspacePath,repoRoot:e.git.repoRoot,branch:e.git.branch,changedFiles:e.git.changedFiles,hasConflicts:e.git.hasConflicts}}]}const y0=60;function v0(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 ri({activeConv:e,ideEntry:t,handleSendChat:n,handleForceSendChat:r,isSendingChat:a=!1,sendFeedbackMessage:o=null,handleFocusAgent:i,isFocusingAgent:u,actionLogs:c,userName:p,scrollToBottomRequestNonce:d,isInputActive:m=!0,isVisible:h=!0}){var me,U,W,Q,V,fe,ce,F;const{t:g}=Xe("common"),v=l.useRef(new Map),f=l.useRef(void 0),y=In(),{sendCommand:j}=yt(),{isVisible:x}=Li();mr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:c.length,isSendingChat:a});const w=Rt.useMemo(()=>Mn(e),[e.status,e.connectionState]);Rt.useEffect(()=>{const le=e.sessionId;if(le)return hc(le,w.isGenerating),()=>{hc(le,!1)}},[e.sessionId,w.isGenerating]);const N=l.useMemo(()=>mv(e,t),[e,t]),k=l.useMemo(()=>{var le;return $i((le=N.targetEntry)==null?void 0:le.providerControls,{hostIdeType:e.hostIdeType,providerType:N.providerType})},[e.hostIdeType,N.providerType,(me=N.targetEntry)==null?void 0:me.providerControls]),b=Gu({isCliLike:N.isCli||N.isAcp}),C=Fv({isCliLike:N.isCli||N.isAcp}),S=r0(e,{enabled:h&&!!e.sessionId,tailLimit:C}),[M,A]=l.useState(b),[T,L]=l.useState(()=>Dl()),P=e.tabKey,B=S.historyMessages,z=S.hasMoreHistory,R=S.historyError,_=Lu(e,S),K=su(_).length;l.useEffect(()=>{A(b)},[b,P]);const E=Math.max(0,_.length-M),D=Oi(e),$=en(e),I=l0(e),G=Wi(e),Y=v0(e),Z=o||G,q=Z||Y,ne=!!G,[ue,ae]=l.useState(!1);l.useEffect(()=>{const le=N.targetEntry;$&&(!le||le.providerControls===void 0||le.controlValues===void 0)&&y($,{minFreshMs:3e4}).catch(()=>{})},[$,N.isAcp,(U=N.targetEntry)==null?void 0:U.providerControls,(W=N.targetEntry)==null?void 0:W.controlValues,y]);const O=l.useCallback(async()=>{if(!ue){if(_.length>M){A(le=>Math.min(_.length,le+y0));return}ae(!0);try{await S.loadHistoryPage()}finally{ae(!1)}}},[S,ue,_.length,M]),{allMessages:se,receivedAtMap:X}=l.useMemo(()=>{const le=ov({historyMessages:B,liveMessages:_,visibleLiveCount:M}),je=g0(e),de=je.length>0?[...le,...je]:le,H={};return de.forEach((be,Ne)=>{const Ce=`${e.tabKey}:${ta(be)}`;let $e=Du(be)||v.current.get(Ce)||0;$e||($e=Date.now(),v.current.set(Ce,$e)),H[ta(be)]=$e}),{allMessages:de,receivedAtMap:H}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,E,B,_,M]),oe=l.useMemo(()=>c.filter(le=>le.routeId===e.tabKey).sort((le,je)=>le.timestamp-je.timestamp),[c,e.tabKey]),Se=l.useCallback(async()=>{var Ne,Ce;if(!$)return;const le=Ou({activeConv:e,visibleMessages:se,actionLogs:c,controls:(Ne=N.targetEntry)==null?void 0:Ne.providerControls,controlValues:(Ce=N.targetEntry)==null?void 0:Ce.controlValues,visibleBarControlCount:k.length,chatTailState:{liveMessages:S.liveMessages,hasLiveSnapshot:S.hasLiveSnapshot,hasMoreHistory:z,historyError:R,historyMessages:B},ui:{controlsVisible:x,visibleLiveCount:M,activityVisible:T,activityCount:K,hiddenLiveCount:E,isInputActive:m,isVisible:h}}),je=await j($,"get_chat_debug_bundle",{agentType:N.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:le}),de=er(je),H=Ku(de),be=await Uu(H);be==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),ht.showToast(Wu(de,{locatorCopyStatus:be}),be==="failed"?"warning":"success")},[e,c,K,se,x,S.hasLiveSnapshot,S.liveMessages,N.providerType,(Q=N.targetEntry)==null?void 0:Q.controlValues,(V=N.targetEntry)==null?void 0:V.providerControls,$,z,E,B,m,h,R,j,T,k.length,M]);l.useEffect(()=>{const le=je=>{je.key===eu&&L(Dl())};return window.addEventListener("storage",le),()=>window.removeEventListener("storage",le)},[]);const ye=l.useCallback(()=>{const le=wv(f.current);f.current=le.state,le.shouldCollect&&Se().catch(je=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",je),ht.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[Se]),ke=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:[g("chatPane.connectingToMachine"),s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:g("chatPane.establishingP2P")})]})]});if((w.isGenerating||e.status==="streaming")&&ae(!1),e.status==="not_monitored"&&I)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(or,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:g("chatPane.agentNotMonitored")}),s.jsx("button",{onClick:i,disabled:u,className:"btn btn-primary",children:u?`⌛ ${g("chatPane.switchingPanel")}`:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(gn,{size:14})," ",g("chatPane.openPanel",{label:D})]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:g("chatPane.clickToSwitchMonitoring")})]});if(e.status==="panel_hidden"&&I)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:g("chatPane.agentPanelHidden")}),s.jsx("button",{onClick:i,disabled:u,className:"btn btn-primary",children:u?`⌛ ${g("chatPane.openingPanel")}`:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(gn,{size:14})," ",g("chatPane.openPanel",{label:D})]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:g("chatPane.openPanelHint")})]});if(e.status==="idle"&&!ue)return!z&&B.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:g("chatPane.noMessagesYet")})]}):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:g("chatPane.loadingChat")})]})}},[e.connectionState,e.status,I,i,z,B.length,u,ue,_.length,D,w.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(tv,{sessionId:e.sessionId,daemonId:e.daemonId,muted:!!((fe=N.targetEntry)!=null&&fe.muted),sendDaemonCommand:j}),s.jsx(Zy,{sessionId:e.sessionId,daemonId:e.daemonId,conv:e})]})}),s.jsx(fx,{messages:se,actionLogs:oe,agentName:yn(e)||D||"Agent",userName:p,isCliMode:N.isCli||N.isAcp,isWorking:w.isGenerating,contextKey:e.tabKey,receivedAtMap:X,lastMessageHash:e.lastMessageHash,showActivityMessages:T,onLoadMore:O,isLoadingMore:ue,hasMoreHistory:z,hiddenLiveCount:E,loadError:R??void 0,emptyState:ke,scrollToBottomRequestNonce:d,isVisible:h}),s.jsx(Cy,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:N.providerType,displayLabel:N.displayLabel,controls:(ce=N.targetEntry)==null?void 0:ce.providerControls,controlValues:(F=N.targetEntry)==null?void 0:F.controlValues,currentStatus:e.status,coordinatorHint:Ta(e),isActive:m,isCliTerminal:N.isCliTerminal}),!N.isCliTerminal&&s.jsx(Cu,{contextKey:e.tabKey,panelLabel:D,isSending:a,isBusy:ne,statusMessage:q,inlineStatusMessage:Z,onSend:n,onForceSend:r,canForceSend:!!r&&w.isGenerating&&!ne,isActive:m,showControlsToggle:k.length>0,onControlsToggle:ye,messageInput:e.messageInput})]})}let sp=bs;function np(){return sp()}class w0{constructor(){st(this,"listeners",new Map)}send(t){}isConnected(){return!1}on(t,n){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(n),()=>{var r;(r=this.listeners.get(t))==null||r.delete(n)}}emit(t,...n){var r;(r=this.listeners.get(t))==null||r.forEach(a=>a(...n))}}let rp=new w0;class k0{sendPtyInput(t,n,r){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,n){return!1}get(t){}onScreenshot(t,n){return()=>{}}onRuntimeEvent(t,n,r){return()=>{}}requestRuntimeSnapshot(t,n,r){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let kt=new k0;function j0(e){e.dashboardWS&&(rp=e.dashboardWS),e.connectionManager&&(kt=e.connectionManager),e.useDaemonsHook&&(sp=e.useDaemonsHook)}const S0=.5,N0=1.25,ns="\x1B",fc={ArrowUp:"A",ArrowDown:"B",ArrowLeft:"D",ArrowRight:"C"};function C0(e){return 1+(e.shift?1:0)+(e.alt?2:0)+(e.ctrl?4:0)}function xc(e,t){let n=e;if(t.shift&&n.length===1&&(n=n.toUpperCase()),t.ctrl){const r=n.toUpperCase().charCodeAt(0);return String.fromCharCode(r&31)}return n}function M0(e,t){if(t in fc){const r=fc[t],a=C0(e);return a===1?`${ns}[${r}`:`${ns}[1;${a}${r}`}switch(t){case"Enter":return e.alt?`${ns}\r`:"\r";case"Escape":return e.alt?`${ns}${ns}`:ns;case"Backspace":{const r=e.ctrl?"\b":"";return e.alt?`${ns}${r}`:r}case"Tab":{const r=e.shift?`${ns}[Z`:" ";return e.alt&&!e.shift?`${ns} `:r}case"Space":{const r=xc(" ",e);return e.alt?`${ns}${r}`:r}}const n=xc(t,e);return e.alt?`${ns}${n}`:n}function gt(e){return Oi(e)}function vn(e){return Fu(e).join(" · ")}function ap(e){var t,n;return!!e.daemonId&&!!((t=e.coordinator)!=null&&t.meshId||typeof((n=e.settings)==null?void 0:n.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.trim().length>0)}function A0(e){var a,o,i;const t=[],n=typeof((a=e.settings)==null?void 0:a.meshNodeFor)=="string"&&e.settings.meshNodeFor.trim().length>0,r=!!((o=e.coordinator)!=null&&o.meshId)||typeof((i=e.settings)==null?void 0:i.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.trim().length>0;return n&&t.push("Mesh node"),r&&t.push("Coordinator"),t}function I0(e){var i,u,c;const t=[],n=typeof((i=e.settings)==null?void 0:i.meshNodeFor)=="string"?e.settings.meshNodeFor.trim():"",r=typeof((u=e.coordinator)==null?void 0:u.meshId)=="string"?e.coordinator.meshId.trim():"",a=typeof((c=e.settings)==null?void 0:c.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor.trim():"",o=r||a;if(n&&t.push(`Mesh node: ${n}`),o&&t.push(`Coordinator: ${o}`),e.meshQueueStats){const{pending:p,assigned:d,completed:m,failed:h}=e.meshQueueStats;t.push(`Queue: ${p} pending, ${d} assigned, ${m} completed, ${h} failed`)}return t.join(" · ")}function op(e,t){const n=$u(e,t);return n||(e.title?e.title:vn(e)||"No messages yet")}function ip(e,t){const{isReconnecting:n,isConnecting:r}=Mn(e);return n?"Reconnecting…":r?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function T0(e,t){const n=["Chat",...Fu(e)];return t!=null&&t.timestampLabel&&n.push(t.timestampLabel),n.filter(Boolean).join(" · ")}function Ks(e){return ip(e)||vn(e)}function P0(e,t){return`${gt(e)} · ${op(e,t)}`}function D0(e){const t=aa(e),n=t?$t(t):yn(e);return`${gt(e)} — ${n||"Agent"}`}function L0(e){return yn(e)||"CLI"}function lp(e){return Eu(e)}function cp(e){return e?`Remote · ${gt(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:""}})}],R0=[{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 _0(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:n,onChange:r,onRemove:a,onPreview:o,preview:i}){const u=_0(e),c=i[t],p=d=>{const m=bc.find(h=>h.kind===d);m&&r(m.make(n))};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:u,onChange:d=>p(d.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(d=>s.jsx("option",{value:d.kind,children:d.label},d.kind))}),(u==="regex"||u==="stable"||u==="changed"||u==="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"}),c&&c!=="loading"&&s.jsx("span",{className:`text-[10px] font-mono px-1.5 py-0.5 rounded ${c.result?"text-status-online bg-status-online/20":"text-text-secondary bg-bg-glass"}`,children:c.result?"match ✓":"no match"}),c==="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:"×"})]}),u==="regex"&&s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs("select",{value:e.section??"",onChange:d=>r({...e,section:d.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)"}),n.map(d=>s.jsx("option",{value:d,children:d},d))]}),s.jsx("input",{value:e.matches??"",onChange:d=>r({...e,matches:d.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"})]}),u==="elapsed"&&s.jsx(As,{label:"elapsed_ms",value:e.elapsed_ms,onChange:d=>r({elapsed_ms:d})}),u==="stable"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(As,{label:"stable_ms",value:e.stable_ms,onChange:d=>r({...e,stable_ms:d})}),s.jsx(As,{label:"cursor_above",value:e.cursor_above??0,onChange:d=>r({...e,cursor_above:d||void 0})})]}),u==="changed"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(As,{label:"cursor_above",value:e.cursor_above,onChange:d=>r({...e,cursor_above:d})}),s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-secondary",children:[s.jsx("input",{type:"checkbox",checked:!!e.changed,onChange:d=>r({...e,changed:d.target.checked}),className:"accent-[var(--accent-primary)]"}),"changed"]})]}),(u==="all"||u==="any")&&s.jsx(E0,{kind:u,cond:e,path:t,sections:n,onChange:r,onPreview:o,preview:i}),u==="not"&&s.jsx("div",{className:"pl-2 border-l border-border-default",children:s.jsx(Gi,{cond:e.not,path:`${t}.not`,sections:n,onChange:d=>r({not:d}),onPreview:o,preview:i})})]})}function E0({kind:e,cond:t,path:n,sections:r,onChange:a,onPreview:o,preview:i}){const u=(e==="all"?t.all:t.any)??[],c=p=>a(e==="all"?{all:p}:{any:p});return s.jsxs("div",{className:"pl-2 border-l border-border-default space-y-1",children:[u.map((p,d)=>s.jsx(Gi,{cond:p,path:`${n}.${e}[${d}]`,sections:r,onChange:m=>c(u.map((h,g)=>g===d?m:h)),onRemove:()=>c(u.filter((m,h)=>h!==d)),onPreview:o,preview:i},d)),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:()=>c([...u,{section:r[0],matches:""}]),children:"+ condition"}),R0.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:()=>c([...u,JSON.parse(JSON.stringify(p.cond))]),title:"insert verified pattern",children:["+ ",p.label]},p.label))]})]})}function As({label:e,value:t,onChange:n}){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:r=>n(Number(r.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 $0({sections:e,otherSectionIds:t,onChange:n,onTest:r,testResult:a}){const o=Object.keys(e),i=a&&a!=="loading"&&!("error"in a)?Object.fromEntries(a.sections.map(m=>[m.id,m])):{},u=(m,h)=>{if(!h||h===m||e[h])return;const g={};for(const[v,f]of Object.entries(e))g[v===m?h:v]=f;n(g)},c=(m,h)=>n({...e,[m]:h}),p=m=>{const h={...e};delete h[m],n(h)},d=()=>{let m="section",h=1;for(;e[m];)m=`section${h++}`;n({...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:r,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:d,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",v=y=>{y==="anchor"?c(m,{anchor:h.anchor??"^",anchor_last:h.anchor_last,until:h.until}):c(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:y=>u(m,y.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:()=>v("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:()=>v("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(As,{label:"from_top",value:typeof h.from_top=="number"?h.from_top:0,onChange:y=>c(m,{...h,from_top:y,from_bottom:void 0})}),s.jsx(As,{label:"from_bottom",value:typeof h.from_bottom=="number"?h.from_bottom:0,onChange:y=>c(m,{...h,from_bottom:y||void 0})}),s.jsx(gc,{def:h,otherIds:t(m),onChange:y=>c(m,y)})]}):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:y=>c(m,{...h,anchor:y.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:y=>c(m,{...h,anchor_last:y.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:y=>c(m,y)})}),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:y=>c(m,{...h,anchor_context:{...h.anchor_context,next:y.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:n}){const r=e.until??"",a=r.startsWith("^");return s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-secondary",children:["until",s.jsxs("select",{value:a?"__regex__":r,onChange:o=>{const i=o.target.value;n(i===""?{...e,until:void 0}:i==="__regex__"?{...e,until:r.startsWith("^")?r:"^"}:{...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:r,onChange:o=>n({...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 F0({model:e,onChange:t,onPreview:n,preview:r,onTestSections:a,sectionPreview:o}){const i=e.states.map(m=>m.id),u=Object.keys(e.sections??{}),c=l.useCallback(m=>t({...e,...m}),[e,t]),p=(m,h)=>c({states:e.states.map((g,v)=>v===m?{...g,...h}:g)}),d=(m,h)=>c({transitions:e.transitions.map((g,v)=>v===m?{...g,...h}:g)});return s.jsxs("div",{className:"space-y-3",children:[s.jsx($0,{sections:e.sections??{},otherSectionIds:m=>u.filter(h=>h!==m),onChange:m=>c({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:()=>c({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:()=>c({states:e.states.filter((g,v)=>v!==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:()=>c({states:e.states.map((g,v)=>({...g,initial:v===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:()=>c({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(B0,{value:m.from,states:i,onChange:g=>d(h,{from:g})}),s.jsx("span",{className:"text-[10px] text-text-muted",children:"→"}),s.jsx("select",{value:m.to,onChange:g=>d(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=>d(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:()=>c({transitions:e.transitions.filter((g,v)=>v!==h)}),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(As,{label:"min_hold_ms",value:m.min_hold_ms??0,onChange:g=>d(h,{min_hold_ms:g||void 0})}),s.jsx(As,{label:"priority",value:m.priority??0,onChange:g=>d(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:()=>d(h,{when:{section:u[0],matches:""}}),children:"+ guard condition"}),m.when&&s.jsx("button",{type:"button",className:"text-[10px] text-text-muted hover:text-status-error",onClick:()=>d(h,{when:void 0}),children:"remove guard"})]}),m.when&&s.jsx(Gi,{cond:m.when,path:`t${h}`,sections:u,onChange:g=>d(h,{when:g}),onPreview:n,preview:r})]})]},h))})]})]})}function B0({value:e,states:t,onChange:n}){const r=new Set(Array.isArray(e)?e:e==="*"?t:[e]),a=e==="*",o=i=>{const u=new Set(r);u.has(i)?u.delete(i):u.add(i);const c=t.filter(p=>u.has(p));n(c.length===1?c[0]:c)};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||r.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 Fn(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 n=Math.floor(t/6e4);return n<60?`${n}m ago`:`${Math.floor(n/60)}h ago`}function yc(e){return e<=0?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}const H0={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"},O0={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 ro(e){return O0[e]??"text-text-primary bg-bg-glass border border-border-default"}function Mr({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 Ar(){return s.jsx("div",{className:"border-t border-white/8 my-2"})}function dp({node:e,depth:t=0}){var a;const n=e.result?"text-status-online":"text-text-muted",r=e.result?"●":"○";return s.jsxs("div",{style:{marginLeft:t*10},className:"font-mono text-[10px] leading-relaxed",children:[s.jsxs("span",{className:n,children:[r," "]}),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 W0({t:e}){const[t,n]=l.useState(!1),r=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:()=>n(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 ${r}`,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 U0({activeConv:e,onClose:t}){var oe,Se,ye,ke,me;const{sendCommand:n}=yt(),[r,a]=l.useState(!0),[o,i]=l.useState(null),[u,c]=l.useState(null),[p,d]=l.useState(!1),[m,h]=l.useState(new Set(["footer"])),[g,v]=l.useState("Snapshot"),[f,y]=l.useState(!1),[j,x]=l.useState(null),[w,N]=l.useState(!1),[k,b]=l.useState(""),[C,S]=l.useState(!1),[M,A]=l.useState("idle"),[T,L]=l.useState(null),[P,B]=l.useState([]),[z,R]=l.useState({}),[_,K]=l.useState(null),[E,D]=l.useState(!1),$=e.daemonId||((oe=e.routeId)==null?void 0:oe.split(":")[0])||e.routeId||"",I=e.sessionId||"",G=l.useCallback(async()=>{a(!0),c(null);try{const U=await n($,"get_spec_debug",{targetSessionId:I}),W=U&&typeof U=="object"?U:{},Q=W.result&&typeof W.result=="object"?W.result:W;Q!=null&&Q.success?i(Q):(c((Q==null?void 0:Q.error)||"Failed to load spec debug"),i(null))}catch(U){c((U==null?void 0:U.message)||String(U)),i(null)}finally{a(!1)}},[n,$,I]);l.useEffect(()=>{G()},[G]),l.useEffect(()=>{if(!E)return;const U=setInterval(()=>{G()},1e3);return()=>clearInterval(U)},[E,G]),l.useEffect(()=>{const U=W=>{W.key==="Escape"&&!f&&t()};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[t,f]);const Y=l.useCallback(async U=>{try{const W=await n($,"validate_spec",{content:JSON.stringify(U)}),Q=W&&typeof W=="object"?W:{},V=Q.result&&typeof Q.result=="object"?Q.result:Q;B(V!=null&&V.valid?[]:(V==null?void 0:V.errors)??["validation failed"])}catch(W){B([(W==null?void 0:W.message)||String(W)])}},[n,$]),Z=l.useCallback(async()=>{L(null),A("idle"),R({});try{const U=await n($,"get_spec_source",{targetSessionId:I}),W=U&&typeof U=="object"?U:{},Q=W.result&&typeof W.result=="object"?W.result:W;if(!(Q!=null&&Q.success)||typeof Q.content!="string"){L((Q==null?void 0:Q.error)||"Failed to load spec source");return}b(Q.content);let V=null;try{V=JSON.parse(Q.content)}catch{}V&&V.$schema==="adhdev:cli/spec@4"?(x(V),N(!1),Y(V)):(x(null),N(!0)),S(!1),y(!0)}catch(U){L((U==null?void 0:U.message)||String(U))}},[n,$,I,Y]),q=l.useCallback(U=>{x(U),b(JSON.stringify(U,null,2)),S(!0),A("idle"),Y(U)},[Y]),ne=l.useCallback(async(U,W)=>{R(Q=>({...Q,[U]:"loading"}));try{const Q=await n($,"eval_condition_preview",{targetSessionId:I,condition:W}),V=Q&&typeof Q=="object"?Q:{},fe=V.result&&typeof V.result=="object"?V.result:V;!(fe!=null&&fe.success)||!fe.result?R(ce=>({...ce,[U]:{result:!1,detail:fe==null?void 0:fe.error}})):R(ce=>({...ce,[U]:{result:fe.result.result,detail:fe.result.detail}}))}catch(Q){R(V=>({...V,[U]:{result:!1,detail:Q==null?void 0:Q.message}}))}},[n,$,I]),ue=l.useCallback(async U=>{K("loading");try{const W=await n($,"resolve_section_preview",{targetSessionId:I,sections:U}),Q=W&&typeof W=="object"?W:{},V=Q.result&&typeof Q.result=="object"?Q.result:Q;!(V!=null&&V.success)||!Array.isArray(V.sections)?K({error:(V==null?void 0:V.error)||"resolve failed"}):K({sections:V.sections,screenLineCount:V.screenLineCount??0})}catch(W){K({error:(W==null?void 0:W.message)||String(W)})}},[n,$,I]),ae=l.useCallback(async()=>{var Q,V;const U=(Q=o==null?void 0:o.snapshot)==null?void 0:Q.specPath;if(!U){L("No spec path on this session");return}if(!w&&P.length>0){L("Fix validation errors before saving");return}const W=!w&&j?JSON.stringify(j,null,2):k;A("saving"),L(null);try{const fe=await n($,"write_spec_source",{specPath:U,content:W}),ce=fe&&typeof fe=="object"?fe:{},F=ce.result&&typeof ce.result=="object"?ce.result:ce;if(!(F!=null&&F.success)){A("error"),L(((V=F==null?void 0:F.validationErrors)==null?void 0:V.join(`
44
- `))||(F==null?void 0:F.error)||"Save failed");return}A("saved"),S(!1),setTimeout(()=>{G()},400),setTimeout(()=>A("idle"),1500)}catch(fe){A("error"),L((fe==null?void 0:fe.message)||String(fe))}},[n,$,(Se=o==null?void 0:o.snapshot)==null?void 0:Se.specPath,k,j,w,P,G]),O=o==null?void 0:o.snapshot,se=async()=>{var F,le,je;let U=o;U||(await G(),U=o);const W=U==null?void 0:U.snapshot,Q=[];if(Q.push("# Spec Debug Snapshot"),Q.push(`Generated: ${new Date().toISOString()}`),Q.push(`Session: ${(U==null?void 0:U.sessionId)??""} (${(U==null?void 0:U.providerType)??""})`),Q.push(`Spec: ${(W==null?void 0:W.spec_id)??""} (${(W==null?void 0:W.specPath)??""})`),Q.push(`Provider: ${(W==null?void 0:W.name)??""} (${(W==null?void 0:W.cliType)??""})`),Q.push(`Working dir: ${(W==null?void 0:W.workingDir)??""}`),Q.push(`Spawned: ${W!=null&&W.spawnedAtMs?new Date(W.spawnedAtMs).toISOString():""}`),Q.push(""),Q.push("## Current State"),Q.push(`State: ${((F=W==null?void 0:W.current_state)==null?void 0:F.id)??"none"} (${((le=W==null?void 0:W.current_state)==null?void 0:le.label)??""})`),Q.push(`Status: ${(W==null?void 0:W.status)??""}`),Q.push(`Idle hold pending: ${(W==null?void 0:W.idleHoldPending)??!1}`),Q.push(`Exited: ${(W==null?void 0:W.exited)??!1}`),Q.push(`Last busy: ${W!=null&&W.lastBusyAt?Fn(W.lastBusyAt):""}`),Q.push(`Cursor: ${(W==null?void 0:W.cursorPosition)!=null?`(${W.cursorPosition.row},${W.cursorPosition.col})`:"n/a"}`),(je=W==null?void 0:W.completionIdleDebounce)!=null&&je.active){const de=W.completionIdleDebounce;Q.push(`completion_idle_after: age=${de.ageMs}ms hold=${de.holdMs}ms force=${de.forceAfterMs}ms remaining=${Math.max(0,de.holdMs-de.ageMs)}ms`)}if(Q.push(""),Q.push("## Modal"),W!=null&&W.current_modal){const de=W.current_modal.buttons.map(H=>H.label).join(" / ");Q.push(`${W.current_modal.title??""} [${de}]`)}else Q.push("none");Q.push(""),Q.push("## State History (last 20)");const V=W!=null&&W.stateHistory?[...W.stateHistory].reverse().slice(0,20):[];for(const de of V){const H=de.reason!=null?typeof de.reason=="string"?de.reason:JSON.stringify(de.reason):"",be=de.debounceKind!=null?typeof de.debounceKind=="string"?de.debounceKind:JSON.stringify(de.debounceKind):"",Ne=de.matchedStateId!=null?String(de.matchedStateId):"",Ce=(de.matchedRules??[]).map($e=>typeof $e=="string"?$e:JSON.stringify($e)).join(", ");Q.push(`- ${de.stateId} @ ${new Date(de.at).toISOString()} held ${de.durationMs}ms | reason: ${H} | debounce: ${be} | eval→${Ne} | rules: ${Ce}`)}if(Q.push(""),Q.push("## Sections"),W!=null&&W.sections)for(const[de,H]of Object.entries(W.sections)){const be=H.split(`
45
- `).slice(0,3).join(`
46
- `);Q.push(`${de}: ${be}`)}Q.push(""),Q.push("## Last Assistant Message");const ce=[...(W==null?void 0:W.messages)??(W==null?void 0:W.committedMessages)??[]].reverse().find(de=>de.role==="assistant");Q.push(ce?ce.content.slice(0,400):""),Q.push(""),Q.push("## Screen (first 50 lines)"),Q.push(W!=null&&W.screen?W.screen.split(`
47
- `).slice(0,50).join(`
48
- `):"");try{await navigator.clipboard.writeText(Q.join(`
49
- `)),v("Copied!"),setTimeout(()=>v("Snapshot"),1500)}catch(de){console.error("[SpecDebugPanel] clipboard write failed",de)}},X=U=>{h(W=>{const Q=new Set(W);return Q.has(U)?Q.delete(U):Q.add(U),Q})};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"}),O&&s.jsx("span",{className:"text-[11px] text-text-secondary font-mono bg-surface-secondary px-1.5 py-0.5 rounded truncate",children:O.spec_id})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[(O==null?void 0:O.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?y(!1):Z()},disabled:r,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:()=>{se()},disabled:r,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:()=>{G()},disabled:r,children:r?"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 ${w?"text-text-secondary hover:bg-bg-glass-hover":"bg-accent-primary/20 text-accent-primary"}`,onClick:()=>{if(w)try{const U=JSON.parse(k);x(U),Y(U)}catch{return}N(!1)},disabled:!j&&w,children:"Form"}),s.jsx("button",{type:"button",className:`px-2 py-0.5 ${w?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>{j&&b(JSON.stringify(j,null,2)),N(!0)},children:"JSON"})]}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate flex-1",title:O==null?void 0:O.specPath,children:((O==null?void 0:O.specPath)??"").split("/").slice(-3).join("/")}),C&&s.jsx("span",{className:"text-status-warning text-[10px]",children:"unsaved"}),!w&&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 ${M==="saving"||!w&&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:()=>{ae()},disabled:M==="saving"||!w&&P.length>0,children:M==="saving"?"Saving…":M==="saved"?"Saved ✓ (reloading)":"Save & Apply"})]}),T&&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:T}),!w&&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,W)=>s.jsx("div",{className:"font-mono",children:U},W))}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:w||!j?s.jsx("textarea",{value:k,onChange:U=>{b(U.target.value),S(!0),A("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(F0,{model:j,onChange:q,onPreview:ne,preview:z,onTestSections:ue,sectionPreview:_})}),s.jsx("div",{className:"text-[10px] text-text-muted shrink-0",children:w?"Raw JSON — validated on save.":'Build the FSM; from/to are constrained to existing states. "test" evaluates a condition against the live screen. Save hot-reloads the session.'})]}),!f&&s.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))] space-y-3 text-[12px]",children:[u&&s.jsx("div",{className:"text-status-error bg-status-error/20 border border-status-error/40 rounded p-2",children:u}),r&&!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",")."]}),O&&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:[O.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:[O.name," ",s.jsxs("span",{className:"text-text-muted",children:["(",O.cliType,")"]})]})]}),O.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:O.workingDir,children:O.workingDir})]}),O.spawnedAtMs?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"Spawned"}),s.jsx("span",{className:"text-text-secondary",children:Fn(O.spawnedAtMs)})]}):null,O.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:O.providerSessionId,children:O.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 ${O.current_state?ro(O.current_state.id):"text-text-muted"}`,children:O.current_state?O.current_state.id:"none"}),((ye=O.current_state)==null?void 0:ye.label)&&O.current_state.label!==O.current_state.id&&s.jsx("span",{className:"text-text-secondary text-[11px]",children:O.current_state.label}),O.status&&O.status!==((ke=O.current_state)==null?void 0:ke.id)&&s.jsxs("span",{className:"text-text-muted text-[11px]",children:["engine: ",s.jsx("span",{className:`font-mono ${ro(O.status)} px-1 py-0.5 rounded text-[10px]`,children:O.status})]}),O.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"}),O.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"}),O.cursorPosition!=null&&s.jsxs("span",{className:"text-text-muted text-[11px] font-mono",children:["cursor: ",s.jsxs("span",{className:"text-text-secondary",children:[O.cursorPosition.row,",",O.cursorPosition.col]})]}),O.lastBusyAt>0&&s.jsxs("span",{className:"text-text-muted text-[11px] ml-auto",children:["last busy: ",s.jsx("span",{className:"text-text-secondary",children:Fn(O.lastBusyAt)})]})]}),((me=O.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:[O.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:[O.completionIdleDebounce.holdMs,"ms"]})]}),s.jsxs("span",{className:"text-text-secondary",children:["force: ",s.jsxs("span",{className:"text-text-secondary",children:[O.completionIdleDebounce.forceAfterMs,"ms"]})]}),s.jsx("span",{className:"text-text-muted ml-auto",children:O.completionIdleDebounce.ageMs<O.completionIdleDebounce.holdMs?s.jsxs("span",{className:"text-status-warning",children:["hold remaining: ",O.completionIdleDebounce.holdMs-O.completionIdleDebounce.ageMs,"ms"]}):O.completionIdleDebounce.ageMs<O.completionIdleDebounce.forceAfterMs?s.jsxs("span",{className:"text-orange-300",children:["force in: ",O.completionIdleDebounce.forceAfterMs-O.completionIdleDebounce.ageMs,"ms"]}):s.jsx("span",{className:"text-status-error",children:"overdue"})})]}),O.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:O.current_modal.title||""}),O.current_modal.buttons.length>0&&s.jsxs("span",{className:"text-text-secondary ml-2",children:["[",O.current_modal.buttons.map(U=>U.label).join(" / "),"]"]})]}),O.fsm&&s.jsxs(s.Fragment,{children:[s.jsx(Ar,{}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsxs(Mr,{children:["FSM — outgoing from ",s.jsx("span",{className:"text-accent-primary font-mono normal-case",children:O.fsm.currentState})," (held ",yc(O.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:E,onChange:U=>D(U.target.checked),className:"accent-[var(--accent-primary)]"}),"live"]})]}),s.jsxs("div",{className:"space-y-1",children:[O.fsm.transitions.length===0&&s.jsx("div",{className:"text-text-muted text-[11px] italic px-1",children:"no outgoing transitions (terminal state)"}),O.fsm.transitions.map((U,W)=>s.jsx(W0,{t:U},W))]})]})]}),s.jsx(Ar,{}),O.sections&&Object.keys(O.sections).length>0&&s.jsxs("div",{children:[s.jsx(Mr,{children:"Sections"}),s.jsx("div",{className:"space-y-1",children:Object.entries(O.sections).map(([U,W])=>{var ce;const Q=m.has(U),V=W.split(`
50
- `),fe=((ce=V[0])==null?void 0:ce.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:()=>X(U),children:[s.jsx("span",{className:"text-[10px] text-text-muted w-3",children:Q?"▾":"▸"}),s.jsx("span",{className:"font-mono text-accent-primary w-20 shrink-0 text-[11px]",children:U}),!Q&&s.jsx("span",{className:"text-text-secondary truncate font-mono text-[11px]",children:fe}),s.jsxs("span",{className:"ml-auto text-text-muted text-[10px] shrink-0",children:[V.length,"L"]})]}),Q&&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:W||"(empty)"})]},U)})})]}),s.jsx(Ar,{}),O.stateHistory&&O.stateHistory.length>0&&s.jsxs("div",{children:[s.jsxs(Mr,{children:["State History (",O.stateHistory.length,")"]}),s.jsx("div",{className:"space-y-px",children:[...O.stateHistory].reverse().slice(0,20).map((U,W)=>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 ${ro(U.stateId)}`,children:U.stateId}),s.jsx("span",{className:"text-text-secondary text-[11px] shrink-0 tabular-nums",children:Fn(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 ${H0[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((Q,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 Q=="string"?Q:JSON.stringify(Q)},V)),U.matchedRules.length>3&&s.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",U.matchedRules.length-3," more"]})]})]},W))})]}),s.jsx(Ar,{}),(()=>{const U=O.messages??O.committedMessages??[];if(U.length===0)return null;const W=U.filter(fe=>fe.role==="user").length,Q=U.filter(fe=>fe.role==="assistant").length,V=[...U].reverse().find(fe=>fe.role==="assistant");return s.jsxs("div",{children:[s.jsxs(Mr,{children:["Transcript (",U.length," — ",W,"u / ",Q,"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?Fn(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?"…":""]})]})]})})(),O.specPath&&s.jsx("div",{className:"text-[10px] text-text-muted font-mono truncate border-t border-border-default pt-2 mt-1",title:O.specPath,children:O.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:()=>d(U=>!U),children:[s.jsx("span",{className:"text-text-muted",children:p?"▾":"▸"}),s.jsxs("span",{children:["Raw screen (",O.screen?O.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:O.screen||"(empty)"})]})]})]})]})})}function K0({activeConv:e,clearToken:t=0,terminalRef:n,handleSendChat:r,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:i=!0,isInputActive:u=!0}){var et;const{t:c}=Xe("common");bs();const{sendPtyInput:p}=yt(),[d,m]=l.useState(!1),h=l.useRef(!1);h.current=d;const[g,v]=l.useState("Runtime terminal unavailable"),[f,y]=l.useState(!1),[j,x]=l.useState(null),[w,N]=l.useState(!1),[k,b]=l.useState(!1),[C,S]=l.useState(1),[M,A]=l.useState(!1),[T,L]=l.useState(!1),[P,B]=l.useState(!1),[z,R]=l.useState(!1),[_,K]=l.useState(!1),[E,D]=l.useState({width:0,height:0}),[$,I]=l.useState({width:0,height:0}),[G,Y]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[Z,q]=l.useState(null),ne=l.useRef(null),ue=l.useRef(null),ae=l.useRef(!1),O=l.useRef(!1),se=l.useRef(i),X=l.useRef(0),oe=l.useRef(!1),Se=l.useRef(""),ye=l.useRef(null),ke=l.useRef(!1),me=l.useRef(!1),U=l.useRef(null),W=l.useRef(null),Q=l.useRef(null),V=32*1024,fe=()=>{var ee,xe,we,Ge;return((xe=(ee=ne.current)==null?void 0:ee.ownerDocument)==null?void 0:xe.defaultView)||((Ge=(we=ue.current)==null?void 0:we.ownerDocument)==null?void 0:Ge.defaultView)||window},ce=ee=>{const xe=fe();return{ownerWindow:xe,frameId:xe.requestAnimationFrame(ee)}},F=()=>{const ee=U.current;if(ee){try{ee.ownerWindow.cancelAnimationFrame(ee.frameId)}catch{}U.current=null}},le=()=>{const ee=W.current;if(ee){try{ee.ownerWindow.clearTimeout(ee.timeoutId)}catch{}W.current=null}},je=()=>{const ee=Q.current;if(ee){try{ee.ownerWindow.clearTimeout(ee.timeoutId)}catch{}Q.current=null}},de=()=>{i&&U.current===null&&(U.current=ce(()=>{J()}))},H=e.tabKey,be=e.sessionId||"",Ne=e.daemonId||((et=e.routeId)==null?void 0:et.split(":")[0])||e.routeId||"",Ce=Wi(e),$e=d?o||Ce:g,Qe=S0,dt=N0,it=.05,he=()=>{const ee=$.width,xe=$.height;if(!Number.isFinite(E.width)||E.width<=0||!Number.isFinite(E.height)||E.height<=0||!Number.isFinite(ee)||ee<=0||!Number.isFinite(xe)||xe<=0)return 1;const we=E.width/ee,Ge=E.height/xe;return Number(Math.min(dt,Math.max(Qe,Math.min(we,Ge))).toFixed(2))},Ee=he(),Fe=ae.current&&C>Ee,Ie=Number.isFinite($.width)&&$.width>0?Math.max(E.width,Math.round($.width*C)):E.width,ve=Number.isFinite($.height)&&$.height>0?Math.max(E.height,Math.round($.height*C)):E.height,Oe=()=>{ce(()=>{const ee=ue.current;ee&&(ee.scrollLeft=0,ee.scrollTop=ee.scrollHeight-ee.clientHeight)})},ut=()=>{var ee,xe;X.current=0,oe.current=!1,Se.current="",ye.current=null,ke.current=!1,me.current=!1,ae.current||(O.current=!1,S(1)),U.current!==null&&F(),m(!1),v("Runtime terminal unavailable"),je(),le(),x(null),q(null),A(!1),y(!1),N(!1),b(!1),(xe=(ee=n.current)==null?void 0:ee.reset)==null||xe.call(ee)},ot=()=>{var ee,xe;X.current=0,oe.current=!1,Se.current="",ye.current=null,ke.current=!1,me.current=!1,U.current!==null&&F(),m(!0),v(""),je(),le(),x(null),q(null),A(!1),y(!1),N(!1),b(!1),(xe=(ee=n.current)==null?void 0:ee.reset)==null||xe.call(ee)},pt=()=>{me.current&&(me.current=!1,ce(()=>{var ee,xe;(xe=(ee=n.current)==null?void 0:ee.scrollToTop)==null||xe.call(ee)}))},J=()=>{if(U.current=null,!i)return;const ee=Se.current;if(!ee)return;const xe=ee.slice(0,V);Se.current=ee.slice(xe.length);const we=n.current;if(!we){Se.current=xe+Se.current,de();return}we.write(xe,()=>{if(Se.current.length>0){de();return}pt()})},te=ee=>{ee&&(Se.current+=ee,de())},ie=(ee,xe=0,we,Ge,He={})=>{var ze,qe,At,Ot;const tt=!!He.force;!tt&&xe>0&&X.current>=xe||!tt&&xe===0&&oe.current||(X.current=xe,xe>0&&N(!0),m(!0),v(""),typeof we=="number"&&typeof Ge=="number"&&we>0&&Ge>0&&((qe=(ze=n.current)==null?void 0:ze.resize)==null||qe.call(ze,we,Ge)),Se.current="",(Ot=(At=n.current)==null?void 0:At.reset)==null||Ot.call(At),ee?te(ee):pt())};l.useEffect(()=>{ut()},[be]),l.useEffect(()=>{var xe;if(!be)return;const ee=((xe=kt.onRuntimeEvent)==null?void 0:xe.call(kt,be,we=>{if(!(!we||we.sessionId!==be)){if(we.type==="runtime_snapshot"){if(!i){ye.current={text:we.text||"",seq:we.seq||0,cols:we.cols,rows:we.rows,force:!!we.force};return}ie(we.text||"",we.seq||0,we.cols,we.rows,{force:!!we.force});return}if(we.type==="session_output"){oe.current=!0,typeof we.seq=="number"&&(X.current=Math.max(X.current,we.seq),we.seq>0&&N(!0)),h.current||m(!0),h.current||v(""),typeof we.data=="string"&&te(we.data);return}if(we.type==="session_cleared"){if(!i){ke.current=!0,Se.current="",ye.current=null;return}ot();return}if(we.type==="session_io_error"){const Ge=typeof we.error=="string"&&we.error?we.error:typeof we.reason=="string"&&we.reason?we.reason:"unknown error";m(!1),v(`Runtime input failed: ${Ge}`);return}}},Ne))||(()=>{});return()=>{ee()}},[Ne,be,n,i]);const pe=async(ee={})=>{var xe;if(!Ne||!be)return{success:!1,error:"daemonId and sessionId are required"};ee.preserveStatus||v(ee.loadingMessage||"Loading runtime terminal...");try{const we=await((xe=kt.requestRuntimeSnapshot)==null?void 0:xe.call(kt,Ne,be,{sinceSeq:ee.sinceSeq,force:ee.force}));return we&&we.success===!1?(ee.preserveStatus||(m(!1),v(`Runtime terminal unavailable: ${we.error}`)),we):we||{success:!0}}catch(we){const Ge=(we==null?void 0:we.message)||String(we);return ee.preserveStatus||(m(!1),v(`Runtime terminal unavailable: ${Ge}`)),{success:!1,error:Ge}}},ge=async ee=>{var tt,ze;const xe=((tt=ne.current)==null?void 0:tt.ownerDocument)||document,we=xe.defaultView||window,Ge=(ze=we.navigator)==null?void 0:ze.clipboard;if(Ge!=null&&Ge.writeText&&we.isSecureContext)try{return await Ge.writeText(ee),!0}catch{}let He=null;try{return He=xe.createElement("textarea"),He.value=ee,He.setAttribute("readonly","true"),He.style.position="fixed",He.style.left="-9999px",He.style.top="0",xe.body.appendChild(He),He.focus(),He.select(),xe.execCommand("copy")}catch{return!1}finally{He==null||He.remove()}},Ae=ee=>{le(),q(ee);const xe=fe();W.current={ownerWindow:xe,timeoutId:xe.setTimeout(()=>{W.current=null,q(we=>we===ee?null:we)},2200)}},De=ee=>{je(),x(ee);const xe=fe();Q.current={ownerWindow:xe,timeoutId:xe.setTimeout(()=>{Q.current=null,x(we=>we===ee?null:we)},2200)}},Me=async()=>{var He,tt,ze,qe;const ee=((tt=(He=n.current)==null?void 0:He.getSelection)==null?void 0:tt.call(He))||"",xe=((qe=(ze=n.current)==null?void 0:ze.getVisibleText)==null?void 0:qe.call(ze))||"",we=ee.trimEnd()||xe.trimEnd();if(!we){Ae("Nothing to copy");return}if(!await ge(we)){Ae("Copy failed");return}Ae(ee.trimEnd()?"Copied selection":"Copied visible terminal")},Be=ee=>{if(!d||!i)return;((p==null?void 0:p(Ne,be,ee))??!1)||Ae("Terminal input failed")},We=ee=>{Be(M0({ctrl:T,alt:P,shift:z},ee)),L(!1),B(!1),R(!1)},Ze=async()=>{if(f)return;y(!0),x("Loading older terminal output..."),me.current=!0;const ee=await pe({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:d});if(y(!1),(ee==null?void 0:ee.success)===!1){me.current=!1,x(`Older terminal output unavailable: ${ee.error}`);return}b(!0),De("Older terminal output loaded"),ce(()=>{var xe;(xe=n.current)==null||xe.bumpResize()})};l.useEffect(()=>{var xe,we;if(!be)return;Ne&&((xe=kt.getState)==null?void 0:xe.call(kt,Ne))==="connected"&&pe();const ee=(we=kt.onStateChange)==null?void 0:we.call(kt,(Ge,He)=>{Ge!==Ne||He!=="connected"||pe()});return()=>{ee==null||ee()}},[Ne,be,n]),l.useEffect(()=>{t&&ut()},[t,H,n]),l.useEffect(()=>{var Ge,He;const ee=ne.current,xe=(He=(Ge=ee==null?void 0:ee.ownerDocument)==null?void 0:Ge.defaultView)==null?void 0:He.ResizeObserver;if(!ee||!xe)return;const we=new xe(tt=>{const ze=tt[0];if(!ze)return;const{width:qe,height:At}=ze.contentRect;D(Ot=>{const ss=Math.round(qe),Te=Math.round(At);return Ot.width===ss&&Ot.height===Te?Ot:{width:ss,height:Te}})});return we.observe(ee),()=>we.disconnect()},[]),l.useEffect(()=>{if(ae.current)return;const ee=he();!Number.isFinite(ee)||ee<=0||S(xe=>O.current?ee<xe-it?ee:xe:(O.current=!0,ee))},[$.height,$.width,E.height,E.width]),l.useEffect(()=>{Fe&&Oe()},[Fe,ve,Ie]),l.useEffect(()=>{var we;const ee=se.current;if(se.current=i,!i)return;ee||b(!1),ke.current&&(ke.current=!1,ot());const xe=ye.current;xe&&(ye.current=null,ie(xe.text,xe.seq,xe.cols,xe.rows,{force:!!xe.force})),Ne&&be&&((we=kt.getState)==null?void 0:we.call(kt,Ne))==="connected"&&pe(),Se.current&&U.current===null&&de(),ce(()=>{var Ge;(Ge=n.current)==null||Ge.bumpResize()})},[Ne,i,be]),l.useEffect(()=>()=>{U.current!==null&&F(),le(),je()},[]),l.useEffect(()=>{const ee=Ge=>{var tt;const He=Ge.detail;He!=null&&He.sessionId&&He.sessionId!==be||d&&((tt=n.current)==null||tt.bumpResize())},xe=fe(),we=xe===window?[window]:[window,xe];for(const Ge of we)Ge.addEventListener("adhdev:fit-cli-terminal",ee);return()=>{for(const Ge of we)Ge.removeEventListener("adhdev:fit-cli-terminal",ee)}},[d,be,n]);const Ue=d&&w&&!k&&(G.atTop||!G.canScroll)||f||!!j;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:ne,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[Ue&&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:()=>{Ze()},disabled:!be||f,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:c(f?"terminal.loadingOlder":"terminal.loadOlderOutput")}),j&&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:j})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[Z&&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:Z}),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:()=>K(ee=>!ee),title:"Spec debug — inspect current state, sections, and transition history",children:c("terminal.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:()=>{Me()},disabled:!d,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:c("terminal.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:()=>A(ee=>!ee),disabled:!d,"aria-label":c(M?"terminal.closeControlKeys":"terminal.openControlKeys"),"aria-expanded":M,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),M&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":c("terminal.openControlKeys"),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:()=>A(!1),"aria-label":c("terminal.closeControlKeys"),children:"×"})]}),s.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",T,L],["Alt",P,B],["Shift",z,R]].map(([ee,xe,we])=>s.jsx("button",{type:"button","aria-pressed":xe,className:`h-9 rounded-lg border text-[12px] font-semibold transition-colors ${xe?"border-sky-400/50 bg-sky-400/25 text-white":"border-white/10 bg-white/[0.06] hover:bg-white/[0.12]"}`,onClick:()=>we(Ge=>!Ge),children:ee},ee))}),s.jsx("div",{className:"grid grid-cols-6 gap-1",children:"abcdefghijklmnopqrstuvwxyz0123456789".split("").map(ee=>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:()=>We(ee),children:ee},ee))}),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:()=>We("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:()=>We("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:()=>We("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:()=>We("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:()=>We("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:()=>We("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:()=>We("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:()=>Be(""),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:()=>We("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:()=>We("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:()=>{ae.current=!0,S(ee=>{const xe=Math.max(Ee,Number((ee-.1).toFixed(2)));return xe>Ee&&Oe(),xe})},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:()=>{ae.current=!0,S(ee=>{const xe=Math.min(dt,Number((ee+.1).toFixed(2)));return xe>Ee&&Oe(),xe})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:ue,className:Fe?"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:Ie>0?`${Ie}px`:"100%",height:ve>0?`${ve}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:$.width>0?`${$.width}px`:"100%",height:$.height>0?`${$.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:C},children:s.jsx(ou,{ref:n,readOnly:!d||!i,sizingMode:"measured",onViewportMetrics:I,onScrollMetrics:Y,onInput:ee=>{!d||(p==null||p(Ne,be,ee))}})})})}),!d&&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:g})]}),s.jsx(Cu,{contextKey:e.tabKey,panelLabel:gt(e),isSending:a,isBusy:!!Ce,statusMessage:$e,inlineStatusMessage:$e,onSend:async ee=>Ce?!1:r(ee),isActive:u&&i,showControlsToggle:!1,animateVisibility:!1}),_&&s.jsx(U0,{activeConv:e,onClose:()=>K(!1)})]})}const G0=5e3,z0=12e3;function V0(e){return e==="disconnected"||e==="reconnecting"}function q0({wsStatus:e,showReconnected:t,loginUrl:n,onReconnect:r,reconnectDelayMs:a=G0,reconnectActionDelayMs:o=z0}){const{t:i}=Xe(),u=V0(e),[c,p]=l.useState(()=>!u||a<=0),[d,m]=l.useState(()=>!u||o<=0),h=l.useRef(!1);l.useEffect(()=>{if(!u){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,u]),l.useEffect(()=>{if(!u){m(!1);return}if(o<=0){m(!0);return}m(!1);const b=setTimeout(()=>{m(!0)},o);return()=>clearTimeout(b)},[o,u]);const g=u?c:e==="offline"||e==="auth_failed",v=!!(r&&e!=="auth_failed"&&(!u||d)),f=l.useMemo(()=>!t||e!=="connected"?!1:a<=0||h.current,[a,t,e]),y=e==="auth_failed"?"red":e==="offline"?"orange":"accent",j={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)"},w={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},N="fixed left-1/2 top-4 z-[var(--z-toast)] flex items-center justify-center pointer-events-none",k={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[g&&s.jsx("div",{className:N,style:k,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:j[y],border:x[y],color:w[y]},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"&&(n?s.jsxs(s.Fragment,{children:[i("connection.sessionExpired")," ",s.jsx("a",{href:n,className:"text-inherit underline",children:i("connection.logInAgain")})]}):i("connection.connectionFailed"))]}),v&&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:()=>r==null?void 0:r(),disabled:e==="offline",children:i("connection.reconnectNow")})]})}),f&&s.jsx("div",{className:N,style:k,children:s.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),i("connection.connected")]})})]})}function up({mode:e,onChange:t,compact:n=!1}){const{t:r}=Xe("common"),a=n?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:r(e==="chat"?"cliView.switchToTerminal":"cliView.switchToChat"),children:e==="chat"?s.jsx(Ii,{size:a}):s.jsx(Zs,{size:a})})}const Fs="New session",Y0="A connected machine is ready. Start a new session with any installed provider — CLI, ACP, or IDE.";function J0(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 X0(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:n=!1}){const r=J0(e),a=X0(e);if(!r||!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(" · ")||r,"data-git-tone":a,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:r})]})}function Z0({wsStatus:e,isConnected:t,daemonCount:n,p2pStates:r={}}){if(e!=="connected")return{tone:"disconnected",titleKey:"connection.disconnected",subtitleKey:null};const a=Object.values(r),o=a.filter(u=>u==="connected").length,i=a.filter(u=>u==="connecting"||u==="new"||u==="checking").length;return n>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:n,onMarkRead:r,onMarkUnread:a,onDelete:o}){const{t:i}=Xe(),u=Sa(e.updatedAt),c=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${c?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:n,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"),u].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[c?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),r()},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 ew({activeConv:e,wsStatus:t,isConnected:n,conversations:r,onOpenHistory:a,onOpenRemote:o,onStopCli:i,activeCliViewMode:u,onSetCliViewMode:c,onHideConversation:p,hiddenConversations:d=[],onShowConversation:m,onShowAllHidden:h,onResetPanelsToMain:g,inboxOpen:v,onInboxOpenChange:f,hiddenOpen:y,onHiddenOpenChange:j,onOpenNewSession:x,onOpenDashboardGuide:w,guideNudgeVisible:N=!1,actionShortcuts:k,notifications:b,notificationUnreadCount:C,onOpenNotification:S,onMarkNotificationRead:M,onMarkNotificationUnread:A,onDeleteNotification:T,onOpenGitDialog:L,onOpenMeshGraph:P}){var Q;const{t:B}=Xe(),{ides:z,p2pStates:R={}}=bs(),_=!!e&&ct(e)&&!lt(e),K=!!e&&lt(e),E=!!(e!=null&&e.daemonId)&&!!((Q=e==null?void 0:e.coordinator)!=null&&Q.meshId),D=u||(e?Ru(e)?"terminal":"chat":null),[$,I]=l.useState(!1),[G,Y]=l.useState(!1),Z=l.useRef(null),q=l.useRef(null),ne=l.useRef(null),ue=z.filter(V=>V.type==="adhdev-daemon"),ae=Z0({wsStatus:t,isConnected:n,daemonCount:ue.length,p2pStates:R}),O=B(ae.titleKey),se=ae.subtitleKey?B(ae.subtitleKey):null,X=ae.tone==="connected"?"#22c55e":ae.tone==="limited"?"#eab308":"#ef4444",oe=ae.tone==="connected"?"0 0 4px #22c55e80":ae.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",Se=l.useMemo(()=>b.filter(V=>!V.readAt),[b]),ye=l.useMemo(()=>b.filter(V=>!!V.readAt),[b]),ke=l.useMemo(()=>Se.slice(0,9),[Se]),me=C;l.useEffect(()=>{if(!v)return;const V=fe=>{var ce;(ce=q.current)!=null&&ce.contains(fe.target)||f(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[v,f]),l.useEffect(()=>{if(!y)return;const V=fe=>{var ce;(ce=ne.current)!=null&&ce.contains(fe.target)||j(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[y,j]),l.useEffect(()=>{if(!y&&!v)return;const V=fe=>{if(!fe.altKey)return;const ce=fe.code.match(/^Digit([1-9])$/);if(!ce)return;const F=Number(ce[1])-1,le=y?d[F]:void 0,je=v?ke[F]:void 0;if(!(!le&&!je)){if(fe.preventDefault(),fe.stopPropagation(),le){m==null||m(le),j(!1);return}je&&(S(je),f(!1))}};return window.addEventListener("keydown",V,!0),()=>window.removeEventListener("keydown",V,!0)},[d,y,v,ke,j,f,S,m]),l.useEffect(()=>{const V=d.length;if(Z.current===null){Z.current=V;return}V>Z.current&&Y(!0),Z.current=V},[d.length]);const U=()=>Y(!1),W=V=>{if(!V)return;const fe=r.find(ce=>ce.tabKey===V);fe&&(p==null||p(fe))};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:B("dashboard.header.title")}),s.jsx("span",{className:"header-title-mobile",children:e?gt(e):B("dashboard.header.title")}),s.jsx("span",{title:O,"aria-label":O,className:"header-title-status-dot",style:{background:X,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:X,boxShadow:oe}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[se&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",se]}),x&&s.jsx("button",{type:"button",onClick:x,className:"btn btn-secondary btn-sm ml-2",title:`${Fs}${k!=null&&k.openNewSession?` (${k.openNewSession})`:""}`,"aria-label":Fs,children:s.jsx(Ti,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[w&&s.jsxs("button",{type:"button",onClick:w,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:B("dashboard.header.guide"),"aria-label":B("dashboard.header.guideOpen"),children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),N&&s.jsx("span",{children:B("dashboard.header.guideShort")})]}),e&&(_||K||!lt(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:vn(e)||gt(e),children:gt(e)}),L&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:B("dashboard.header.openGitStatus"),onClick:()=>L(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"}),E&&P&&s.jsxs("button",{type:"button",onClick:()=>P(e),className:"btn btn-secondary btn-sm dashboard-header-mesh-button",title:B("dashboard.header.openMeshGraph"),children:[s.jsx(es,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:B("dashboard.header.meshGraph")})]}),(_||K)&&i&&s.jsxs(s.Fragment,{children:[_&&c&&D&&s.jsx(up,{mode:D,onChange:c,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:B(K?"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(Mt,{size:14})})]}),!lt(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:B("dashboard.header.chatHistory"),children:s.jsx(Mi,{size:14})}),!_&&!lt(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:B("dashboard.header.remoteControl"),children:s.jsx(us,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:q,children:[s.jsxs("div",{className:`dashboard-header-hidden${$?" is-drop-target":""}${G?" hidden-spawn-flash":""}`,onAnimationEnd:U,ref:ne,onDragEnter:V=>{V.dataTransfer.types.includes("text/tab-key")&&(V.preventDefault(),I(!0))},onDragOver:V=>{V.dataTransfer.types.includes("text/tab-key")&&(V.preventDefault(),V.dataTransfer.dropEffect="move",I(!0))},onDragLeave:V=>{V.currentTarget.contains(V.relatedTarget)||I(!1)},onDrop:V=>{const fe=V.dataTransfer.getData("text/tab-key");V.preventDefault(),I(!1),W(fe)},children:[s.jsxs("button",{type:"button",onClick:()=>j(!y),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`${B("dashboard.hidden.title")}${k!=null&&k.toggleHiddenTabs?` (${k.toggleHiddenTabs})`:""}. ${B("dashboard.hidden.dragHint")}`,children:[s.jsx(Ai,{size:16}),d.length>0&&s.jsx("span",{className:`dashboard-header-hidden-badge${G?" hidden-badge-pop":""}`,children:d.length})]}),y&&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:B("dashboard.hidden.title")}),s.jsx(vc,{value:k==null?void 0:k.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[g&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:g,children:B("dashboard.hidden.resetPanels")}),d.length>0&&h&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{h(),j(!1)},children:B("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:B("dashboard.hidden.hideCurrentTab")}),s.jsx(vc,{value:k==null?void 0:k.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:gt(e)})]}),d.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:d.map(V=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{m==null||m(V),j(!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":B("dashboard.header.generating")}),gt(V)]}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(V)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(V)+1]}):null,vn(V)]})]},V.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:B("dashboard.hidden.empty")})]})]}),s.jsxs("button",{type:"button",onClick:()=>f(!v),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:B("dashboard.header.activityInbox"),children:[s.jsx(Cn,{size:16}),me>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:me})]}),v&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[Se.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:B("dashboard.inbox.unread")}),Se.map(V=>s.jsx(wc,{notification:V,shortcutIndex:ke.indexOf(V)>=0?ke.indexOf(V)+1:void 0,onOpen:()=>S(V),onMarkRead:()=>M(V.id),onMarkUnread:()=>A(V.id),onDelete:()=>T(V.id)},V.id))]}),ye.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:B("dashboard.inbox.read")}),ye.map(V=>s.jsx(wc,{notification:V,onOpen:()=>S(V),onMarkRead:()=>M(V.id),onMarkUnread:()=>A(V.id),onDelete:()=>T(V.id)},V.id))]}),b.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:B("dashboard.inbox.empty")})]})]})]})]})}function Bt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function tw(e,t){return String(e||"")!==String(t||"")}function sw(e,t={}){const n=String(t.textQuery||"").trim().toLowerCase(),r=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),o=!!t.resumableOnly;return!n&&!r&&!a&&!o?e:e.filter(i=>!(o&&!i.canResume||n&&![i.title,i.preview].map(c=>String(c||"").toLowerCase()).join(`
52
- `).includes(n)||r&&!String(i.workspace||"").toLowerCase().includes(r)||a&&!vu(i.summaryMetadata).map(c=>c.toLowerCase()).join(`
53
- `).includes(a)))}function nw(e,t="recent"){const n=e.slice();return n.sort((r,a)=>{if(t==="oldest")return(Number(r.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="messages"){const o=(Number(a.messageCount)||0)-(Number(r.messageCount)||0);if(o!==0)return o}return(Number(a.lastMessageAt)||0)-(Number(r.lastMessageAt)||0)}),n}function pp(e,t={}){return nw(sw(e,t),t.sortMode||"recent")}function ai(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function hp(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function rw(e){return e?e("launch.startFresh"):"Start fresh"}function aw(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function ow(e){return e?e("launch.openSavedHistory"):"Open saved history"}function iw(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function zi(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function lw(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function cw(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function dw(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function da(e,t,n){if(typeof e=="function"){const o=t,i=n;return o==="start-fresh"?e("launch.startFreshWith",{label:i}):e("launch.restart",{label:i})}const r=e,a=t;return r==="start-fresh"?`Start fresh with ${a}?`:`Restart ${a}?`}function ua(e,t){if(typeof e=="function"){const r=t;return e(r==="start-fresh"?"launch.startFreshReview":r==="restart-ide"?"launch.restartIdeReview":"launch.restartStoppedReview")}const n=e;return n==="start-fresh"?"Review the provider and target folder before starting fresh.":n==="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,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function ha(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function mp(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function fp(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function uw(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 xp({activeConv:e,ides:t,isCreatingChat:n,isRefreshingHistory:r,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:u,missingWorkspaceResumePath:c,onSavedHistoryFiltersChange:p,onClose:d,onNewChat:m,onSwitchSession:h,onRefreshHistory:g,onResumeSavedSession:v}){var L;const{t:f}=Xe("common"),y=t.find(P=>P.id===e.routeId),j=(y==null?void 0:y.chats)||[],x=(L=y==null?void 0:y.activeChat)==null?void 0:L.id,w=ct(e)&&!lt(e),[N,k]=l.useState(()=>Bt()),b=u||N,C=String(c||"").trim(),S=P=>{if(p){p(P);return}k(P)},M=l.useMemo(()=>a.map(P=>{const B=String(P.workspace||"").trim();return P.canResume||B||!C?P:{...P,workspace:C,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[C,a]),A=l.useMemo(()=>pp(M,{textQuery:b.textQuery,workspaceQuery:b.workspaceQuery,modelQuery:b.modelQuery,resumableOnly:b.resumableOnly,sortMode:b.sortMode}),[M,b.modelQuery,b.resumableOnly,b.sortMode,b.textQuery,b.workspaceQuery]),T=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:d,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:w?iw(f):f("historyModal.chatHistory")}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:D0(e)}),w&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:zi(f)})]}),s.jsx("button",{onClick:d,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(Mt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!w&&s.jsx("button",{onClick:m,disabled:n,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:f(n?"historyModal.creating":"historyModal.startNewChat")}),w?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:b.textQuery,onChange:P=>S({...b,textQuery:P.target.value}),placeholder:f("historyModal.searchPlaceholder"),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:b.workspaceQuery,onChange:P=>S({...b,workspaceQuery:P.target.value}),placeholder:f("historyModal.filterWorkspace"),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:b.modelQuery,onChange:P=>S({...b,modelQuery:P.target.value}),placeholder:f("historyModal.filterModel"),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:b.sortMode,onChange:P=>S({...b,sortMode:P.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:f("historyModal.sortRecent")}),s.jsx("option",{value:"oldest",children:f("historyModal.sortOldest")}),s.jsx("option",{value:"messages",children:f("historyModal.sortMessages")})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:b.resumableOnly,onChange:P=>S({...b,resumableOnly:P.target.checked})}),f("historyModal.resumeReadyOnly")]})]}),A.map(P=>{const B=e.providerSessionId===P.providerSessionId,z=B||!P.canResume||!!i,R=P.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{z||!v||v(P)},disabled:z,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${B?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${z?"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 ${B?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:P.title||f("historyModal.untitledSession")}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:P.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:uw(P.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:P.preview||f("historyModal.noSavedPreview")}),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:[P.workspace||f("historyModal.workspaceUnknown"),R?f("historyModal.selectedWorkspaceSuffix"):"",Js(P.summaryMetadata)?` · ${Js(P.summaryMetadata)}`:"",P.messageCount>0?` · ${f("historyModal.msgCount",{count:P.messageCount})}`:""]}),s.jsx("div",{className:"shrink-0",children:B?f("historyModal.statusActive"):P.canResume?R?f("historyModal.statusResumeSelectedWorkspace"):i===P.providerSessionId?f("historyModal.statusResuming"):f("historyModal.statusResume"):f("historyModal.statusMissingWorkspace")})]})]},P.id)})]}):j.map(P=>s.jsxs("div",{onClick:()=>{h(e.routeId,P.id),d()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${x===P.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 ${x===P.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:P.title||f("historyModal.untitledSession")}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[P.id.substring(0,12),"..."]}),x===P.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:f("historyModal.statusActive")})]})]},P.id)),(w&&!o&&A.length===0||!w&&j.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:w?a.length>0?f("historyModal.noMatchingHistory"):lw(f):f("historyModal.noRecentChats")})]}),w&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:dw(f)})})]}),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:r||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:r||o?f("historyModal.refreshing"):s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ja,{size:13})," ",w?cw(f):f("historyModal.refreshHistory")]})})})]})]});return typeof document>"u"?T:fn.createPortal(T,document.body)}const kc={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 bp({toasts:e,onDismiss:t,onClickToast:n}){const{t:r}=Xe();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=kc[a.type]||kc.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||n&&n(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":r("toast.dismiss"),children:s.jsx(Mt,{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:r(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,u)=>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:c=>{c.stopPropagation(),i.onClick(),t(a.id)},children:i.label},u))})]})]},a.id)})})}const pw=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function hw(e){const t=e.workspace||"";if(!t)return"";const n=t.split(/[/\\]/).filter(Boolean);return n.length>0?n[n.length-1]:t}function mw(e,t){return gp(e)||t}function gp(e){var a,o,i;const t=(o=(a=e.summaryMetadata)==null?void 0:a.items)==null?void 0:o.find(u=>(u==null?void 0:u.id)==="model"),n=((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim();if(n)return n;const r=(i=e.controlValues)==null?void 0:i.model;return typeof r=="string"&&r.trim()?r.trim():""}function fw(e){return gp(e)||void 0}function xw(e){return e.sessionId||e.instanceId||e.agentType}function yp(e=[]){const t={};for(const n of e)n.type==="adhdev-daemon"&&(t[n.id]=ts(n,{fallbackId:n.id}));return t}function vp(e,t={}){var r;const n=e.daemonId||((r=e.id)==null?void 0:r.split(":")[0])||e.id;return{machineName:_g(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[n]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Vi(e,t={}){return bw(e,vp(e,t))}function bw(e,t={}){var h,g,v,f,y,j,x,w,N;const n=[],r=t.machineName,a=t.connectionState,o=hw(e),i=e.workspace||"",u=Og(e.type,{agentName:e.cliName}),c=ct(e)||lt(e)?u:$t(e.type),p=mw(e,c),d=Array.isArray(e.childSessions)?e.childSessions.map(k=>{var b,C,S;return{sessionId:k.id,instanceId:k.id,providerSessionId:k.providerSessionId,activeChatId:(b=k.activeChat)==null?void 0:b.id,transport:k.transport,sessionCapabilities:k.capabilities,agentType:k.providerType,agentName:k.providerName||$t(k.providerType),model:fw(k),status:k.status,title:k.title,lastMessagePreview:k.lastMessagePreview,lastMessageRole:k.lastMessageRole,lastMessageAt:k.lastMessageAt,lastMessageHash:k.lastMessageHash,messages:((C=k.activeChat)==null?void 0:C.messages)||[],activeModal:((S=k.activeChat)==null?void 0:S.activeModal)||void 0,unread:k.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,inboxBucket:k.inboxBucket,completionMarker:k.completionMarker,surfaceHidden:k.surfaceHidden,muted:k.muted,git:k.git,settings:k.settings,coordinator:k.coordinator,messageInput:k.messageInput}}):[],m=pw(e);if(m){const k=e.sessionId||e.instanceId,b=(h=e.settings)==null?void 0:h.meshCoordinatorFor,C=((g=e.settings)==null?void 0:g.meshNodeFor)||!((v=e.settings)!=null&&v.meshCoordinatorFor)&&((f=e.settings)==null?void 0:f.launchedByCoordinator),S=b?" (Coordinator)":C?" (Mesh Node)":"",M=u+S,A=(y=e.activeChat)==null?void 0:y.activeModal,T=A&&Array.isArray(A.buttons)&&A.buttons.length>0,L=Wg(e.activeChat,[{status:e.status,activeModal:(j=e.activeChat)==null?void 0:j.activeModal}],e.agents||[]),P=e.activeChat||{title:"",messages:[]};let B=P.title&&String(P.title).trim()?String(P.title).trim():"";const z=(x=e.activeChat)==null?void 0:x.id,R=e.chats;if(z&&Array.isArray(R)&&R.length>0){const Y=R.find(Z=>Z.id===z||Z.id&&String(Z.id)===String(z));Y!=null&&Y.title&&String(Y.title).trim()&&(B=String(Y.title).trim())}const _=(ct(e)||lt(e),e.type),K=(ct(e)||lt(e))&&zl(B,M,_)?"":B,E=P.messages||[],D=typeof z=="string"?z.trim():"",$=(ct(e)||lt(e))&&D===String(e.type||"").trim(),I=D&&!$?D:e.providerSessionId,G=e.coordinator||(typeof((w=e.settings)==null?void 0:w.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:k,providerSessionId:e.providerSessionId,historySessionId:I,nativeSessionId:k,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:ct(e)&&e.mode||"chat",agentName:M,agentType:_,status:L,title:K,messages:E,resume:e.resume,hostIdeType:!ct(e)&&!lt(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||K||(ct(e)?e.mode==="chat"?M:`Terminal${S}`:M),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:T?A.buttons:void 0,modalMessage:T?A.message:void 0,streamSource:"native",tabKey:Ja(k,e.id),machineName:r,connectionState:a,settings:e.settings,coordinator:G,messageInput:e.messageInput})}if(m&&(ct(e)||lt(e)))return n;for(const k of d){const b=k.activeModal&&Array.isArray(k.activeModal.buttons)&&k.activeModal.buttons.length>0,C=Ug(k),S=xw(k),M=`${e.id}:${S}`,A=k.title&&String(k.title).trim()||"",T=zl(A,k.agentName,k.agentType)?"":A,L=k.messages||[];if(!(k.transport==="cdp-webview"||!!k.sessionId||!!k.providerSessionId||L.length>0||b||!!T||!["idle","panel_hidden","disconnected","not_monitored"].includes(C)))continue;const B=k.coordinator||(typeof((N=k.settings)==null?void 0:N.meshCoordinatorFor)=="string"&&k.settings.meshCoordinatorFor?{meshId:k.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:k.sessionId||k.instanceId,providerSessionId:k.providerSessionId,historySessionId:k.activeChatId||k.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:k.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:k.sessionCapabilities,mode:"chat",agentName:k.agentName,agentType:k.agentType,status:C,title:T,messages:L,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:k.git||e.git,displayPrimary:o||T||k.agentName||c,displaySecondary:k.model&&k.model.trim()?k.model.trim():`${c} · ${k.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:k.lastMessagePreview,lastMessageRole:k.lastMessageRole,lastMessageAt:k.lastMessageAt,lastMessageHash:k.lastMessageHash,lastUpdated:k.lastUpdated||e.lastUpdated,inboxBucket:k.inboxBucket,completionMarker:k.completionMarker,modalButtons:b?k.activeModal.buttons:void 0,modalMessage:b?k.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Ja(k.sessionId||k.instanceId,M),machineName:r,connectionState:a,settings:k.settings,coordinator:B,messageInput:k.messageInput})}return n.length===0&&n.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:u,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||c,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}),n}function wp(e){return String(e.type||e.id||"").trim()}function ma(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function gw(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(a=>a.type===n);return ma(r==null?void 0:r.modelOptions)}function yw(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(a=>a.type===n);return ma(r==null?void 0:r.thinkingLevelOptions)}function kp(e){const t=new Map;for(const n of e||[])n!=null&&n.type&&t.set(n.type,{models:ma(n.modelOptions),thinking:ma(n.thinkingLevelOptions)});return t}function vw(e){var t;return e.category!=="cli"||!wp(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 wn(e){var r;const t=new Set,n=[];for(const a of e||[]){if(!vw(a))continue;const o=wp(a);if(!o||t.has(o))continue;t.add(o);const i=String(a.displayName||a.name||o),u=a.detectedPath||((r=a.lastDetection)==null?void 0:r.path)||null;n.push({type:o,label:i,icon:a.icon,statusLabel:u?`Detected at ${u}`:"Detected on this machine",detectedPath:u,...Array.isArray(a.modelOptions)&&a.modelOptions.length?{modelOptions:a.modelOptions}:{},...Array.isArray(a.thinkingLevelOptions)&&a.thinkingLevelOptions.length?{thinkingLevelOptions:a.thinkingLevelOptions}:{}})}return n}function kn(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],n=new Set,r=[];for(const a of t){const o=typeof a=="string"?a.trim():"";!o||n.has(o)||(n.add(o),r.push(o))}return r}function cr(e){return e.map(t=>t.type)}function ww(e,t){const n=kn(e),r=t.trim();return!r||n.includes(r)?n:[...n,r]}function kw(e,t){return kn(e).filter(n=>n!==t)}function jc(e,t,n){const r=kn(e),a=r.indexOf(t);if(a<0)return r;const o=r.filter(u=>u!==t);if(n==="top")return[t,...o];if(n==="bottom")return[...o,t];const i=n==="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 jw({value:e,availableProviders:t,onChange:n,disabled:r=!1,saveButton:a}){const[o,i]=l.useState(""),u=l.useMemo(()=>new Map(t.map(h=>[h.type,h])),[t]),c=l.useMemo(()=>kn(e),[e]),p=c.filter(h=>!u.has(h)).length,d=t.filter(h=>!c.includes(h.type)),m=()=>{o&&(n(ww(c,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:c.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."}):c.map((h,g)=>{const v=u.get(h),f=!!v;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]}),(v==null?void 0:v.icon)&&s.jsx("span",{"aria-hidden":"true",children:v.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:v?`${v.label} · ${v.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:r||g===0,title:"Move up",onClick:()=>n(jc(c,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:r||g===c.length-1,title:"Move down",onClick:()=>n(jc(c,h,"down")),children:s.jsx(Sc,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:r,onClick:()=>n(kw(c,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:r||d.length===0,children:[s.jsx("option",{value:"",children:d.length?"Select provider…":"No additional detected CLI providers"}),d.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:r||!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 Sw(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 jp(e,t){const n=Sw(e);return{daemonId:n.daemonId,payload:{...t,...n.targetSessionId&&!t.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const Sp=[{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:"🏄"}],Np=[{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:"◆"}],Cp=[{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:"🟠"}],Nw=Sp,Cw=Np,Mw=Cp;function Aw({icon:e,title:t,subtitle:n,badge:r,actions:a,className:o}){return s.jsxs("div",{className:Ht("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,r&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[r.count!==void 0?r.count:""," ",r.text]})]}),n&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:n})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function br({icon:e,title:t,subtitle:n,badge:r,actions:a,widthClassName:o="max-w-6xl",contentClassName:i,children:u}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(Aw,{icon:e,title:t,subtitle:n,badge:r,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Ht("mx-auto flex w-full flex-col gap-4",o,i),children:u})})]})}const oi="adhdev:themechange";function Iw(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function ln(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function cn(e){return e==="system"?Iw():e}function Mp(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function zr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(oi,{detail:{preference:e,theme:t}}))}function Tw(){const e=ln(),t=cn(e);Mp(t),zr(e,t)}function Ls(){const[e,t]=l.useState(ln),[n,r]=l.useState(()=>cn(ln()));l.useEffect(()=>{Mp(n)},[n]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),u=c=>{if(e==="system"){const p=c.matches?"light":"dark";r(p),zr("system",p)}};return i.addEventListener("change",u),()=>i.removeEventListener("change",u)},[e]),l.useEffect(()=>{const i=c=>{const p=c.detail||{},d=p.preference,m=p.theme;t(d==="dark"||d==="light"||d==="system"?d:ln()),r(m==="dark"||m==="light"?m:cn(ln()))},u=c=>{if(c.key!=="theme")return;const p=ln(),d=cn(p);t(p),r(d)};return window.addEventListener(oi,i),window.addEventListener("storage",u),()=>{window.removeEventListener(oi,i),window.removeEventListener("storage",u)}},[]);const a=l.useCallback(i=>{const u=cn(i);t(i),r(u);try{localStorage.setItem("theme",i)}catch{}zr(i,u)},[]),o=l.useCallback(()=>{t(i=>{const u=i==="dark"?"light":i==="light"?"system":"dark",c=cn(u);r(c);try{localStorage.setItem("theme",u)}catch{}return zr(u,c),u})},[]);return{theme:n,preference:e,setPreference:a,cycleTheme:o,isDark:n==="dark"}}const Nc={dark:"Dark",light:"Light",system:"System"};function Pw({collapsed:e}){const{preference:t,cycleTheme:n}=Ls(),r=t==="dark"?s.jsx(Wf,{size:16}):t==="light"?s.jsx(Of,{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:n,title:`Theme: ${Nc[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:r}),!e&&s.jsx("span",{className:"text-xs",children:Nc[t]})]})}const ii="adhdev:langchange";function Dw(){const e=wt.language;return un(e)?e:mu()}function Lw(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(ii,{detail:{language:e}}))}function Rw(){const[e,t]=l.useState(Dw);l.useEffect(()=>{const r=i=>{un(i)&&t(i)},a=i=>{const u=i.detail||{};un(u.language)&&t(u.language)},o=i=>{if(i.key!==zo)return;const u=i.newValue;un(u)&&u!==wt.language&&(wt.changeLanguage(u),Vo(u))};return wt.on("languageChanged",r),window.addEventListener(ii,a),window.addEventListener("storage",o),()=>{wt.off("languageChanged",r),window.removeEventListener(ii,a),window.removeEventListener("storage",o)}},[]);const n=l.useCallback(r=>{if(un(r)){t(r);try{localStorage.setItem(zo,r)}catch{}wt.changeLanguage(r),Vo(r),Lw(r)}},[]);return{language:e,setLanguage:n}}function _w({collapsed:e}){const{language:t,setLanguage:n}=Rw(),{t:r}=Xe("common"),a=qa.find(i=>i.code===t)??qa[0],o=r("language.select",{defaultValue:"Select language"});return s.jsxs("div",{className:`nav-item relative cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,title:`${r("language.label",{defaultValue:"Language"})}: ${a.label}`,children:[s.jsx("span",{className:"nav-icon",children:s.jsx(Qf,{size:16})}),!e&&s.jsx("span",{className:"text-xs",children:a.label}),s.jsx("select",{"aria-label":o,value:t,onChange:i=>n(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 Ew({children:e,brand:t,navItems:n,sidebarSections:r=[],footerItems:a=[],footerInfo:o,footerActions:i,preMainContent:u,collapsedStorageKey:c="sidebar-collapsed"}){const[p,d]=l.useState(!1),[m,h]=l.useState(()=>{try{return localStorage.getItem(c)==="1"}catch{return!1}}),g=()=>d(!0),v=()=>d(!1),f=()=>{h(w=>{const N=!w;try{localStorage.setItem(c,N?"1":"0")}catch{}return N})},y=l.useMemo(()=>({collapsed:m,mobileMenuOpen:p,openMobileMenu:g,closeMobileMenu:v,toggleCollapsed:f}),[m,p]),j=w=>`nav-item${w.active?" active":""} cursor-pointer ${m?"justify-center py-2.5 px-0":""}${w.className?` ${w.className}`:""}`,x=w=>s.jsxs("div",{className:j(w),id:`nav-${w.id}`,onClick:()=>{w.onSelect(),v()},title:m?w.title??(typeof w.label=="string"?w.label:void 0):w.title,children:[s.jsx("span",{className:"nav-icon",children:w.icon}),!m&&w.label]},w.id);return s.jsxs("div",{className:`app-layout${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:v,onKeyDown:w=>w.key==="Escape"&&v()}),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,y)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:v,children:s.jsx(Mt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:n.map(x)}),r.map(w=>s.jsxs("div",{className:w.className??"border-t border-border-subtle pt-2 mt-2",children:[!m&&w.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:w.title}):null,w.items.map(x)]},w.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(x),ao(o,y),s.jsx(Pw,{collapsed:m}),s.jsx(_w,{collapsed:m}),ao(i,y)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[u,e]})})]})}function xt({title:e,icon:t,description:n,accentColor:r,className:a,collapsible:o,defaultOpen:i=!0,badge:u,children:c}){const[p,d]=l.useState(i),m=o?p:!0,h=(e||n)&&s.jsxs("div",{className:Ht("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}),u]}),n&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:n})]}),o&&s.jsx("span",{className:Ht("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:Ht("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",r&&"border-l-[3px]",a),style:r?{borderLeftColor:r}:void 0,children:[o&&h?s.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>d(g=>!g),"aria-expanded":m,children:h}):h,m&&c]})}function La({icon:e,title:t,description:n,action:r,className:a}){return s.jsxs("div",{className:Ht("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:n}),r]})}const $w={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"},Fw={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Kt({variant:e,children:t,onDismiss:n,className:r}){return s.jsxs("div",{className:Ht("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",$w[e],r),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Fw[e]}),s.jsx("span",{children:t})]}),n&&s.jsx("button",{onClick:n,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function St({label:e,hint:t,children:n,className:r}){return s.jsxs("div",{className:Ht("mb-5",r),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),n,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function is(e){const{className:t,...n}=e;return s.jsx("input",{...n,className:Ht("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 Bw={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},ks=l.forwardRef(function({variant:t="secondary",size:n="md",type:r,className:a,...o},i){return s.jsx("button",{ref:i,type:r??"button",className:Ht("btn",Bw[t],n==="sm"&&"btn-sm",a),...o})}),Hw=l.forwardRef(function({options:t,children:n,className:r,...a},o){return s.jsx("select",{ref:o,className:Ht("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",r),...a,children:n??(t==null?void 0:t.map(i=>s.jsx("option",{value:i.value,disabled:i.disabled,children:i.label},i.value)))})}),Ow={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"},Ww={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Uw({status:e,label:t,className:n}){const r=t||e;return s.jsxs("span",{className:Ht("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Ow[e],n),children:[s.jsx("span",{className:Ht("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Ww[e])}),r]})}function Bs({label:e,description:t,checked:n,disabled:r,onChange:a,extra:o}){return s.jsxs("div",{className:`flex justify-between items-center ${r?"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":n,"aria-disabled":r,disabled:r,onClick:()=>a(!n),className:`relative inline-flex items-center ${r?"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:n?"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)] ${n?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function Kw({onPrefChange:e}){const[t,n]=Zg(),[r,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,u)=>{n({[i]:u}),e==null||e(i,u)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Bs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Cn,{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(Bs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{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."}),r==="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:()=>{ju().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"})]}),r==="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."}),r==="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(Bs,{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(Bs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Kf,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:i=>o("approvalAlert",i)}),s.jsx(Bs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(or,{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 n=t[4]??null;let r=null;if(n){const a=n.match(/(?:^|\.)(\d+)$/);r=a?Number(a[1]):null}return{base:[Number(t[1]),Number(t[2]),Number(t[3])],prereleaseNumber:r,isPrerelease:n!==null}}function fa(e){var t;return((t=li(e))==null?void 0:t.base)??null}function Gw(e,t){const n=fa(e),r=fa(t);if(!n||!r)return e.localeCompare(t);for(let a=0;a<3;a+=1){if(n[a]<r[a])return-1;if(n[a]>r[a])return 1}return 0}function zw(e,t){const n=li(e),r=li(t);if(!n||!r)return e!==t;for(let a=0;a<3;a+=1){if(n.base[a]<r.base[a])return!0;if(n.base[a]>r.base[a])return!1}return n.isPrerelease&&r.isPrerelease?n.prereleaseNumber===null||r.prereleaseNumber===null?!1:n.prereleaseNumber<r.prereleaseNumber:!1}function qi(e,t){const n=e.version||null;return e.versionMismatch===!0?!0:!n||!t?!1:zw(n,t)}function tr(e,t){if(e.versionUpdateRequired===!0)return!0;const n=e.version||null;if(!n||!t||n===t||Gw(n,t)>=0)return!1;const r=fa(n),a=fa(t);return!r||!a?!1:r[0]!==a[0]||r[1]!==a[1]}function Vw(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 qw({ides:e,emptyMessage:t,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a}){const o=e.filter(i=>i.type==="adhdev-daemon");return o.length===0?s.jsx(La,{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(Jw,{ide:i,allIdes:e,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a},i.id))})}function Cc({title:e,message:t,confirmLabel:n,confirmColor:r,onConfirm:a,onCancel:o}){const i=r==="red"?"bg-status-error/20 text-status-error border-status-error/40 hover:bg-status-error/30":"";return fn.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:u=>u.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:r==="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:n})]})]})}),document.body)}function Yw(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),r=[...Nw,...Cw,...Mw].find(a=>a.id===t||t.includes(a.id)||a.id.includes(t));return r?{icon:r.icon,name:r.name}:{icon:"📝",name:e}}function Jw({ide:e,allIdes:t,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a}){var B,z;const[o,i]=l.useState("idle"),[u,c]=l.useState(""),[p,d]=l.useState(null),[m,h]=l.useState("idle"),[g,v]=l.useState(""),f=e.version||null,y=((B=e.machine)==null?void 0:B.platform)||((z=e.system)==null?void 0:z.platform)||"",j=ts(e,{fallbackId:e.id}),x=y==="win32"?"🪟":y==="darwin"?"🍎":"🐧",w=t.filter(R=>R.daemonId===e.id&&R.transport==="cdp-page"),N=t.filter(R=>R.daemonId===e.id&&R.transport==="pty"),k=t.filter(R=>R.daemonId===e.id&&R.transport==="acp"),b=e.p2p,C=async()=>{if(n){i("upgrading"),c("Starting upgrade...");try{const R=Vw(await n(e.id,"daemon_upgrade",{}));R.alreadyLatest?(i("done"),c(`Already on v${R.version||"latest"}.`)):R.upgraded||R.success?(i("done"),c(`Upgrade to v${R.version||"latest"} started. Daemon is restarting...`)):(i("error"),c(R.error||"Upgrade failed"))}catch(R){i("error"),c(oo(R,"Connection lost during upgrade"))}}},S=async()=>{if(d(null),!!r){h("loading");try{await r(e.id),h("done"),v("Machine disconnected.")}catch(R){h("error"),v(oo(R,"Failed to disconnect"))}}},M=async()=>{if(d(null),!!a){h("loading");try{await a(e.id),h("done"),v("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(R){h("error"),v(oo(R,"Failed to revoke token"))}}},A="0.9.82",T=qi(e,A),L=tr(e,A),P=w.length+N.length+k.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:x}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:j}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),f&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${T?"":"bg-bg-secondary"}`,style:T?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",f,!T&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[n&&T&&s.jsx("button",{onClick:C,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${A}`,children:o==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${L?"↑ Update now":`↑ Update${` to v${A}`}`}`}),r&&s.jsx("button",{onClick:()=>d("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:()=>d("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(Uw,{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:[w.map(R=>{const _=Yw(R.type),K=R.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:_.icon}),s.jsx("span",{children:_.name}),K!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${K?"bg-status-online":"animate-pulse"}`,style:K?void 0:{background:"var(--status-warning)"},title:K?"CDP connected":"CDP connecting..."})]},R.id)}),N.map(R=>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:R.cliName||"CLI"})]},R.id)),k.map(R=>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:R.cliName||"ACP"})]},R.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(u||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||u})]}),p==="disconnect"&&s.jsx(Cc,{title:"🔌 Disconnect Machine",message:`Disconnect "${j}" 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:()=>d(null)}),p==="revoke"&&s.jsx(Cc,{title:"⚠️ Remove Machine",message:`Remove "${j}" 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:M,onCancel:()=>d(null)})]})}const Xw=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function Qw({daemonId:e,knownCliTypes:t=Xw}){const{sendCommand:n}=yt(),[r,a]=l.useState({}),[o,i]=l.useState({}),[u,c]=l.useState(!0),[p,d]=l.useState(null),[m,h]=l.useState(null),[g,v]=l.useState(""),f=l.useCallback(async()=>{if(e){c(!0),h(null);try{const x=await n(e,"list_coordinator_prompts",{}),w=x!=null&&x.result&&typeof x.result=="object"?x.result:x;if(!(w!=null&&w.success)){h((w==null?void 0:w.error)||"Failed to load");return}const N=w.entries||{};v(w.dir||"");const k={};for(const b of t)k[b]=N[b]||{override:"",append:""};for(const b of Object.keys(N))k[b]||(k[b]=N[b]);a(k),i(JSON.parse(JSON.stringify(k)))}catch(x){h((x==null?void 0:x.message)||String(x))}finally{c(!1)}}},[n,e,t]);l.useEffect(()=>{f()},[f]);const y=l.useCallback(async(x,w)=>{var N;if(e){d(`${x}:${w}`),h(null);try{const k=((N=r[x])==null?void 0:N[w])||"",b=await n(e,"write_coordinator_prompt",{key:x,kind:w,content:k}),C=b!=null&&b.result&&typeof b.result=="object"?b.result:b;if(!(C!=null&&C.success)){h((C==null?void 0:C.error)||"Save failed");return}i(S=>({...S,[x]:{...S[x]||{override:"",append:""},[w]:k}}))}catch(k){h((k==null?void 0:k.message)||String(k))}finally{d(null)}}},[n,e,r]),j=l.useMemo(()=>(x,w)=>{var N,k;return(((N=r[x])==null?void 0:N[w])||"")!==(((k=o[x])==null?void 0:k[w])||"")},[r,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}),u&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Loading…"}),s.jsx("div",{className:"flex flex-col gap-6",children:Object.entries(r).map(([x,w])=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-2",children: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:w.override,onChange:N=>a(k=>({...k,[x]:{...k[x],override:N.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 y(x,"override"),disabled:p===`${x}:override`||!j(x,"override"),children:p===`${x}:override`?"Saving…":j(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:w.append,onChange:N=>a(k=>({...k,[x]:{...k[x],append:N.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 y(x,"append"),disabled:p===`${x}:append`||!j(x,"append"),children:p===`${x}:append`?"Saving…":j(x,"append")?"Save append":"Saved"})})]},x))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const Zw=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function ek(){const{preference:e,setPreference:t}=Ls();return s.jsx("div",{className:"flex gap-2",children:Zw.map(n=>s.jsxs("button",{onClick:()=>t(n.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===n.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===n.id?{color:"var(--accent-on-primary)"}:void 0,children:[s.jsx("span",{children:n.icon}),n.label]},n.id))})}function tk(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 sk(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 Mc(e){const{r:t,g:n,b:r}=sk(e);return .2126*io(t)+.7152*io(n)+.0722*io(r)}function Ac(e,t){const n=Mc(e),r=Mc(t),a=Math.max(n,r),o=Math.min(n,r);return(a+.05)/(o+.05)}function Ap(e){const t=tk(e);if(!t)return"#111827";const n="#111827",r="#ffffff";return Ac(t,n)>=Ac(t,r)?n:r}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},nk=[{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"}}}],Ip="adhdev-chat-theme",Tp="adhdev-chat-theme-custom";function Vr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Ip)||"ember"}catch{return"ember"}}function os(e){try{const t=localStorage.getItem(Tp);if(t){const n=JSON.parse(t);return{...e==="dark"?ci:di,...n[e]}}}catch{}return e==="dark"?ci:di}function Ir(e,t){try{localStorage.setItem(Tp,JSON.stringify({dark:e,light:t}))}catch{}}function Xt(e,t){const n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${n}, ${r}, ${a}, ${t})`}function xa(e,t){const n=Math.min(255,parseInt(e.slice(1,3),16)+t),r=Math.min(255,parseInt(e.slice(3,5),16)+t),a=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${n.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const rk={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function sr(e,t){var a;const n=(a=rk[e])==null?void 0:a[t];if(!n)return;const r=document.documentElement;r.style.setProperty("--accent-primary",n),r.style.setProperty("--accent-primary-light",xa(n,24)),r.style.setProperty("--accent-on-primary",Ap(n)),r.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${xa(n,18)})`),r.style.setProperty("--border-accent",Xt(n,.35)),r.style.setProperty("--nav-active-bg",Xt(n,.1)),r.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${n}, 0 0 12px ${Xt(n,.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",Xt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Xt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Xt(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",Xt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Xt(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",Ap(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${xa(e.accentColor,40)})`),t.style.setProperty("--border-accent",Xt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Xt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Xt(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 ${Xt(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(n=>e.style.removeProperty(n))}function ak(e){try{localStorage.setItem(Ip,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=zs()?"dark":"light";Gs(os(t))}else Yi(),sr(e,zs()?"dark":"light")}function ok(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Vr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=zs()?"dark":"light";Gs(os(t))}else Yi(),sr(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 Ft({label:e,value:t,onChange:n}){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:r=>n(r.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:r=>{/^#[0-9a-fA-F]{0,6}$/.test(r.target.value)&&n(r.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 Bn({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 ik({dark:e,onColorsChange:t}){const n=e?"dark":"light",[r,a]=l.useState(()=>os(n));l.useEffect(()=>{a(os(n))},[n]);const o=l.useCallback((i,u)=>{a(c=>{const p={...c,[i]:u},m=os(n==="dark"?"light":"dark");return n==="dark"?Ir(p,m):Ir(m,p),Gs(p),t(p),p})},[n,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(Bn,{title:"App Background",children:[s.jsx(Ft,{label:"Background",value:r.bgPrimary,onChange:i=>o("bgPrimary",i)}),s.jsx(Ft,{label:"Surface",value:r.bgSecondary,onChange:i=>o("bgSecondary",i)}),s.jsx(Ft,{label:"Card",value:r.surfacePrimary,onChange:i=>o("surfacePrimary",i)})]}),s.jsxs(Bn,{title:"App Text",children:[s.jsx(Ft,{label:"Primary",value:r.textPrimary,onChange:i=>o("textPrimary",i)}),s.jsx(Ft,{label:"Secondary",value:r.textSecondary,onChange:i=>o("textSecondary",i)}),s.jsx(Ft,{label:"Muted",value:r.textMuted,onChange:i=>o("textMuted",i)})]}),s.jsxs(Bn,{title:"Borders & Accent",children:[s.jsx(Ft,{label:"Border subtle",value:r.borderSubtle,onChange:i=>o("borderSubtle",i)}),s.jsx(Ft,{label:"Border default",value:r.borderDefault,onChange:i=>o("borderDefault",i)}),s.jsx(Ft,{label:"Accent",value:r.accentColor,onChange:i=>o("accentColor",i)})]})]}),s.jsxs("div",{children:[s.jsxs(Bn,{title:"Chat Bubbles",children:[s.jsx(Ft,{label:"User bubble",value:r.userBubble,onChange:i=>o("userBubble",i)}),s.jsx(Ft,{label:"User text",value:r.userText,onChange:i=>o("userText",i)}),s.jsx(Ft,{label:"Agent bubble",value:r.assistantBubble,onChange:i=>o("assistantBubble",i)}),s.jsx(Ft,{label:"Agent text",value:r.assistantText,onChange:i=>o("assistantText",i)})]}),s.jsxs(Bn,{title:"Chat Layout",children:[s.jsx(Ft,{label:"Chat BG",value:r.containerBg,onChange:i=>o("containerBg",i)}),s.jsx(Ft,{label:"Send button",value:r.sendButton,onChange:i=>o("sendButton",i)}),s.jsx(Ft,{label:"Input border",value:r.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:r.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:[r.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const i=e?ci:di,c=os(e?"light":"dark");e?Ir(i,c):Ir(c,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 lk(){const[e,t]=l.useState(Vr),[n,r]=l.useState(!0),[a,o]=l.useState(()=>os("dark"));l.useEffect(()=>{r(zs());const c=new MutationObserver(()=>{const m=zs();r(m);const h=Vr();h==="custom"?Gs(os(m?"dark":"light")):sr(h,m?"dark":"light")});c.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{const m=zs();r(m);const h=Vr();h==="custom"?Gs(os(m?"dark":"light")):sr(h,m?"dark":"light")};return p.addEventListener("change",d),()=>{c.disconnect(),p.removeEventListener("change",d)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?Gs(os(n?"dark":"light")):(Yi(),sr(e,n?"dark":"light"))},[e,n]),l.useEffect(()=>{o(os(n?"dark":"light"))},[n]);const i=c=>{t(c),ak(c)},u=[...nk,{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:u.map(c=>{const p=e===c.id,d=n?c.preview.dark:c.preview.light,m=c.id==="honey"||c.id==="ember"?"#1a1a1a":c.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>i(c.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:d.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.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:d.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:d.assistantBubble,border:d.assistantBorder,color:d.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:c.id==="custom"?"🎨 Custom":c.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:c.description})]})]})]},c.id)})}),e==="custom"&&s.jsx(ik,{dark:n,onColorsChange:c=>o(c)})]})}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 ck(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Xi())},n=a=>{const o=a.detail;t(o)},r=a=>{a.key&&a.key!==Ji||t()};return window.addEventListener(ui,n),window.addEventListener("storage",r),()=>{window.removeEventListener(ui,n),window.removeEventListener("storage",r)}}function dk(e){try{localStorage.setItem(Ji,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ui,{detail:e}))}function uk(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(Xi()==="chat")},[]),s.jsx(Bs,{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:n=>{t(n),dk(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const pk="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",hk="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function mk({themeDescription:e=pk,mobileDescription:t=hk,fontsSlot:n}){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(ek,{})]}),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(lk,{})]}),n,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(uk,{})]})]})}const lo=new Map,Ic=new Map;function fk(e){if(!e||typeof e!="object")return null;const t=e,n=t.result&&typeof t.result=="object"?t.result:t,r=n.machine;return!r||typeof r!="object"?null:{machine:r,timestamp:typeof n.timestamp=="number"?n.timestamp:void 0}}function xk(e,t,n,r){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:r,platform:n.platform,machine:n}}function Pp(){const{sendCommand:e}=yt(),{injectEntries:t,getIdes:n}=ar();return l.useCallback(async(r,a)=>{if(!r)return;const o=(a==null?void 0:a.minFreshMs)??Tv,i=Ic.get(r)||0;if(!(a!=null&&a.force)&&i>0&&Date.now()-i<o)return;const u=lo.get(r);if(u)return u;const c=(async()=>{const p=await e(r,"get_machine_runtime_stats"),d=fk(p);if(!d)return;const m=n().find(g=>g.id===r),h=xk(m,r,d.machine,d.timestamp||Date.now());t([h]),Ic.set(r,Date.now())})().finally(()=>{lo.delete(r)});return lo.set(r,c),c},[n,t,e])}function bk(e,t,n){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:n.timestamp,platform:n.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...n.machine}}}function gk(e,t){const{sendData:n}=yt(),{injectEntries:r,getIdes:a}=ar(),o=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!n)return;const i=o?o.split("|"):[];if(i.length===0)return;const u=i.map(c=>ls.subscribe({sendData:n},c,{type:"subscribe",topic:"machine.runtime",key:`machine:${c}`,params:{intervalMs:t==null?void 0:t.intervalMs}},d=>{const m=a().find(g=>g.id===c),h=bk(m,c,d);r([h])}));return()=>{u.forEach(c=>c())}},[o,a,r,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,n])}function yk(e,t){const{sendData:n}=yt(),[r,a]=l.useState(null),[o,i]=l.useState(!1);return l.useEffect(()=>{if(!e){a(null),i(!1);return}if(!(t!=null&&t.enabled)||!n){i(!1);return}a(null),i(!0);let u=null;const c=ls.subscribe({sendData:n},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=>{u&&(clearTimeout(u),u=null),a(p.diagnostics),i(!1)});return c.initialSendAccepted?u=setTimeout(()=>{i(!1)},Lv):i(!1),()=>{u&&clearTimeout(u),c()}},[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,n]),{diagnostics:r,loading:o,applyDiagnostics:a}}function vk(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Dp(e){const{sendData:t}=yt(),[n,r]=l.useState({});return l.useEffect(()=>{const a=vk(e);if(!a||!e.sessionId||!t){r({});return}const o=ls.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},i=>{r({status:i.status,modalMessage:i.modalMessage,modalButtons:i.modalButtons}),xn.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||r({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),n}function wk(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function kk(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 jk(e,t,n){const r=await n(`/api/v1/sessions/${encodeURIComponent(e)}/interactive-prompt/resolve`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let a=`HTTP ${r.status}`;try{const o=await r.json();typeof(o==null?void 0:o.error)=="string"&&(a=o.error)}catch{}throw new Error(a)}}async function Sk({promptSession:e,response:t,useP2PCommand:n,sendCommand:r,fetchImpl:a=fetch}){if(n){const o=await r(e.routeId,"interactive_prompt_response",{targetSessionId:e.sessionId,sessionId:e.sessionId,response:t});if(!wk(o))throw new Error(kk(o));return}await jk(e.sessionId,t,a)}function Lp(e){const{ides:t,isP2PActive:n,p2pStates:r}=bs(),{sendCommand:a}=yt(),[o,i]=l.useState(null),[u,c]=l.useState(!1),[p,d]=l.useState(null),m=l.useRef(!1),h=l.useMemo(()=>Ax(t,e),[t,e]),g=!!h,v=l.useMemo(()=>h?h.prompt.promptId===o?null:h:null,[o,h]),f=l.useCallback(async x=>{if(!v||m.current)return;m.current=!0;const w=lu(v.prompt,x);c(!0),d(null);try{const N=(r==null?void 0:r[v.daemonId])==="connected"||n===!0;await Sk({promptSession:v,response:w,useP2PCommand:N,sendCommand:a}),i(v.prompt.promptId)}catch(N){throw d(N instanceof Error?N.message:String(N)),N}finally{c(!1),m.current=!1}},[n,r,v,a]),y=l.useCallback(()=>{v&&i(v.prompt.promptId)},[v]),j=l.useCallback(()=>{i(null),d(null)},[]);return{promptSession:v,hasActivePrompt:g,responseError:p,isSubmitting:u,submit:f,cancel:y,reopen:j}}function Rp(e){return e instanceof Error?e.message:String(e||"")}function Nk(e){const t=Rp(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 Ck(e){const t=Rp(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:n,sendDaemonCommand:r,setCliViewModeOverrides:a}){if(!e||!ct(e)||lt(e))return;const o=An(e);if(o===t)return;const i=e.sessionId;i&&a(u=>({...u,[i]:t}));try{await r(Ds(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:xs(e),mode:t})}catch(u){const c=Ck(u);i&&!c&&a(p=>{const d={...p};return o===Ak(n,i)?delete d[i]:d[i]=o,d}),Nk(u)?console.warn(c?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",u instanceof Error?u.message:String(u)):console.error("Failed to switch CLI view mode:",u)}}function Tc(e,t){const n=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!n||e.transport!=="pty")return e;const r=t[n];return!r||e.mode===r?e:{...e,mode:r}}function Mk(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let n=!1;const r=e.map(a=>{const o=Tc(a,t),i=Array.isArray(a.childSessions)?a.childSessions.map(c=>Tc(c,t)):a.childSessions,u=i!==a.childSessions;return o!==a||u?(n=!0,{...o,...u?{childSessions:i}:{}}):a});return n?r:e}function Ak(e,t){if(!t)return null;for(const n of e){if(n.sessionId===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal";for(const r of n.childSessions||[])if(r.id===t&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal"}return null}function Ik({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:r,isConversationMuted:a}){l.useEffect(()=>{ju()},[]);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 ny(o),l.useEffect(()=>{if(Object.keys(t).length===0)return;const u=setTimeout(()=>{n(c=>{const p=Date.now(),d={};for(const[m,h]of Object.entries(c))p-h<5e3&&(d[m]=h);return Object.keys(d).length===Object.keys(c).length?c:d})},5500);return()=>clearTimeout(u)},[t,n]),l.useEffect(()=>{const i=setInterval(()=>{const u=Date.now()-3e5;r(c=>{const p=c.filter(d=>d.timestamp>u).slice(-100);return p.length===c.length?c:p})},6e4);return()=>clearInterval(i)},[r]),null}function Pc(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function Vs(e){const t=[...e.messages].reverse().find(a=>!(a!=null&&a._localId))||e.messages[e.messages.length-1],n=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,r=Pc(t==null?void 0:t.receivedAt)||Pc(t==null?void 0:t.timestamp)||0;return Math.max(n,r)}function pi(e,t=0){return Vs(e)||e.lastUpdated||t||0}function Ep(e){return Vs(e)||e.lastUpdated||0}function $p(e,t,n=Ep){const r=n(t)-n(e);if(r!==0)return r;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 hi(e){var n;const t=Zt(e.status,{activeModal:(n=e.modalButtons)!=null&&n.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function Tk(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!hi(e)&&!e.title.trim()}function Pk(e){return e.length===0?null:[...e].sort((t,n)=>{const r=Number(hi(n))-Number(hi(t));if(r!==0)return r;const a=n.messages.length-t.messages.length;return a!==0?a:$p(t,n)})[0]||null}function cs(e,t){const n=e.filter(i=>i.routeId===t);if(n.length===0)return null;const r=n.find(i=>i.streamSource==="native")||null,a=n.filter(i=>i.streamSource==="agent-stream"),o=Pk(a);return r?o&&Tk(r)?o:r:o||n[0]||null}function Dk(e){const t=e.filter(a=>a.type!=="adhdev-daemon"),n=new Set;for(const a of t){if(!Xo(a))continue;const o=bu(a);o&&n.add(o)}const r=new Map;for(const a of t){const o=Rg(a,n),i=r.get(o);if(!i){r.set(o,a);continue}const u=m=>(m.workspace?1:0)+(m.activeChat?1:0)+(m.lastMessagePreview?1:0),c=u(i),p=u(a),d=p>c||p===c&&(a.timestamp||0)>(i.timestamp||0)?a:i;r.set(o,Lk(d,d===a?i:a))}return Array.from(r.values())}function Lk(e,t){const n=Xo(t),r=Xo(e);if(!n&&!r)return e;const a=r?n?void 0:t:e,o=r?e:n?t:void 0,i=a&&String(a.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,u=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,c=o==null?void 0:o.settings;return{...e,...i&&{ownerDaemonId:i},...u&&!e.ownerMachineName&&{ownerMachineName:u},...c&&!r&&{settings:{...c,...e.settings??{}}}}}function co(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function Rk(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function Dc(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],n=t[t.length-1],r=n?Rk(bn(n.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((n==null?void 0:n.id)||""),String((n==null?void 0:n.index)??""),String((n==null?void 0:n.receivedAt)??(n==null?void 0:n.timestamp)??""),r].join(":")}function _k(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||""),Dc(e.activeChat),...t.map(n=>[n.id||"",n.providerSessionId||"",n.transport||"",n.mode||"",n.status||"",n.title||"",n.lastMessageHash||"",String(n.lastMessageAt||""),n.lastMessagePreview||"",n.lastMessageRole||"",String(n.lastUpdated||""),Dc(n.activeChat)].join(":"))].join("|")}function Ek(e,t){const n=Date.now();return e.map(r=>{const a=t[r.tabKey];return a&&n-a<5e3?{...r,messages:[],title:""}:r})}function $k(e,t){const n=new Map;for(const r of e){const a=t.get(r.routeId)||r;for(const o of Qn({routeId:r.routeId}))n.set(o,a);for(const o of Qn({providerSessionId:r.providerSessionId,sessionId:r.sessionId}))n.set(o,r.streamSource==="native"?a:r);for(const o of Qn({tabKey:r.tabKey}))n.set(o,r)}return n}function Fk(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Bk(e){const t=Fk(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 n=String(t.role||""),r=bn(t.content).slice(0,240);return`${e.messages.length}:${n}:${r}`}function Hk({ides:e,connectionStates:t,clearedTabs:n}){const r=l.useMemo(()=>Dk(e),[e]),a=l.useMemo(()=>uu(e),[e]),o=l.useMemo(()=>yp(e),[e]),i=l.useRef([]),u=l.useRef([]),c=l.useRef([]),p=l.useRef(new Map),d=l.useRef(new Map),m=l.useMemo(()=>{const N=new Map,k=[];for(const M of r){const{connectionState:A="new",machineName:T}=vp(M,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),L=_k(M),P=p.current.get(M.id);if(P&&P.ide===M&&P.sourceSignature===L&&P.connectionState===A&&P.machineName===T){N.set(M.id,P),k.push(...P.conversations);continue}const B=Vi(M,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),z={ide:M,sourceSignature:L,connectionState:A,machineName:T,conversations:B};N.set(M.id,z),k.push(...B)}p.current=N;const b=new Map,C=M=>{const A=Bk(M),T=d.current.get(M.tabKey);if(T&&T.signature===A)return b.set(M.tabKey,T),T.timestamp;const L={signature:A,timestamp:Ep(M)||(T==null?void 0:T.timestamp)||0};return b.set(M.tabKey,L),L.timestamp},S=[...k].sort((M,A)=>$p(M,A,C));return d.current=b,S},[r,t,o]),h=l.useMemo(()=>{const N=Ek(m,n);return co(i.current,N)?i.current:(i.current=N,N)},[m,n]),g=l.useMemo(()=>{const N=new Map,k=Array.from(new Set(h.map(b=>b.routeId)));for(const b of k){const C=cs(h,b);C&&N.set(b,C)}return N},[h]),v=l.useMemo(()=>{const N=new Map;for(const k of h){const b=g.get(k.routeId),C=k.streamSource==="native"&&b?b:k;for(const S of Qn({providerSessionId:k.providerSessionId,sessionId:k.sessionId,tabKey:k.tabKey}))N.set(S,C)}return N},[h,g]),f=l.useMemo(()=>$k(h,g),[h,g]),y=l.useCallback(N=>{if(N)return v.get(N)},[v]),j=l.useCallback(N=>{if(N)return f.get(N)},[f]),x=l.useMemo(()=>{const N=h.filter(k=>!Ps(k,a).surfaceHidden);return co(u.current,N)?u.current:(u.current=N,N)},[h,a]),w=l.useMemo(()=>{const N=x.map(k=>k.tabKey);return co(c.current,N)?c.current:(c.current=N,N)},[x]);return{chatIdes:r,conversations:h,visibleConversations:x,visibleTabKeys:w,resolveConversationBySessionId:y,resolveConversationByTarget:j}}function Ok({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:n,setSearchParams:r}){const a=l.useMemo(()=>{var u;return e||!t?null:((u=n(t))==null?void 0:u.tabKey)??null},[e,n,t]),o=l.useMemo(()=>{var u;return!e||!t?null:((u=n(t))==null?void 0:u.tabKey)??null},[e,n,t]),i=l.useCallback(()=>{t&&r(u=>{const c=new URLSearchParams(u);return c.delete("activeTab"),c},{replace:!0})},[r,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function Wk({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:r}){l.useEffect(()=>{ht.setIdes(e)},[e]),l.useEffect(()=>{ht.setResolveAction((a,o,i)=>{t(a,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const a=ht.onToast(o=>{n(u=>u.some(p=>p.message===o.message&&o.timestamp-p.timestamp<3e3)?u:[...u.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(()=>n(u=>u.filter(c=>c.id!==o.id)),i)});return()=>{a()}},[n]),l.useEffect(()=>{const a=rp.on("status_event",o=>{ht.handleRawEvent(o,"ws")});return()=>{a()}},[]),l.useEffect(()=>{var o;const a=i=>{var f;const u=i.data;if((u==null?void 0:u.type)!=="notification_action"||typeof u.action!="string"||!u.action.startsWith("approval_")||!(u.daemonId||u.targetSessionId||u.targetKey))return;const c=u.targetSessionId||u.targetKey||u.daemonId,p=r(c),d=(p==null?void 0:p.routeId)||u.daemonId;if(!d)return;const m=Number(u.buttonIndex),h=u.button||((f=p==null?void 0:p.modalButtons)==null?void 0:f[m])||"Approve",g=String(h).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),v=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(g);t(d,"resolve_action",{action:v?"approve":"reject",button:h,...Number.isFinite(m)&&{buttonIndex:m},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...u.targetSessionId&&{targetSessionId:u.targetSessionId}}).catch(y=>console.error("[SW Action] approval failed:",y))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",a)}},[r,t])}const Uk="adhdev_dashboardLayout_v1",Kk="adhdev_dashboardDockview_v1",Gk="adhdev_dashboardDockviewHiddenRestore_v1",Hn={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Qi(e,t){try{const n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function zk(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Fp(e){return`${Uk}:${e}`}function Vk(e){const t=Fp(e);return Qi(t,null)}function qk(e,t){try{const n=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,r=Fp(e);if(n){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Bp(e){return`${Kk}:${e}`}function Yk(e){const t=Bp(e);return Qi(t,null)}function Jk(e,t){try{const n=Bp(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Hp(e){return`${Gk}:${e}`}function Xk(e){const t=Hp(e);return Qi(t,{})}function Qk(e,t){try{const n=Hp(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Zk(){return{groupAssignments:[...Hn.groupAssignments],focusedGroup:Hn.focusedGroup,groupActiveTabIds:{...Hn.groupActiveTabIds},groupTabOrders:{...Hn.groupTabOrders},groupSizes:[...Hn.groupSizes]}}function ej(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):t.length===0}function tj(){const[e]=l.useState(()=>zk(typeof window<"u"?window.innerWidth:1280)),[t,n]=l.useState(()=>new Map),[r,a]=l.useState(0),[o,i]=l.useState({}),[u,c]=l.useState({}),[p,d]=l.useState([]),[m,h]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[g,v]=l.useState(!1),f=l.useCallback(()=>{if(g)return;const M=Vk(e)??Zk();n(new Map(M.groupAssignments)),a(M.focusedGroup),i(M.groupActiveTabIds),c(M.groupTabOrders),d(M.groupSizes),v(!0)},[g,e]);l.useEffect(()=>{g&&qk(e,{groupAssignments:[...t.entries()],focusedGroup:r,groupActiveTabIds:o,groupTabOrders:u,groupSizes:p})},[g,e,t,r,o,u,p]),l.useEffect(()=>{const M=window.matchMedia("(max-width: 767px)"),A=T=>h(T.matches);return M.addEventListener("change",A),()=>M.removeEventListener("change",A)},[]);const y=l.useCallback(M=>{n(M)},[]),j=l.useCallback(M=>{a(M)},[]),x=l.useCallback(M=>{i(M)},[]),w=l.useCallback(M=>{c(M)},[]),N=l.useCallback(M=>{d(M)},[]),k=l.useCallback(M=>{j(M)},[j]),b=l.useCallback((M,A)=>{i(T=>(T[M]??null)===(A??null)?T:{...T,[M]:A})},[]),C=l.useCallback((M,A)=>{c(T=>{const L=T[M];return ej(L,A)?T:{...T,[M]:A}})},[]),S=l.useCallback((M,A)=>{const T=A.get(M)??0;return b(T,M),k(T),T},[k,b]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:y,focusedGroup:r,updateFocusedGroup:j,focusGroup:k,groupActiveTabIds:o,updateGroupActiveTabIds:x,setGroupActiveTab:b,groupTabOrders:u,updateGroupTabOrders:w,setGroupTabOrder:C,groupSizes:p,updateGroupSizes:N,isMobile:m,hasHydratedStoredLayout:g,hydrateStoredLayout:f,focusConversationTab:S}}function sj(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0],r=Ca(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function nj({urlActiveTab:e,conversations:t,resolveConversationBySessionId:n,normalizedGroupAssignments:r,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:u,historyModalOpen:c,activeConv:p,isRefreshingHistory:d,ides:m,handleRefreshHistory:h}){const g=l.useRef(!1),v=l.useRef(!1),f=l.useRef(null),y=l.useRef(!1);l.useEffect(()=>{if(!e||g.current||t.length===0)return;if(!a){o();return}const j=n(e);j&&(i(j.tabKey,r),g.current=!0,v.current=!0,f.current!=null&&(window.clearTimeout(f.current),f.current=null),u(x=>{const w=new URLSearchParams(x);return w.delete("activeTab"),w},{replace:!0}))},[e,t,n,r,a,o,i,u]),l.useEffect(()=>{if(!(v.current||a)&&t.length!==0){if(!e){o(),v.current=!0;return}if(g.current){v.current=!0;return}if(f.current==null)return f.current=window.setTimeout(()=>{f.current=null,!(v.current||a)&&(o(),v.current=!0)},1500),()=>{f.current!=null&&(window.clearTimeout(f.current),f.current=null)}}},[e,t.length,a,o]),l.useEffect(()=>{if(!c){y.current=!1;return}if(!p||y.current||d)return;const j=m.find(x=>x.id===p.routeId);j&&(!j.chats||j.chats.length===0||sj(j.chats,p))&&(y.current=!0,h())},[c,p,d,m,h])}function uo(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0];if((n==null?void 0:n.active)===!0)return!0;const r=Ca(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function Op({sendDaemonCommand:e,activeConv:t,chats:n,updateRouteChats:r,setToasts:a,setClearedTabs:o}){const[i,u]=l.useState(!1),[c,p]=l.useState(!1),d=l.useCallback(async v=>{try{await e("standalone","launch_ide",{ideType:v,enableCdp:!0})}catch(f){console.error("Launch failed",f)}},[e]),m=l.useCallback(async(v,f)=>{try{const y=v||(t==null?void 0:t.daemonId)||"",j=await e(y,"switch_chat",{id:f,sessionId:f,...Ws(t)}),x=j==null?void 0:j.result;if((j==null?void 0:j.success)===!0||x==="switched"||x==="switched-by-title")return;x===!1||x==="not_found"?on(a,"⚠️ Session tab not found — try refreshing history"):typeof x=="string"&&x.startsWith("error:")?on(a,`⚠️ Switch error: ${x}`):on(a,"⚠️ Session switch failed")}catch(y){console.error("Switch failed",y),on(a,`❌ Switch failed: ${y.message||"connection error"}`)}},[t,e,a]),h=l.useCallback(async()=>{if(!(!t||i)){u(!0);try{const v=Us(t);await e(v,"new_chat",{...Ws(t)}),Qv(v,t.sessionId,Ca(t)[0]),o(f=>({...f,[t.tabKey]:Date.now()}))}catch(v){console.error("New chat failed",v)}finally{u(!1)}}},[t,i,e,o]),g=l.useCallback(async()=>{var v,f;if(!(!t||c)){p(!0);try{const y=Us(t),j=async()=>e(y,"list_chats",{forceExpand:!0,...Ws(t)});let x=await j(),w=(x==null?void 0:x.chats)||((v=x==null?void 0:x.result)==null?void 0:v.chats);uo(w,t)&&(await new Promise(N=>setTimeout(N,450)),x=await j(),w=(x==null?void 0:x.chats)||((f=x==null?void 0:x.result)==null?void 0:f.chats)),x!=null&&x.success&&Array.isArray(w)&&(r(t.routeId,w),uo(w,t)&&!uo(n,t)&&on(a,"⚠️ History dialog did not fully open — try once more"))}catch(y){console.error("Refresh history failed",y)}finally{p(!1)}}},[t,n,c,e,r,a]);return{isCreatingChat:i,isRefreshingHistory:c,handleLaunchIde:d,handleSwitchSession:m,handleNewChat:h,handleRefreshHistory:g}}function rj(e,t){if(e.size!==t.size)return!1;for(const[n,r]of e)if(t.get(n)!==r)return!1;return!0}function aj(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function Lc(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(a=>t[Number(a)]===e[Number(a)])}function Tr(e,t){const n=new Set(t),r=t.length>0?[0]:[];for(const[i,u]of e)!n.has(i)||u<=0||r.includes(u)||r.push(u);r.sort((i,u)=>i-u);const a={};r.forEach((i,u)=>{a[i]=u}),r.length===0&&(a[0]=0);const o=new Map;for(const[i,u]of e){if(!n.has(i)||u<=0)continue;const c=a[u];typeof c=="number"&&c>0&&o.set(i,c)}return{assignments:o,groupCount:Math.max(1,r.length),mapping:a,usedGroups:r}}function Rc(e,t){const n={};for(const[r,a]of Object.entries(e)){const o=t[Number(r)];typeof o=="number"&&(n[o]=a)}return n}function oj(e,t,n){if(t.length===0)return 0;if(typeof n[e]=="number")return n[e];const r=[...t].reverse().find(a=>a<e)??t[0];return n[r]??0}function ij(e,t,n){if(t.length<=1)return[];const r=t.map(i=>e[i]).filter(i=>Number.isFinite(i)),a=r.length===t.length?r:Array(n).fill(100/n),o=a.reduce((i,u)=>i+u,0);return o>0?a.map(i=>i/o*100):Array(n).fill(100/n)}function _c(e,t){const n={};for(const[r,a]of Object.entries(e)){const o=Number(r);n[o>=t?o+1:o]=a}return n}function Ec(e){return Array(e).fill(100/e)}function lj({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:n,updateGroupActiveTabIds:r,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:i,isMobile:u,visibleConversations:c,visibleTabKeys:p}){const d=l.useRef(null),m=l.useMemo(()=>Tr(e,p),[e,p]),h=m.assignments,g=l.useMemo(()=>u?1:m.groupCount,[m.groupCount,u]),v=g>1,f=l.useCallback((k,b)=>{t(C=>{const S=new Map(Tr(C,p).assignments);return b===0?S.delete(k):S.set(k,b),S}),r(C=>({...C,[b]:k})),n(b)},[t,p,r,n]),y=l.useCallback(k=>{t(b=>{const C=Tr(b,p).assignments,S=new Map;for(const[M,A]of C)A!==k&&(A>k?S.set(M,A-1):S.set(M,A));return S}),i(b=>{if(b.length<=1)return[];const C=[...b];C.splice(k,1);const S=C.reduce((M,A)=>M+A,0);return S>0?C.map(M=>M/S*100):[]}),n(0)},[t,p,i,n]),j=l.useCallback((k,b)=>{b.preventDefault();const C=d.current;if(!C)return;const S=b.clientX,M=C.offsetWidth,A=o.length===g?[...o]:Ec(g),T=P=>{const z=(P.clientX-S)/M*100,R=[...A];R[k]=Math.max(15,A[k]+z),R[k+1]=Math.max(15,A[k+1]-z),i(R)},L=()=>{document.removeEventListener("mousemove",T),document.removeEventListener("mouseup",L),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",T),document.addEventListener("mouseup",L)},[o,g,i]),x=l.useCallback((k,b,C)=>{if(g>=4)return;const S=C==="left"?b:b+1;t(M=>{const A=Tr(M,p).assignments,T=new Map;for(const L of c){const P=A.get(L.tabKey)??0,B=P>=S?P+1:P;B>0&&T.set(L.tabKey,B)}return S>0&&T.set(k,S),T}),i(M=>{const A=M.length===g?[...M]:Ec(g),T=A[b]??100/g,L=Math.max(15,T/2),P=Math.max(15,T/2),B=[...A];B[b]=L,B.splice(S,0,P);const z=B.reduce((R,_)=>R+_,0);return B.map(R=>R/z*100)}),r(M=>{const A=_c(M,S);return A[S]=k,A}),a(M=>{const A=_c(M,S);return A[S]=[k],A}),n(S)},[g,t,p,c,i,r,a,n]);l.useEffect(()=>{rj(e,h)||t(h)},[e,h,t]),l.useEffect(()=>{const{mapping:k,usedGroups:b}=m;r(C=>{const S=Rc(C,k);return Lc(C,S)?C:S}),a(C=>{const S=Rc(C,k);return Lc(C,S)?C:S}),n(C=>{const S=u?0:oj(C,b,k);return C===S?C:S}),i(C=>{const S=u?[]:ij(C,b,m.groupCount);return aj(C,S)?C:S})},[m,u,r,a,n,i]);const w=l.useMemo(()=>{const k=Array.from({length:g},()=>[]);for(const b of c){const C=h.get(b.tabKey)??0,S=Math.min(C,g-1);k[S].push(b)}return k},[c,h,g]),N=l.useCallback(()=>{t(new Map),n(0)},[t,n]);return{containerRef:d,normalizedGroupAssignments:h,numGroups:g,isSplitMode:v,groupedConvs:w,moveTabToGroup:f,closeGroup:y,handleResizeStart:j,splitTabRelative:x,clearAllSplits:N}}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 cj(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 Pr(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:{},n=po(t.channel)||po(e.updateChannel)||po(e.releaseChannel)||void 0,r=cj(t.npmTag)||(n==="preview"?"next":n==="stable"?"latest":void 0),a=Pr(t.targetVersion)||Pr(e.serverVersion)||void 0,o=Pr(t.minVersion)||void 0,i=Pr(t.updateCommand)||(n?`adhdev update --channel ${n}`:void 0);return{...n?{channel:n}:{},...r?{npmTag:r}:{},...a?{targetVersion:a}:{},...o?{minVersion:o}:{},...i?{updateCommand:i}:{}}}function dn(e,t=null){return Zi(e).targetVersion||t}function Wp(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 dj({ides:e,sendDaemonCommand:t}){const n="0.9.82",r=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:qi(m,dn(m,n))).sort((m,h)=>Number(tr(h,dn(h,n)))-Number(tr(m,dn(m,n)))),[n,e]),a=l.useMemo(()=>r.some(m=>tr(m,dn(m,n))),[n,r]),o=l.useMemo(()=>r.map(m=>dn(m,n)).find(m=>typeof m=="string"&&m.trim().length>0)||n,[n,r]),[i,u]=l.useState(!1),[c,p]=l.useState({}),d=l.useCallback(async m=>{var g,v;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||(v=f==null?void 0:f.result)!=null&&v.success?p(y=>({...y,[m]:"done"})):p(y=>({...y,[m]:"error"}))}catch{p(f=>({...f,[m]:"error"}))}}},[e,t]);return{versionMismatchDaemons:r,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:u,upgradingDaemons:c,handleBannerUpgrade:d}}const Kp=80;function qr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function uj(e){return{...e,createdAt:qr(e.createdAt),updatedAt:qr(e.updatedAt,e.createdAt),lastEventAt:qr(e.lastEventAt,e.updatedAt||e.createdAt)}}function pj(e){const t=xu(e);return t==="unknown:"?e.id:t}function hj(e){return[e.type,fu(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function mj(e,t=Kp){const n=new Map;for(const r of e){if(r.deletedAt)continue;const a=pj(r),o=n.get(a);if(!o){n.set(a,r);continue}(r.updatedAt>o.updatedAt||r.updatedAt===o.updatedAt&&r.createdAt>o.createdAt)&&n.set(a,r)}return Array.from(n.values()).sort((r,a)=>{const o=a.updatedAt-r.updatedAt;return o!==0?o:a.createdAt-r.createdAt}).slice(0,Math.max(0,t))}function fj(e,t){const n=Date.now(),r=[];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),u=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!u)continue;const c=qr(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,n),p=hj({type:u,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(o==null?void 0:o.lastUpdated)||a.lastUpdated});r.push(uj({id:p,dedupKey:p,type:u,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Eu(a),preview:dv(a),createdAt:c,updatedAt:c,lastEventAt:c}))}return mj(r)}function xj(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function bj(e){const{conversations:t,liveSessionInboxState:n,maxItems:r=Kp}=e,a=l.useMemo(()=>fj(t,n).slice(0,Math.max(0,r)),[t,n,r]),o=l.useMemo(()=>xj(a),[a]);return{notifications:a,unreadCount:o}}function gj({notifications:e,sendDaemonCommand:t}){const n=l.useCallback(o=>{const i=e.find(c=>c.id===o),u=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:u}).catch(()=>{})},[e,t]),r=l.useCallback(o=>{const i=e.find(u=>u.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(u=>u.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:n,handleMarkDashboardNotificationUnread:r,handleDeleteDashboardNotification:a}}function el(...e){const t=new Set,n=[],r=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const i=o.toLowerCase();t.has(i)||(t.add(i),n.push(o))};for(const a of e){if(Array.isArray(a)){for(const o of a)r(o);continue}r(a)}return n}function yj(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 n=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(n){const r=n[1].toUpperCase(),a=(n[2]||"").replace(/[\\/]+/g,"\\");return a?`${r}:\\${a}`:`${r}:\\`}return null}function tl(e,t=[]){if(e==="win32"){for(const n of t){if(typeof n!="string")continue;const r=yj(n);if(r)return r}return"C:\\"}for(const n of t){const r=typeof n=="string"?n.trim():"";if(r)return r}return"~"}function vj(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const n=t.includes("\\")?"\\":"/",r=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(r[0]||"")?r.length<=2?`${r[0]}\\`:r.slice(0,-1).join("\\"):r.length<=2?n:r.slice(0,-1).join(n)||n}function wj(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function sl(e,t,n){const r=await e(t,"file_list_browse",{path:n}),a=wj(r);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(r==null?void 0:r.error)||"Could not browse folder");const o=typeof(a==null?void 0:a.path)=="string"?a.path:n,i=o.includes("\\")?"\\":"/",u=(p,d)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${d}`:p==="/"||p==="\\"?`${i}${d}`:`${p.replace(/[\\/]+$/,"")}${i}${d}`,c=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:u(o,p.name)})).sort((p,d)=>p.name.localeCompare(d.name)):[];return{path:o,directories:c}}function $c(e,t){const n=t.meshId||"",r={meshId:n,workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp",adhdevMcpArgs:t.adhdevMcpArgs||`mcp --mode ipc --repo-mesh ${n}`};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand|adhdevMcpArgs)\s*\}\}/g,(a,o)=>r[o]||"")}function Gp(e,t={}){const n=e==null?void 0:e.mcpConfig;if((n==null?void 0:n.mode)!=="manual")return null;const a=$c(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"}).trim();return!a.includes(`
65
- `)&&!a.startsWith("{")?null:{serverName:n.serverName||"adhdev-mesh",configFormat:n.format,configPathCommand:n.configPathCommand,requiresRestart:n.requiresRestart===!0,instructions:n.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:$c(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function kj(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.instructions=="string"?t.instructions:"",r=typeof t.template=="string"?t.template:"";return!n&&!r?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:n||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:r}}function dr(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function zp(e){return Ma(e)||e.tabKey||e.routeId||null}function Vp(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",n=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",r=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",a=e.conversations.find(o=>{if(r&&o.routeId!==r)return!1;const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(u=>typeof u=="string"?u.trim():"").filter(Boolean);return!!(t&&i.includes(t)||n&&i.includes(n)||r&&o.routeId===r)});if(a!=null&&a.tabKey)return a.tabKey;if(r){const o=cs(e.conversations,r)||e.conversations.find(i=>i.routeId===r);if(o!=null&&o.tabKey)return o.tabKey}return t||n||r||null}function Cs(e){return String(e||"").trim()}function qp(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 jj(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Sj(e,t){const n=Cs(e.providerSessionId),r=Cs(e.targetSessionId),a=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Cs).filter(Boolean);return!!(n&&i.includes(n)||r&&i.includes(r))});return a?a.tabKey:r||n||null}function Nj(e,t,n){if(t.event!=="agent:generating_completed")return null;const r=qp(t.daemonId);if(r&&r!==e.machineId)return null;const a=Cs(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=Cs(e.resumeSessionId),i=Cs(e.launchedSessionId),u=Cs(t.providerSessionId),c=Cs(t.targetSessionId);if(o&&o!==u&&o!==c||i&&i!==u&&i!==c)return null;const p=ba(e.workspacePath);if(p){const d=ba(t.workspaceName);if(d&&!jj(d,p))return null}return Sj(t,n)}function Fc(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Cj({ides:e,conversations:t,onOpenSession:n}){const[r,a]=l.useState(null),o=l.useRef(null),i=l.useCallback(()=>{o.current=null,a(null)},[]),u=l.useCallback(c=>{o.current=c,a(c)},[]);return l.useEffect(()=>{if(!r)return;const c=ba(r.workspacePath),p=e.find(m=>{var y,j,x,w;if(!m||m.type==="adhdev-daemon"||qp(m.daemonId||m.id)!==r.machineId||(ir(m)?"cli":hn(m)?"acp":"ide")!==r.kind)return!1;const v=String(m.agentType||m.type||"");if(r.providerType&&v!==r.providerType)return!1;if(r.resumeSessionId)return String(m.providerSessionId||"")===r.resumeSessionId;if(r.launchedSessionId){const N=String(r.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(b=>String(b||"")).filter(Boolean).includes(N)}if(c){const N=ba(m.workspace||m.runtimeWorkspaceLabel);return N?N===c:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((w=(x=(j=(y=m.activeChat)==null?void 0:y.messages)==null?void 0:j.at)==null?void 0:x.call(j,-1))==null?void 0:w.timestamp)||0)>=r.startedAt-5e3});if(!p)return;const d=Vp({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});d&&(i(),n(d))},[i,t,e,n,r]),l.useEffect(()=>ht.onStatusEvent(c=>{const p=o.current;if(!p)return;const d=Nj(p,c,t);d&&(i(),n(d))}),[i,t,n]),l.useEffect(()=>{if(!r)return;const c=window.setTimeout(()=>{a(p=>!p||p.startedAt!==r.startedAt?p:(o.current=null,null))},45e3);return()=>window.clearTimeout(c)},[r]),{trackPendingLaunch:u}}function Mj({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:r,ides:a,setCliViewModeOverrides:o}){const i=Fi(),{launchCli:u}=wa(),c=l.useCallback(async(y,j)=>sl(e,y,j),[e]),p=l.useCallback(async(y,j)=>{if(!j.trim())return{ok:!1,error:"Choose a workspace path first."};try{const x=await e(y,"workspace_add",{path:j.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]),d=l.useCallback(async(y,j,x)=>{var w;try{const N={ideType:j,enableCdp:!0};(w=x==null?void 0:x.workspacePath)!=null&&w.trim()&&(N.workspace=x.workspacePath.trim());const k=await e(y,"launch_ide",N);return!(k!=null&&k.success)&&(k==null?void 0:k.success)!==void 0?{ok:!1,error:(k==null?void 0:k.error)||"Could not launch IDE"}:(t({machineId:y,kind:"ide",providerType:j,workspacePath:(x==null?void 0:x.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(N){return{ok:!1,error:N instanceof Error?N.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(y,j,x,w)=>{var k,b,C,S;const N=Date.now();try{const M={cliType:x};(k=w==null?void 0:w.workspacePath)!=null&&k.trim()?M.dir=w.workspacePath.trim():w!=null&&w.workspaceId&&(M.workspaceId=w.workspaceId),(b=w==null?void 0:w.resumeSessionId)!=null&&b.trim()&&(M.resumeSessionId=w.resumeSessionId.trim()),Array.isArray(w==null?void 0:w.cliArgs)&&w.cliArgs.length>0&&(M.cliArgs=w.cliArgs),(C=w==null?void 0:w.initialModel)!=null&&C.trim()&&(M.initialModel=w.initialModel.trim()),(S=w==null?void 0:w.initialThinkingLevel)!=null&&S.trim()&&(M.initialThinkingLevel=w.initialThinkingLevel.trim());const A=await u(y,M),T=(A==null?void 0:A.result)||A,L=(T==null?void 0:T.sessionId)||(T==null?void 0:T.id);return A!=null&&A.success&&L?(t({machineId:y,kind:j,providerType:x,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,launchedSessionId:L,startedAt:N}),{ok:!0}):A!=null&&A.success?(t({machineId:y,kind:j,providerType:x,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,startedAt:N}),{ok:!0}):{ok:!1,error:(A==null?void 0:A.error)||(T==null?void 0:T.error)||`Could not launch ${j.toUpperCase()} session`}}catch(M){return Fc(M)?(t({machineId:y,kind:j,providerType:x,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,startedAt:N}),{ok:!0}):{ok:!1,error:M instanceof Error?M.message:`Could not launch ${j.toUpperCase()} session`}}},[u,e,t]),h=l.useCallback(async y=>{var j;if(i!=null&&i.listMeshes)return i.listMeshes(y);if(!y)return[];try{const x=await e(y,"list_meshes",{}),w=(x==null?void 0:x.result)??x;if((w==null?void 0:w.success)===!1)throw new Error((w==null?void 0:w.error)||"Could not load meshes");return(Array.isArray(w==null?void 0:w.meshes)?w.meshes:Array.isArray((j=w==null?void 0:w.result)==null?void 0:j.meshes)?w.result.meshes:[]).map(k=>{var b;return{id:String((k==null?void 0:k.id)||""),name:String((k==null?void 0:k.name)||(k==null?void 0:k.id)||"Untitled mesh"),repoIdentity:(k==null?void 0:k.repoIdentity)||(k==null?void 0:k.repo_identity)||null,workspace:Array.isArray(k==null?void 0:k.nodes)&&k.nodes.length>0?String(((b=k.nodes[0])==null?void 0:b.workspace)||""):null,nodesCount:Array.isArray(k==null?void 0:k.nodes)?k.nodes.length:void 0,status:(k==null?void 0:k.status)||null}}).filter(k=>k.id)}catch(x){throw console.error("List meshes failed",x),x}},[i,e]),g=l.useCallback(async(y,j,x,w)=>{var k,b;if(!j.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(y,j,x,w);const N=Date.now();try{const C={meshId:j.trim()};x.trim()&&(C.cliType=x.trim());const S=(k=w==null?void 0:w.initialModel)==null?void 0:k.trim(),M=(b=w==null?void 0:w.initialThinkingLevel)==null?void 0:b.trim();S&&(C.initialModel=S),M&&(C.initialThinkingLevel=M);const A=await e(y,"launch_mesh_coordinator",C),T=(A==null?void 0:A.result)??A;if((T==null?void 0:T.success)===!1||(A==null?void 0:A.success)===!1){const P=String((T==null?void 0:T.code)||(A==null?void 0:A.code)||""),B=kj((T==null?void 0:T.meshCoordinatorSetup)||(T==null?void 0:T.manualSetup)||(A==null?void 0:A.meshCoordinatorSetup)||(A==null?void 0:A.manualSetup));return{ok:!1,error:(T==null?void 0:T.error)||(A==null?void 0:A.error)||"Could not launch mesh coordinator",code:P||void 0,manualSetup:B}}const L=(T==null?void 0:T.sessionId)||(T==null?void 0:T.id);return L?n(L):t({machineId:y,kind:"cli",providerType:(T==null?void 0:T.cliType)||x.trim()||void 0,workspacePath:(T==null?void 0:T.workspace)||null,startedAt:N}),{ok:!0}}catch(C){return Fc(C)?(t({machineId:y,kind:"cli",providerType:x.trim()||void 0,startedAt:N}),{ok:!0}):{ok:!1,error:C instanceof Error?C.message:"Could not launch mesh coordinator"}}},[i,n,e,t]),v=l.useCallback(async(y,j)=>{if(!y||!j)return[];try{const x=await e(y,"list_saved_sessions",{providerType:j,kind:"cli",limit:30}),w=(x==null?void 0:x.result)??x;return Array.isArray(w==null?void 0:w.sessions)?w.sessions:[]}catch(x){return console.error("List saved sessions failed",x),[]}},[e]),f=l.useCallback(async y=>{await _p({conversation:r,mode:y,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[r,a,e,o]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:p,handleLaunchMachineIde:d,handleLaunchMachineProvider:m,handleListMachineMeshes:h,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:v,setActiveCliViewMode:f}}function Aj(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 Ij(e,t,n=Date.now()){return!e||!Aj(t)?null:{tabKey:e,nonce:n}}function Tj({isMobile:e,conversations:t,visibleConversations:n,groupActiveTabIds:r,focusedGroup:a,groupedConvs:o,setSearchParams:i}){const[u,c]=l.useState(null),[p,d]=l.useState(null),m=l.useMemo(()=>{var y,j;if(!e){if(u){const x=t.find(w=>w.tabKey===u);if(x)return x}return n[0]}const f=r[a];if(f){const x=t.find(w=>w.tabKey===f);if(x)return x}return((y=o[a])==null?void 0:y[0])||((j=o[0])==null?void 0:j[0])},[t,u,a,r,o,e,n]),h=l.useCallback(f=>{c(f)},[]),g=l.useCallback(f=>{c(f.tabKey),i(y=>{const j=new URLSearchParams(y),x=pv(f);return x?j.set("activeTab",x):j.delete("activeTab"),j},{replace:!0})},[i]),v=l.useCallback((f,y)=>{const j=Ij(f,y);j&&d(j)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:v,scrollToBottomRequest:p,setDesktopActiveTab:h}}function Pj(e){const t=e.completedKey||null,n=e.pendingKey||null;return e.shouldMarkSeen?t===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:n!==null&&n!==e.autoReadKey,nextPendingKey:n===e.autoReadKey?n:null}:n===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:n}:{shouldSchedule:!0,shouldCancelPending:n!==null&&n!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!n,nextPendingKey:null}}function Dj(e){const t=String(e.liveState.completionMarker||""),n=String(e.liveState.seenCompletionMarker||""),r=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",t,n,r,a?"1":"0"].join(":");return{shouldMarkSeen:!!(r==="task_complete"&&a&&(!t||t!==n)),autoReadKey:o,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function Lj({activeConv:e,isMobile:t,liveSessionInboxState:n,sendDaemonCommand:r}){const a=l.useRef(null),o=l.useRef(null),i=l.useRef(null),u=l.useRef(null),c=l.useRef(null);l.useEffect(()=>{const p=()=>{i.current&&(clearTimeout(i.current),i.current=null),u.current&&(clearTimeout(u.current),u.current=null),c.current&&(document.removeEventListener("visibilitychange",c.current),c.current=null),o.current=null};if(t){p(),a.current=null;return}if(!(e!=null&&e.sessionId)){p(),a.current=null;return}const d=Ps(e,n),m=Dj({tabKey:e.tabKey,historySessionId:Ma(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:Vs(e),liveState:d}),h=m.autoReadKey,g=Pj({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 v=()=>{if(document.visibilityState!=="visible"||a.current===h)return;a.current=h,o.current=null,i.current=null,u.current=null,c.current&&(document.removeEventListener("visibilitychange",c.current),c.current=null);const y=m.readAt;r(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:y,completionMarker:m.completionMarker}).catch(()=>{})};if(o.current=g.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(v,1500);const y=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};c.current=y,document.addEventListener("visibilitychange",y);return}const f=()=>{document.visibilityState==="visible"&&(u.current&&clearTimeout(u.current),u.current=setTimeout(v,800),c.current&&(document.removeEventListener("visibilitychange",c.current),c.current=null))};c.current=f,document.addEventListener("visibilitychange",f)},[e,t,n,r]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),u.current&&clearTimeout(u.current),c.current&&document.removeEventListener("visibilitychange",c.current)},[])}function ho(e){if(!e)return"";const t=String(e.workspacePath||"").trim();if(t)return t;const n=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(n)?n:""}function Rj({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:r,sendDaemonCommand:a,updateRouteChats:o,setToasts:i,setClearedTabs:u,setSearchParams:c}){var K;const{launchCli:p}=wa(),[d,m]=l.useState(!1),[h,g]=l.useState([]),[v,f]=l.useState(()=>Bt()),[y,j]=l.useState(!1),[x,w]=l.useState(null),N=l.useRef(null),k=l.useMemo(()=>n||t||e,[e,n,t]),b=!!k&&ct(k)&&!lt(k),C=l.useMemo(()=>{if(!k||!b)return null;const E=k.daemonId||k.routeId||"",D=xs(k),$=ho(k);return`${E}:${D}:${k.providerSessionId||""}:${$}`},[k,b]),S=l.useMemo(()=>!k||!b?"":ho(k),[k,b]),{isCreatingChat:M,isRefreshingHistory:A,handleSwitchSession:T,handleNewChat:L,handleRefreshHistory:P}=Op({sendDaemonCommand:a,activeConv:k,chats:(K=r.find(E=>E.id===(k==null?void 0:k.routeId)))==null?void 0:K.chats,updateRouteChats:o,setToasts:i,setClearedTabs:u}),B=l.useCallback(()=>{m(!0)},[]),z=l.useCallback(()=>{m(!1)},[]),R=l.useCallback(async()=>{if(!(!k||!b||y)){j(!0);try{const E=k.daemonId||k.routeId,D=xs(k),$=ho(k),I=await a(E,"list_saved_sessions",{agentType:D,providerType:D,kind:"cli",limit:50,...k.providerSessionId?{providerSessionId:k.providerSessionId}:{},...$?{workspace:$}:{}}),G=(I==null?void 0:I.result)??I;g(Array.isArray(G==null?void 0:G.sessions)?G.sessions:[])}catch(E){console.error("Refresh saved sessions failed",E),g([])}finally{j(!1)}}},[k,y,b,a]);l.useEffect(()=>{if(!d){N.current=null;return}if(!b){N.current=null,g([]),j(!1);return}!C||y||N.current!==C&&(N.current=C,R())},[R,d,y,b,C]);const _=l.useCallback(async E=>{if(!k||!b||!E.providerSessionId||!E.workspace)return;const D=k.daemonId||k.routeId,$=xs(k);try{w(E.providerSessionId);const I=await p(D,{cliType:$,dir:E.workspace,resumeSessionId:E.providerSessionId,initialModel:wu(E.summaryMetadata,"model",{preferShortValue:!0})||void 0}),G=(I==null?void 0:I.result)??I,Y=typeof(G==null?void 0:G.sessionId)=="string"?G.sessionId:typeof(G==null?void 0:G.id)=="string"?G.id:"";Y&&c(Z=>{const q=new URLSearchParams(Z);return q.set("activeTab",Y),q},{replace:!0}),z()}catch(I){console.error("Resume saved session failed",I)}finally{w(null)}},[z,k,b,a,c]);return{historyModalOpen:d,openHistoryModal:B,closeHistoryModal:z,historyTargetConv:k,isSavedSessionHistoryTarget:b,isHistoryCreatingChat:M,isHistoryRefreshingHistory:A,handleHistorySwitchSession:T,handleHistoryNewChat:L,handleHistoryRefresh:P,savedHistorySessions:h,savedHistoryFilters:v,setSavedHistoryFilters:f,missingWorkspaceResumePath:S,isSavedHistoryLoading:y,resumingSavedHistorySessionId:x,handleRefreshSavedHistory:R,handleResumeSavedHistorySession:_}}function _j({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:u}){const[c,p]=l.useState(null),[d,m]=l.useState(null),h=l.useMemo(()=>{if(e||!r)return null;const j=u(r);return j&&!ct(j)&&!lt(j)?j:null},[e,r,u]),g=l.useMemo(()=>{const j=c==null?void 0:c.routeId;if(!j)return null;const x=c!=null&&c.tabKey?o.find(w=>w.tabKey===c.tabKey):a?o.find(w=>w.tabKey===a):null;return(x==null?void 0:x.routeId)===j?x:cs(o,j)},[o,c,a]),v=l.useMemo(()=>{if(g)return i.find(j=>j.id===g.routeId)},[i,g]);l.useEffect(()=>{h&&(p({routeId:h.routeId,tabKey:ec(h)}),m(h),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,h]);const f=l.useCallback(j=>{j&&(p({routeId:j.routeId,tabKey:ec(j)}),m(j))},[]),y=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:v,remoteDialogActiveConv:d,setRemoteDialogActiveConv:m,openRemoteDialog:f,closeRemoteDialog:y}}function Ej({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:u,activeConv:c,sendDaemonCommand:p}){const{remoteDialogConv:d,remoteDialogIdeEntry:m,remoteDialogActiveConv:h,setRemoteDialogActiveConv:g,openRemoteDialog:v,closeRemoteDialog:f}=_j({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:u}),[y,j]=l.useState(!1),[x,w]=l.useState(null),N=l.useCallback(async C=>{const S=C||c;!S||!ct(S)&&!lt(S)||(w(S),j(!0))},[c]),k=l.useCallback(()=>{j(!1),w(null)},[]),b=l.useCallback(async C=>{const S=x||c;if(!S||!ct(S)&&!lt(S)){k();return}j(!1);try{const M=xs(S),A=S.routeId||S.daemonId||"";await p(A,"stop_cli",{cliType:M,targetSessionId:S.sessionId,mode:C,...Ta(S)})}catch(M){console.error("Stop CLI failed:",M)}finally{w(null)}},[c,k,x,p]);return{remoteDialogConv:d,remoteDialogIdeEntry:m,remoteDialogActiveConv:h,setRemoteDialogActiveConv:g,openRemoteDialog:v,closeRemoteDialog:f,cliStopDialogOpen:y,cliStopTargetConv:x,requestCliStop:N,cancelCliStop:k,confirmCliStop:b}}function mo(e,t=!0){return(e??!0)&&t}const nl=l.memo(function({activeConv:t,clearToken:n,isCliTerminal:r,ideEntry:a,terminalRef:o,handleModalButton:i,handleRelaunch:u,handleSendChat:c,handleForceSendChat:p,isSendingChat:d,sendFeedbackMessage:m=null,handleFocusAgent:h,isFocusingAgent:g,actionLogs:v,userName:f,scrollToBottomRequestNonce:y,isInputActive:j=!0,isVisible:x=!0}){const w=r,N=!r,k=mo(x,w),b=mo(x,N),C=mo(x),S=Dp(t),M=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:M,onModalButton:i}),M.transport!=="pty"&&M.transport!=="acp"&&M.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:u,children:"Relaunch with CDP"})]})}):null,M.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:w?"visible":"hidden",pointerEvents:w?"auto":"none"},children:s.jsx(K0,{activeConv:M,clearToken:n,terminalRef:o,handleSendChat:c,isSendingChat:d,sendFeedbackMessage:m,isVisible:k,isInputActive:j&&k})}),s.jsx("div",{"aria-hidden":r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:N?"visible":"hidden",pointerEvents:N?"auto":"none"},children:s.jsx(ri,{activeConv:M,ideEntry:a,handleSendChat:c,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:g,actionLogs:v,userName:f,scrollToBottomRequestNonce:y,isInputActive:j&&b,isVisible:b})})]}):s.jsx(ri,{activeConv:M,ideEntry:a,handleSendChat:c,handleForceSendChat:p,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:g,actionLogs:v,userName:f,scrollToBottomRequestNonce:y,isInputActive:j&&C,isVisible:C})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.handleForceSendChat===t.handleForceSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function $j({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:r,interactive:a=!0,meshOnly:o=!1}){var w,N,k;const i=hr(),u=Ds(e),c=o?null:_u(e),p=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),d=!o&&e.streamSource==="agent-stream"&&!!e.agentName,m=!o&&!d&&(e.transport==="pty"||e.transport==="acp"),h=yn(e),g=uv(e),v=(w=e.settings)==null?void 0:w.meshNodeFor,f=e.meshQueueStats,y=((N=e.coordinator)==null?void 0:N.meshId)||((k=e.settings)==null?void 0:k.meshCoordinatorFor),j=l.useCallback(()=>{if(r){r();return}u&&i("/dashboard",{state:{openMachineId:u}})},[u,i,r]),x=l.useCallback(()=>{if(n){n();return}const b=zp(e);b&&i(dr(b))},[e,i,n]);return!p&&!d&&!m&&!c&&!v&&!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(us,{size:12}),s.jsx("span",{children:g})]}):s.jsxs("span",{className:"conversation-meta-chip",title:g,children:[s.jsx(us,{size:12}),s.jsx("span",{children:g})]})),d&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(or,{size:12}),s.jsx("span",{children:h})]}),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(or,{size:12}),s.jsx("span",{children:h})]}),c&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:j,title:c,children:[s.jsx(Is,{size:12}),s.jsx("span",{children:c})]}):s.jsxs("span",{className:"conversation-meta-chip",title:c,children:[s.jsx(Is,{size:12}),s.jsx("span",{children:c})]})),v&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Is,{size:12}),s.jsx("span",{children:"Mesh Node"})]}),y&&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(Rf,{size:12}),s.jsxs("span",{children:[f.pending," Pending"]})]})]})}function Fj({selectedConversation:e,isAcp:t,isStandalone:n,selectedIdeEntry:r,actionLogs:a,userName:o,isSendingChat:i,sendFeedbackMessage:u=null,isFocusingAgent:c,onBack:p,onOpenNativeConversation:d,onOpenMachine:m,onOpenHistory:h,onOpenRemote:g,onOpenMeshGraph:v,onStopCli:f,cliViewMode:y,onSetCliViewMode:j,handleSendChat:x,handleForceSendChat:w,handleFocusAgent:N,handleModalButton:k,handleRelaunch:b}){var L,P;const C=l.useRef(null),S=ct(e)&&!t,M=S&&y==="terminal",A=!!e.daemonId&&!!((L=e.coordinator)!=null&&L.meshId||(P=e.settings)!=null&&P.meshCoordinatorFor),T=n?"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 ${T} 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:gt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx($j,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[S&&y&&s.jsx(up,{mode:y,onChange:j,compact:!0}),S&&f&&s.jsx("button",{onClick:()=>{f(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(Mt,{size:14})}),A&&v&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>v(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(es,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>h(e),type:"button",children:s.jsx(Mi,{size:14})}),!t&&!S&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:s.jsx(us,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(nl,{activeConv:e,clearToken:0,isCliTerminal:M,ideEntry:r,terminalRef:C,handleModalButton:k,handleRelaunch:b,handleSendChat:x,handleForceSendChat:w,isSendingChat:i,sendFeedbackMessage:u,handleFocusAgent:N,isFocusingAgent:c,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 Bj(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Yp(){const[e,t]=l.useState("unix"),[n,r]=l.useState("powershell"),[a,o]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(Bj())},[]);const u=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 ${n==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>r("powershell"),children:"⚡ PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>r("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:u,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 Jp({section:e,onSectionChange:t}){const n=[{key:"machines",label:"Machines",icon:us},{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:n.map(({key:r,label:a,icon:o})=>{const i=e===r;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(r),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})]},r)})})})}function Dr({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 nn({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 On({icon:e,title:t,subtitle:n,children:r}){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:n}),r]})}function Hj({conversation:e,onCancel:t,onConfirm:n}){const{t:r}=Xe(),a=gt(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:r("mobileInbox.hideTitle",{title:a})}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:r("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:n,className:"btn btn-primary w-full justify-center min-h-[42px]",children:r("mobileInbox.hide")}),s.jsx("button",{onClick:t,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:r("common.cancel")})]})]})]})}function Lr({item:e,type:t,getAvatarText:n,onOpenConversation:r,onRequestHideConversation:a,onRequestStopCli:o,onOpenMeshGraph:i,onCollectChatDebugBundle:u,isMuted:c,onToggleMute:p}){const{t:d}=Xe(),m=t==="needs_attention"||t==="task_complete",h=t==="working",g=t==="earlier",v=t==="task_complete",{isReconnecting:f,isConnecting:y}=Mn(e.conversation),j=gt(e.conversation),x=vn(e.conversation),w=ip(e.conversation,{requiresAction:t==="needs_attention"}),N=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",k=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",C=g?"text-text-muted":"text-text-secondary",S=g?"text-text-secondary opacity-80":"text-text-muted",M=g?"text-text-muted opacity-80":"text-text-muted",A=!h&&!v,T=ap(e.conversation),L="text-[color:var(--status-warning)]",P=B=>{if(!u)return;B.preventDefault(),B.stopPropagation();const z=u==null?void 0:u(e.conversation);Promise.resolve(z).catch(R=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",R)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${N}`,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 ${k}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:n(j)}),T&&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:B=>{B.preventDefault(),B.stopPropagation(),i(e.conversation)},"aria-label":d("mobileInbox.openMeshGraphFor",{title:j}),title:d("mobileInbox.openLiveMeshGraph"),children:s.jsx(es,{size:13})})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>r(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:j})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${C}`,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:`${L} animate-pulse`,children:d("mobileInbox.reconnectingItem")})]}):y?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:d("mobileInbox.connectingItem")})]}):w==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:L,children:d("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:[A&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${M}`,children:du(e.timestamp)}),v&&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:d("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 ${c?"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:B=>{B.preventDefault(),B.stopPropagation(),p()},"aria-label":c?d("mobileInbox.unmute",{title:j}):d("mobileInbox.mute",{title:j}),title:d(c?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:c?s.jsx(Qd,{size:13}):s.jsx(Cn,{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:B=>{B.preventDefault(),B.stopPropagation(),a()},"aria-label":d("mobileInbox.hideConversationAria",{title:j}),title:d("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:B=>{B.preventDefault(),B.stopPropagation(),o()},"aria-label":d("mobileInbox.stopSessionAria",{title:j}),title:d("mobileInbox.stopSessionTitle"),children:s.jsx(Mt,{size:13})})]})]})},e.conversation.tabKey)}function Bc({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 Oj({section:e,attentionItems:t,unreadItems:n,workingItems:r,completedItems:a,hiddenConversations:o,machineCards:i,getAvatarText:u,actionLogs:c,sendDaemonCommand:p,onOpenConversation:d,onShowAllHidden:m,onHideConversation:h,onOpenMeshGraph:g,onStopCli:v,onOpenNewSession:f,onOpenMachine:y,onOpenSettings:j,onSectionChange:x,wsStatus:w="connected",isStandalone:N=!1,onCollectChatDebugBundle:k,isConversationMuted:b,onToggleMuteConversation:C}){const{t:S}=Xe(),[M,A]=l.useState(null),T=w==="disconnected"||w==="reconnecting"||w==="offline"||w==="auth_failed",L=i.length>0,P=t.length>0||n.length>0||r.length>0||a.length>0,B=S(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),z=N?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",R=N?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",_=l.useCallback(async D=>{const $=Us(D);if(!$)return;const I=Array.isArray(D.messages)?D.messages:[],G=Ou({activeConv:D,visibleMessages:I,actionLogs:c,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:I.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),Y=await p($,"get_chat_debug_bundle",{...Ws(D),delivery:"daemon_file",frontendSnapshot:G}),Z=er(Y),q=Ku(Z),ne=await Uu(q);ne==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ht.showToast(Wu(Z,{locatorCopyStatus:ne}),ne==="failed"?"warning":"success")},[c,p]),K=k||_,E=l.useCallback(()=>{M&&(h==null||h(M),A(null))},[M,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 ${z}`,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:B}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||n.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(Cn,{size:13}),s.jsx("span",{children:t.length+n.length})]}),s.jsx("button",{onClick:j,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(ka,{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] ${R}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:T?s.jsx(On,{icon:s.jsx(Bc,{}),title:S(w==="offline"?"mobileInbox.networkOffline":w==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:S(w==="offline"?"mobileInbox.waitingForNetwork":w==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):i.length===0?s.jsx(On,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:S(N?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:S(N?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!N&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Yp,{})})}):s.jsx(nn,{children:i.map((D,$)=>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] ${$>0?"border-t border-border-subtle/70":""}`,onClick:()=>y(D.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:u(D.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:D.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:D.unread>0?s.jsx("span",{className:"text-accent-primary",children:S("mobileInbox.newCount",{count:D.unread})}):D.total>0?S("mobileInbox.chatCount",{count:D.total}):S("mobileInbox.idle")})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:D.subtitle}),D.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[S("mobileInbox.chatCount",{count:D.total}),D.unread>0?S("mobileInbox.unreadSuffix",{count:D.unread}):""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:S("mobileInbox.noActiveChats")})]})]},D.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(Dr,{title:S("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(nn,{children:t.map((D,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:D,type:"needs_attention",getAvatarText:u,onOpenConversation:d,onRequestHideConversation:h?()=>A(D.conversation):void 0,onRequestStopCli:v?()=>v(D.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:K,isMuted:b==null?void 0:b(D.conversation),onToggleMute:C?()=>C(D.conversation):void 0})},D.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(Dr,{title:S("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(nn,{children:n.map((D,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:D,type:"task_complete",getAvatarText:u,onOpenConversation:d,onRequestHideConversation:h?()=>A(D.conversation):void 0,onRequestStopCli:v?()=>v(D.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:K,isMuted:b==null?void 0:b(D.conversation),onToggleMute:C?()=>C(D.conversation):void 0})},D.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(Dr,{title:S("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(nn,{children:r.map((D,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:D,type:"working",getAvatarText:u,onOpenConversation:d,onRequestHideConversation:h?()=>A(D.conversation):void 0,onRequestStopCli:v?()=>v(D.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:K,isMuted:b==null?void 0:b(D.conversation),onToggleMute:C?()=>C(D.conversation):void 0})},D.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(Dr,{title:S("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(nn,{children:a.map((D,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:D,type:"earlier",getAvatarText:u,onOpenConversation:d,onRequestHideConversation:h?()=>A(D.conversation):void 0,onRequestStopCli:v?()=>v(D.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:K,isMuted:b==null?void 0:b(D.conversation),onToggleMute:C?()=>C(D.conversation):void 0})},D.conversation.tabKey))}):P?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:S("mobileInbox.allCaughtUp")}):T?s.jsx(On,{icon:s.jsx(Bc,{size:28}),title:S("mobileInbox.connecting"),subtitle:S("mobileInbox.connectingSubtitle")}):L?s.jsx(On,{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:Y0,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(On,{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(nn,{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"})]})}),M&&s.jsx(Hj,{conversation:M,onCancel:()=>A(null),onConfirm:E}),s.jsx(Jp,{section:e,onSectionChange:x})]})}function Wj(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 Xp(e){const t=[e.workspace||"Workspace unknown"],n=Js(e.summaryMetadata);n&&t.push(n),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const r=Wj(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:r?`Updated ${r}`:"",preview:(e.preview||"").trim()}}function rl({title:e,description:t,currentPath:n,directories:r,busy:a=!1,error:o="",confirmLabel:i="Use this folder",onClose:u,onNavigate:c,onConfirm:p}){const[d,m]=l.useState(n);l.useEffect(()=>{m(n)},[n]);const h=vj(n),g=d.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:u,"aria-label":"Close folder browser",children:s.jsx(Mt,{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||c(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:d,onChange:v=>m(v.target.value),onKeyDown:v=>{v.key!=="Enter"||!g||a||(v.preventDefault(),c(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||c(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}):r.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:r.map(v=>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:()=>c(v.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(gn,{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:v.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:v.path})]})]},v.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:u,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(g||n),disabled:!g&&!n||a,children:i})]})]})})}function Qp({title:e,description:t,details:n,workspaceOptions:r,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:i="Launch",busyLabel:u="Launching…",busy:c=!1,showArgsInput:p,argsValue:d,onArgsChange:m,showModelInput:h,modelValue:g,onModelChange:v,historyProviderNode:f,onConfirm:y,onCancel:j}){const x=r==null?void 0:r.find(w=>w.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:j,"aria-label":"Close launch confirmation",children:s.jsx(Mt,{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:[r&&r.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),s.jsx("select",{value:a||"",onChange:w=>o(w.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:c,children:r.map(w=>s.jsx("option",{value:w.key,children:w.label},w.key))}),(x==null?void 0:x.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:x.description})]}),f,n.map(w=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:w.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:w.value})]},`${w.label}:${w.value}`)),h&&v&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:g||"",onChange:w=>v(w.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:c})]}),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:d||"",onChange:w=>m(w.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:c})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:j,disabled:c,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:y,disabled:c,children:[s.jsx(Xd,{size:14}),c?u:i]})]})]})})}function Hc(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Zp(e){const{machine:t,currentWorkspacePath:n,currentWorkspaceId:r,includeHome:a=!0}=e,o=[];a&&o.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const c of t.workspaces||[])o.push({key:`saved:${c.id}`,label:`${c.id===t.defaultWorkspaceId?"⭐ ":""}${Hc(c.path,c.label)}`,description:c.path,workspaceId:c.id,workspacePath:c.path});const i=(n==null?void 0:n.trim())||"",u=i?(t.workspaces||[]).find(c=>c.path===i):null;if(i&&!u&&o.push({key:`custom:${i}`,label:Hc(i),description:i,workspaceId:null,workspacePath:i}),r){const c=`saved:${r}`;if(o.some(p=>p.key===c))return{options:o,selectedKey:c}}return u?{options:o,selectedKey:`saved:${u.id}`}:i?{options:o,selectedKey:`custom:${i}`}:{options:o,selectedKey:"__home__"}}function Uj(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Kj(e){return[Uj(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Gj(e){return e.lastLaunchedAt?Sa(e.lastLaunchedAt):""}function eh(e){return{metaText:Kj(e),updatedLabel:Gj(e)}}function xo(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function zj({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:r,onBrowseDirectory:a,onListSavedSessions:o}){var he,Ee,Fe,Ie;const i=In(),[u,c]=l.useState(!1),p=(((he=e.detectedIdes)==null?void 0:he.length)||0)>0,d=l.useMemo(()=>(e.workspaces||[]).map(ve=>({id:ve.id,path:ve.path,label:ve.label})),[e]),m=e.defaultWorkspaceId||null,[h,g]=l.useState(m||((Ee=d[0])==null?void 0:Ee.id)||""),[v,f]=l.useState(""),[y,j]=l.useState(""),[x,w]=l.useState([]),[N,k]=l.useState(!1),[b,C]=l.useState(""),[S,M]=l.useState(!1),[A,T]=l.useState(xo(p,t.length,n.length)),L=l.useRef(null),[P,B]=l.useState(null),z=l.useRef("__home__"),[R,_]=l.useState("__home__"),[K,E]=l.useState(""),[D,$]=l.useState(""),[I,G]=l.useState(""),[Y,Z]=l.useState([]),[q,ne]=l.useState(()=>Bt().textQuery),[ue,ae]=l.useState(()=>Bt().workspaceQuery),[O,se]=l.useState(()=>Bt().modelQuery),[X,oe]=l.useState(()=>Bt().resumableOnly),[Se,ye]=l.useState(()=>Bt().sortMode),[ke,me]=l.useState(!1),[U,W]=l.useState(!1),Q=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 fe=h==="__custom__"?v.trim():((Fe=d.find(ve=>ve.id===h))==null?void 0:Fe.path)||"",ce=h==="__custom__"&&!!fe&&r.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(r.message),F=h!=="__custom__"&&((Ie=d.find(ve=>ve.id===h))==null?void 0:Ie.path)||"",le=l.useMemo(()=>(e.recentLaunches||[]).map(ve=>ve.workspace),[e]),je=l.useCallback(async ve=>{k(!0),C("");try{const Oe=await a(ve);j(Oe.path),f(Oe.path),w(Oe.directories)}catch(Oe){C(Oe instanceof Error?Oe.message:"Could not load folder")}finally{k(!1)}},[a]),de=l.useCallback(()=>{var Oe;g("__custom__"),M(!0);const ve=tl(e.platform,el(v.trim(),F,le,e.defaultWorkspacePath,(Oe=d.find(ut=>ut.id===m))==null?void 0:Oe.path,d.map(ut=>ut.path)));je(ve)},[v,m,je,le,F,e.platform,d]),H=l.useCallback(ve=>{if(ve!=null&&ve.workspaceId){g(ve.workspaceId),f("");return}if(ve!=null&&ve.workspacePath){g("__custom__"),f(ve.workspacePath);return}g(""),f("")},[]),be=l.useCallback(ve=>{if(g(ve),ve==="__custom__"){de();return}f("")},[de]),Ne=l.useCallback(ve=>{g("__custom__"),f(ve)},[]),Ce=l.useCallback((ve,Oe)=>{L.current=Oe,z.current=ve.selectedWorkspaceKey||"__home__",_(ve.selectedWorkspaceKey||"__home__"),E(ve.initialArgs||""),$(ve.initialModel||""),G(""),Z([]);const ut=ve.providerType?`${e.id}:${ve.providerType}`:null;if(tw(V.current,ut)){const ot=Bt();ne(ot.textQuery),ae(ot.workspaceQuery),se(ot.modelQuery),oe(ot.resumableOnly),ye(ot.sortMode)}V.current=ut,B(ve),ve.providerType&&o&&(me(!0),o(ve.providerType).then(ot=>Z(ot||[])).catch(ot=>console.warn("Failed to load saved sessions",ot)).finally(()=>me(!1)))},[o,e.id]),$e=l.useMemo(()=>pp(Y,{textQuery:q,workspaceQuery:ue,modelQuery:O,resumableOnly:X,sortMode:Se}),[O,X,Y,Se,q,ue]);l.useEffect(()=>{I&&($e.some(ve=>ve.providerSessionId===I)||G(""))},[$e,I]);const Qe=l.useCallback(()=>{L.current&&(W(!0),L.current().finally(()=>{L.current=null,W(!1),B(null)}))},[]),dt=l.useCallback(()=>{L.current=null,B(null)},[]),it=l.useCallback(ve=>{z.current=ve,_(ve)},[]);return l.useEffect(()=>{var ve;Q.current!==e.id&&(Q.current=e.id,g(m||((ve=d[0])==null?void 0:ve.id)||"__custom__"),f(""),j(""),w([]),C(""),M(!1),ne(Bt().textQuery),ae(Bt().workspaceQuery),se(Bt().modelQuery),oe(Bt().resumableOnly),ye(Bt().sortMode),V.current=null,T(xo(p,t.length,n.length)))},[n.length,t.length,m,p,e.id,d]),l.useEffect(()=>{var ve;h!=="__custom__"&&(h&&d.some(Oe=>Oe.id===h)||g(m||((ve=d[0])==null?void 0:ve.id)||"__custom__"))},[m,h,d]),l.useEffect(()=>{A==="ide"&&p||A==="cli"&&t.length>0||A==="acp"&&n.length>0||T(xo(p,t.length,n.length))},[A,n.length,t.length,p]),{showAllRecent:u,setShowAllRecent:c,hasIdeOptions:p,workspaceRows:d,defaultWorkspaceId:m,workspaceChoice:h,customWorkspacePath:v,browseCurrentPath:y,browseDirectories:x,browseBusy:N,browseError:b,browseDialogOpen:S,activeLauncherKind:A,launchConfirm:P,launchConfirmWorkspaceKeyRef:z,launchConfirmWorkspaceKey:R,launchConfirmArgs:K,launchConfirmModel:D,launchConfirmResumeId:I,launchConfirmSavedSessions:Y,launchConfirmTextFilter:q,launchConfirmWorkspaceFilter:ue,launchConfirmModelFilter:O,launchConfirmResumableOnly:X,launchConfirmSortMode:Se,filteredLaunchConfirmSavedSessions:$e,launchConfirmSessionsLoading:ke,launchConfirmBusy:U,resolvedWorkspacePath:fe,canCreateMissingWorkspace:ce,openBrowseDialog:de,loadBrowsePath:je,handleWorkspaceChoiceChange:be,chooseCustomWorkspacePath:Ne,setCustomWorkspacePath:f,setBrowseDialogOpen:M,setActiveLauncherKind:T,openLaunchConfirm:Ce,handleConfirmLaunch:Qe,closeLaunchConfirm:dt,setWorkspaceSelectionFromOption:H,setLaunchConfirmWorkspaceKeyAndSync:it,setLaunchConfirmArgs:E,setLaunchConfirmModel:$,setLaunchConfirmResumeId:G,setLaunchConfirmTextFilter:ne,setLaunchConfirmWorkspaceFilter:ae,setLaunchConfirmModelFilter:se,setLaunchConfirmResumableOnly:oe,setLaunchConfirmSortMode:ye}}function Vj({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:n,cliProviders:r,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:u,isStandalone:c,section:p,showBottomNav:d,onBack:m,onSectionChange:h,onOpenConversation:g,onOpenRecent:v,onOpenMachineDetails:f,onMachineUpgrade:y,onLaunchDetectedIde:j,onAddWorkspace:x,onBrowseDirectory:w,onLaunchWorkspaceProvider:N,onListSavedSessions:k}){const{t:b}=Xe("common"),C=_=>_==="ide"?"IDE":_==="cli"?"CLI":"ACP",S=n.slice(0,4),M=t.slice(0,3),A=zj({selectedMachineEntry:e,cliProviders:r,acpProviders:a,machineAction:u,onBrowseDirectory:w,onListSavedSessions:k}),T=l.useMemo(()=>S.map(_=>{const{metaText:K,updatedLabel:E}=eh(_);return{key:`recent-launch:${_.id}`,primary:_.label,secondary:K,updatedLabel:E,onClick:()=>{const{options:D,selectedKey:$}=Zp({machine:{workspaces:A.workspaceRows,defaultWorkspaceId:A.defaultWorkspaceId},currentWorkspacePath:_.workspace});A.openLaunchConfirm({title:_.kind==="ide"?da(b,"restart-ide",_.label):_.providerSessionId?mp(b,_.label):da(b,"start-fresh",_.label),description:_.kind==="ide"?ua(b,"restart-ide"):_.providerSessionId?fp(b):ua(b,"start-fresh"),confirmLabel:_.kind==="ide"?pa(b,"restart-ide"):_.providerSessionId?ai(b,!0):pa(b,"start-fresh"),busyLabel:_.kind==="ide"?ha(b,"restart-ide"):_.providerSessionId?hp(b,!0):ha(b,"start-fresh"),workspaceOptions:D,selectedWorkspaceKey:$,details:[{label:"Mode",value:C(_.kind)},..._.providerType?[{label:"Provider",value:_.providerType}]:[]]},async()=>{const I=D.find(G=>G.key===A.launchConfirmWorkspaceKeyRef.current);A.setWorkspaceSelectionFromOption(I),await v({..._,workspace:(I==null?void 0:I.workspacePath)??null})})}}}),[A,v,S,b]),L=l.useMemo(()=>M.map(_=>({key:`recent-chat:${_.conversation.tabKey}`,primary:gt(_.conversation),secondary:T0(_.conversation,{timestampLabel:_.timestamp?du(_.timestamp):null}),unread:_.unread,onClick:()=>g(_.conversation)})),[g,M]),P=A.showAllRecent?T:T.slice(0,4),B=T.length>0,z=L.length>0,R=c?"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 ${R} 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:ts(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:[z&&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))})]}),B&&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:P.map(_=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:_.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:_.primary}),_.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:_.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:_.secondary})]},_.key))}),T.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>A.setShowAllRecent(_=>!_),children:A.showAllRecent?"Show fewer":`Show ${T.length-4} more`})})]}),!1,s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:y,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"})]})]})]})]}),A.browseDialogOpen&&s.jsx(rl,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:A.browseCurrentPath,directories:A.browseDirectories,busy:A.browseBusy,error:A.browseError,confirmLabel:"Use this folder",onClose:()=>A.setBrowseDialogOpen(!1),onNavigate:_=>{A.loadBrowsePath(_)},onConfirm:_=>{A.chooseCustomWorkspacePath(_),A.setBrowseDialogOpen(!1)}}),A.launchConfirm&&s.jsx(Qp,{title:A.launchConfirm.title,description:A.launchConfirm.description,details:A.launchConfirm.details,workspaceOptions:A.launchConfirm.workspaceOptions,selectedWorkspaceKey:A.launchConfirmWorkspaceKey,onWorkspaceChange:A.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:A.launchConfirm.providerType?ai(b,!!A.launchConfirmResumeId):A.launchConfirm.confirmLabel,busyLabel:A.launchConfirm.providerType?void 0:A.launchConfirm.busyLabel,busy:A.launchConfirmBusy,showArgsInput:A.launchConfirm.showArgsInput,argsValue:A.launchConfirmArgs,onArgsChange:A.setLaunchConfirmArgs,showModelInput:A.launchConfirm.showModelInput,modelValue:A.launchConfirmModel,onModelChange:A.setLaunchConfirmModel,historyProviderNode:A.launchConfirm.providerType&&(A.launchConfirmSessionsLoading||A.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"}),A.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(b)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:A.launchConfirmTextFilter,onChange:_=>A.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:A.launchConfirmBusy||A.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:A.launchConfirmWorkspaceFilter,onChange:_=>A.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:A.launchConfirmBusy||A.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:A.launchConfirmModelFilter,onChange:_=>A.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:A.launchConfirmBusy||A.launchConfirmSessionsLoading}),s.jsxs("select",{value:A.launchConfirmSortMode,onChange:_=>A.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:A.launchConfirmBusy||A.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:A.launchConfirmResumableOnly,onChange:_=>A.setLaunchConfirmResumableOnly(_.target.checked),disabled:A.launchConfirmBusy||A.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:A.launchConfirmResumeId,onChange:_=>A.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:A.launchConfirmBusy||A.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:rw(b)}),A.filteredLaunchConfirmSavedSessions.map(_=>s.jsxs("option",{value:_.providerSessionId,disabled:!_.canResume,children:[_.title||_.providerSessionId," ",_.canResume?"":"(workspace missing)"]},_.providerSessionId))]}),!A.launchConfirmSessionsLoading&&A.launchConfirmSavedSessions.length>0&&A.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),A.launchConfirmResumeId&&(()=>{const _=A.filteredLaunchConfirmSavedSessions.find(E=>E.providerSessionId===A.launchConfirmResumeId);if(!_)return null;const K=Xp(_);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:K.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:K.providerSessionId}),s.jsx("div",{className:"mt-1",children:K.metaLine}),K.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:K.updatedLabel}),K.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:K.preview})]})})()]}),onConfirm:A.handleConfirmLaunch,onCancel:A.closeLaunchConfirm}),d&&s.jsx(Jp,{section:p,onSectionChange:h})]})}const Oc=8e3;function qj(e){const t=e&&typeof e=="object"&&"result"in e?e.result:e,n=t&&typeof t=="object",r=n&&t.success===!1,a=n&&t.mirrorStale===!0;return!r&&!a?{confirmed:!0}:{confirmed:!1,reason:r&&typeof t.error=="string"?t.error:a?"the coordinator did not confirm the change":"command was rejected"}}function th(e,t,n){const r=l.useRef(new Map),[,a]=l.useState(0),o=l.useCallback(()=>a(g=>g+1),[]);l.useEffect(()=>{const g=r.current;if(g.size===0)return;const v=Date.now();let f=!1;for(const[y,j]of g){const x=e.get(y),w=j.muted===void 0||(x?x.muted===j.muted:!1),N=j.hidden===void 0||(x?x.surfaceHidden===j.hidden:!1),k=v-j.at>Oc;(w&&N||k)&&(g.delete(y),f=!0)}f&&o()},[e,o]),l.useEffect(()=>{if(r.current.size===0)return;const g=setInterval(()=>{const v=r.current,f=Date.now();let y=!1;for(const[j,x]of v)f-x.at>Oc&&(v.delete(j),y=!0);y&&o(),v.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,v)=>{const f=r.current.get(g);r.current.set(g,{...f,...v,at:Date.now()}),o()},[o]),u=l.useCallback(g=>{const v=g.sessionId,f=v?r.current.get(v):void 0;return(f==null?void 0:f.muted)!==void 0?f.muted:Ps(g,e).muted},[e]),c=l.useCallback(g=>{const v=g.sessionId,f=v?r.current.get(v):void 0;return(f==null?void 0:f.hidden)!==void 0?f.hidden:Ps(g,e).surfaceHidden},[e]),p=l.useCallback((g,v)=>{const f=Ds(g),y=g.sessionId;!f||!y||(i(y,v),t(f,"set_conversation_prefs",{sessionId:y,...v,...Ta(g)}).then(j=>{const x=qj(j);x.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",x.reason),r.current.delete(y),o(),n==null||n(`Couldn't update conversation — ${x.reason}`))}).catch(j=>{console.warn("[conversation-prefs] set_conversation_prefs failed",j),r.current.delete(y),o();const x=j instanceof Error?j.message:String(j??"the daemon is unreachable");n==null||n(`Couldn't update conversation — ${x}`)}))},[t,i,o,n]),d=l.useCallback(g=>{p(g,{muted:!u(g)})},[p,u]),m=l.useCallback((g,v)=>{p(g,{hidden:v})},[p]),h=l.useCallback(g=>{p(g,{hidden:!c(g)})},[p,c]);return{isMuted:u,isHidden:c,toggleMute:d,setHidden:m,toggleHidden:h}}function Yr(e){return[...e].sort((t,n)=>{const r=n.timestamp-t.timestamp;return r!==0?r:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function Yj(e,t=[]){const n=new Map(e.map(a=>[a.conversation.tabKey,a])),r=t.map(a=>n.get(a)).filter(a=>!!a);return r.length===e.length?r:Yr(e)}function Jj(e){var r,a,o;const t=((r=e.p2p)==null?void 0:r.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 Xj(e,t){if(!e)return[];const n=e.recentLaunches||[];return n.length>0?n.map(r=>({id:r.id,label:r.title||r.providerName||r.providerType,kind:r.kind,providerType:r.providerType,providerSessionId:r.providerSessionId,subtitle:Js(r.summaryMetadata)||r.workspace||void 0,workspace:r.workspace,summaryMetadata:r.summaryMetadata})):t.filter(r=>r.type!=="adhdev-daemon"&&r.daemonId===e.id).map(r=>{var i;const a=ir(r)?"cli":hn(r)?"acp":"ide",o=Js(r.summaryMetadata);return{id:`${a}:${r.type}:${r.workspace||""}`,label:((i=r.activeChat)==null?void 0:i.title)||(ir(r)?r.cliName||r.type:hn(r)&&r.cliName||r.type),kind:a,providerType:r.type,providerSessionId:r.providerSessionId,subtitle:hn(r)?o||r.workspace||void 0:r.workspace||void 0,workspace:r.workspace||void 0,timestamp:r.lastMessageAt||0}}).sort((r,a)=>a.timestamp-r.timestamp).map(({timestamp:r,...a})=>a)}function Qj(e,t){const n=new Map;for(const r of t){const a=Ds(r.conversation),o=n.get(a);o?o.push(r):n.set(a,[r])}return e.map(r=>{const a=n.get(r.id)||[],o=[...a].sort((m,h)=>h.timestamp-m.timestamp)[0]||null,i=(o==null?void 0:o.conversation)||null,u=Qo(r),c=a.filter(m=>m.unread||m.requiresAction).length,p=Jj(r),d=[r.platform||"machine",p].filter(Boolean);return{id:r.id,label:ts(r,{fallbackId:r.id}),subtitle:d.join(" · "),unread:c,total:a.length,latestConversation:i,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:u,preview:i?P0(i,Zu(i)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((r,a)=>{const o=r.latestTimestamp||r.fallbackActivityAt||0,i=a.latestTimestamp||a.fallbackActivityAt||0;return i!==o?i-o:r.label.localeCompare(a.label)})}function Zj(e){return e==="chat"}function Rr(e,t){var n;if(!(typeof window>"u"))try{if(!(!!((n=import.meta.env)!=null&&n.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,t)}catch{}}function eS({conversations:e,machineEntries:t,items:n,selectedConversation:r,selectedTabKey:a,screen:o,liveSessionInboxState:i,sendDaemonCommand:u,requestedActiveTabKey:c,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:g,setSelectedTabKey:v,setScreen:f,setSelectedMachineId:y,setSection:j,setMachineBackTarget:x,resetMachineAction:w}){const N=l.useRef(null),k=l.useCallback(b=>{if(!(b!=null&&b.sessionId))return;const C=Ps(b,i),S=Math.max(Date.now(),Vs(b),C.lastUpdated||0);Rr("mark_read:start",{tabKey:b.tabKey,sessionId:b.sessionId,displayPrimary:gt(b),inboxBucket:C.inboxBucket,unread:C.unread,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,activityAt:Vs(b),readAt:S}),u(Ds(b)||b.routeId,"mark_session_seen",{sessionId:b.sessionId,providerSessionId:b.providerSessionId,seenAt:S,completionMarker:C.completionMarker}).then(M=>{Rr("mark_read:result",{tabKey:b.tabKey,sessionId:b.sessionId,result:M})}).catch(M=>{Rr("mark_read:error",{tabKey:b.tabKey,sessionId:b.sessionId,error:M instanceof Error?M.message:String(M)})})},[i,u]);return l.useEffect(()=>{var C;if(!r){Zj(o)&&f("inbox"),v(((C=e[0])==null?void 0:C.tabKey)||null),N.current=null;return}if(o!=="chat"){N.current=null;return}const b=`${r.tabKey}:${r.sessionId||""}`;N.current!==b&&(N.current=b,k(r))},[e,k,o,r,f,v]),l.useEffect(()=>{if(!c)return;const b=e.find(C=>C.tabKey===c);b&&(v(b.tabKey),f("chat"),p==null||p())},[e,p,c,f,v]),l.useEffect(()=>{if(!d)return;const b=t.find(C=>C.id===d);b&&(y(b.id),w(),j("machines"),x("inbox"),f("machine"),m==null||m())},[t,m,d,w,x,f,j,y]),l.useEffect(()=>{h&&(j(h),f("inbox"),g==null||g())},[g,h,f,j]),l.useEffect(()=>{const b=n.filter(C=>C.inboxBucket==="task_complete"||C.unread);b.length!==0&&Rr("inbox_state",{screen:o,selectedTabKey:a,items:b.map(C=>{const S=Ps(C.conversation,i);return{liveState:S,tabKey:C.conversation.tabKey,sessionId:C.conversation.sessionId,displayPrimary:gt(C.conversation),serverBucket:S.inboxBucket,computedBucket:C.inboxBucket,serverUnread:S.unread,computedUnread:C.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:Vs(C.conversation)}})})},[n,i,o,a]),{markConversationRead:k}}function tS(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 sS(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function nS({sendDaemonCommand:e,navigate:t,ides:n,conversations:r}){const{launchCli:a}=wa(),[o,i]=l.useState("idle"),[u,c]=l.useState(""),[p,d]=l.useState(null),m=l.useCallback(()=>{i("idle"),c(""),d(null)},[]),h=l.useCallback(async(w,N,k)=>{var b;try{i("loading"),c(`Launching ${N}…`);const C={ideType:N,enableCdp:!0};(b=k==null?void 0:k.workspacePath)!=null&&b.trim()&&(C.workspace=k.workspacePath.trim()),await e(w,"launch_ide",C),i("done"),c(`${N} launch requested`)}catch(C){i("error"),c(C instanceof Error?C.message:"Launch IDE failed"),console.error("Launch IDE failed",C)}},[e]),g=l.useCallback(async(w,N,k)=>{if(N.trim())try{i("loading"),c(k!=null&&k.createIfMissing?"Creating folder…":"Saving workspace…");const b=await e(w,"workspace_add",{path:N.trim(),createIfMissing:(k==null?void 0:k.createIfMissing)===!0});if(b!=null&&b.success){i("done"),c(k!=null&&k.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),c((b==null?void 0:b.error)||"Could not save workspace")}catch(b){i("error"),c(b instanceof Error?b.message:"Could not save workspace")}},[e]),v=l.useCallback(async w=>{var N,k,b,C,S,M;try{i("loading"),c("Starting daemon upgrade…");const A=await e(w,"daemon_upgrade",{});if((N=A==null?void 0:A.result)!=null&&N.alreadyLatest){i("done"),c(`Already on v${((k=A==null?void 0:A.result)==null?void 0:k.version)||"latest"}.`);return}if((b=A==null?void 0:A.result)!=null&&b.upgraded||(C=A==null?void 0:A.result)!=null&&C.success){i("done"),c(`Upgrade to v${((S=A==null?void 0:A.result)==null?void 0:S.version)||"latest"} started. Daemon is restarting…`);return}i("error"),c(((M=A==null?void 0:A.result)==null?void 0:M.error)||"Upgrade failed")}catch(A){i("error"),c(A instanceof Error?A.message:"Upgrade failed")}},[e]),f=l.useCallback(async(w,N,k,b)=>{var M,A,T;const C=Date.now(),S={machineId:w,kind:N,providerType:k,workspaceId:(b==null?void 0:b.workspaceId)||null,workspacePath:(b==null?void 0:b.workspacePath)||null,resumeSessionId:(b==null?void 0:b.resumeSessionId)||null,startedAt:C};try{i("loading"),c(`Launching ${k}…`),d(S);const L={cliType:k};(M=b==null?void 0:b.workspacePath)!=null&&M.trim()?L.dir=b.workspacePath.trim():b!=null&&b.workspaceId&&(L.workspaceId=b.workspaceId),b!=null&&b.resumeSessionId&&(L.resumeSessionId=b.resumeSessionId),(A=b==null?void 0:b.args)!=null&&A.trim()&&(L.cliArgs=b.args.trim().split(/\s+/).filter(Boolean)),(T=b==null?void 0:b.model)!=null&&T.trim()&&(L.initialModel=b.model.trim());const P=await a(w,L),B=(P==null?void 0:P.result)||P,z=(B==null?void 0:B.sessionId)||(B==null?void 0:B.id);if(P!=null&&P.success&&z){d(null),i("done"),c(`${k} launched`),t(dr(z));return}if(P!=null&&P.success){i("loading"),c(`${k} launch requested — waiting for session…`);return}d(null),i("error"),c((P==null?void 0:P.error)||(B==null?void 0:B.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(L){if(sS(L)){i("loading"),c(`${k} launch requested — waiting for session…`);return}d(null),i("error"),c(L instanceof Error?L.message:`Could not launch ${N.toUpperCase()} workspace`)}},[t,e]),y=l.useCallback(async(w,N)=>{try{const k=await e(w,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),b=(k==null?void 0:k.result)??k;return Array.isArray(b==null?void 0:b.sessions)?b.sessions:[]}catch(k){return console.error("Failed to list saved sessions on mobile:",k),[]}},[e]),j=l.useCallback(async(w,N)=>sl(e,w,N),[e]);l.useEffect(()=>{if(!p)return;const w=Wc(p.workspacePath),N=n.find(b=>{var L,P,B,z;if(!b||b.type==="adhdev-daemon"||tS(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 A=String(b.providerSessionId||"");if(p.resumeSessionId&&A)return A===p.resumeSessionId;if(w){const R=Wc(b.workspace||b.runtimeWorkspaceLabel);return R?R===w:!1}return Number(b.lastUpdated||b._lastUpdate||b.timestamp||((z=(B=(P=(L=b.activeChat)==null?void 0:L.messages)==null?void 0:P.at)==null?void 0:B.call(P,-1))==null?void 0:z.timestamp)||0)>=p.startedAt-5e3});if(!N)return;const k=Vp({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:r});k&&(d(null),i("done"),c(`${p.providerType} launched`),t(dr(k)))},[r,n,t,p]),l.useEffect(()=>{if(!p)return;const w=window.setTimeout(()=>{d(N=>!N||N.startedAt!==p.startedAt?N:(i("error"),c("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(w)},[p]);const x=l.useCallback(async(w,N)=>{if(N.kind==="ide"&&N.providerType){await h(w,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await f(w,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[h,f]);return{machineAction:{state:o,message:u},resetMachineAction:m,handleLaunchDetectedIde:h,handleAddWorkspace:g,handleMachineUpgrade:v,handleLaunchWorkspaceProvider:f,handleListSavedSessions:y,handleBrowseDirectory:j,handleOpenRecent:x}}function rS({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:r,resetMachineAction:a,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:u,setSection:c,setMachineBackTarget:p}){const d=l.useCallback(j=>{o(j.tabKey),i("chat"),r(j)},[r,i,o]),m=l.useCallback(j=>{const x=e.find(w=>w.routeId===j.routeId&&w.streamSource==="native");x&&(o(x.tabKey),i("chat"),r(x))},[e,r,i,o]),h=l.useCallback(()=>{r(t),i("inbox")},[r,t,i]),g=l.useCallback((j,x="inbox")=>{u(j),a(),c("machines"),p(x),i("machine")},[a,p,i,c,u]),v=l.useCallback(j=>{const x=Ds(j);x&&g(x,"chat")},[g]),f=l.useCallback(()=>{a(),i(n)},[n,a,i]),y=l.useCallback(j=>{c(j),i("inbox")},[i,c]);return{openConversation:d,openNativeConversation:m,backFromConversation:h,openMachine:g,openConversationMachine:v,backFromMachine:f,changeMachineSection:y}}function jn(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function aS(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function oS({conversations:e,hiddenConversations:t,ides:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,userName:u,requestedActiveTabKey:c,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:g,onOpenHistory:v,onOpenRemote:f,onStopCli:y,wsStatus:j,isConnected:x,onShowAllHiddenConversations:w,onHideConversation:N,onOpenMeshGraph:k,onOpenNewSession:b,liveSessionInboxState:C,setCliViewModeOverrides:S}){const[M,A]=l.useState(()=>{var H;return((H=e[0])==null?void 0:H.tabKey)||null}),[T,L]=l.useState(()=>e[0]?"chat":"inbox"),[P,B]=l.useState("chats"),[z,R]=l.useState(null),[_,K]=l.useState("inbox"),E=l.useRef([]),D=hr(),$="0.9.82",I=l.useMemo(()=>e.find(H=>H.tabKey===M)||e[0]||null,[e,M]),G=l.useMemo(()=>I?n.find(H=>H.id===I.routeId):void 0,[n,I]),Y=l.useMemo(()=>!I||lt(I)||!ct(I)?null:An(I),[I]),Z=l.useMemo(()=>n.filter(H=>H.type==="adhdev-daemon").sort(_i),[n]),q=l.useMemo(()=>Z.find(H=>H.id===z)||null,[Z,z]),ne=Pa({sendDaemonCommand:a,activeConv:I||void 0,setActionLogs:o,isStandalone:i}),ue=nS({sendDaemonCommand:a,navigate:D,ides:n,conversations:e}),ae=o0(e),O=l.useMemo(()=>e.map(H=>{const be=T==="chat"&&(I==null?void 0:I.tabKey)===H.tabKey,Ne=Na(H,C,{hideOpenTaskCompleteUnread:!0,isOpenConversation:be}),Ce=Vs(H),$e=Zu(H),Qe=op(H,$e);return{conversation:H,timestamp:Ce,preview:Qe,unread:Ne.unread,requiresAction:Ne.requiresAction,isWorking:Ne.isWorking,inboxBucket:Ne.inboxBucket}}),[e,C,T,I,ae]),{markConversationRead:se}=eS({conversations:e,machineEntries:Z,items:O,selectedConversation:I,selectedTabKey:M,screen:T,liveSessionInboxState:C,sendDaemonCommand:a,requestedActiveTabKey:c,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:g,setSelectedTabKey:A,setScreen:L,setSelectedMachineId:R,setSection:B,setMachineBackTarget:K,resetMachineAction:ue.resetMachineAction}),X=rS({conversations:e,selectedConversation:I,machineBackTarget:_,markConversationRead:se,resetMachineAction:ue.resetMachineAction,setSelectedTabKey:A,setScreen:L,setSelectedMachineId:R,setSection:B,setMachineBackTarget:K}),{isMuted:oe,toggleMute:Se}=th(C,a),ye=l.useMemo(()=>Yr(O.filter(H=>H.requiresAction&&!oe(H.conversation))),[O,oe]),ke=l.useMemo(()=>Yr(O.filter(H=>H.unread&&!H.requiresAction&&!oe(H.conversation))),[O,oe]),me=l.useMemo(()=>Yj(O.filter(H=>!H.unread&&!H.requiresAction&&H.isWorking),E.current),[O]);l.useEffect(()=>{E.current=me.map(H=>H.conversation.tabKey)},[me]);const U=l.useMemo(()=>Yr(O.filter(H=>!H.unread&&!H.requiresAction&&!H.isWorking)),[O]),W=l.useMemo(()=>q?O.filter(H=>Ds(H.conversation)===q.id):[],[O,q]),Q=l.useMemo(()=>Xj(q,n),[n,q]),V=(q==null?void 0:q.version)||null,fe=!!q&&!!V&&!0&&V!==$,ce=l.useMemo(()=>(q==null?void 0:q.availableProviders)||[],[q]),F=l.useMemo(()=>ce.filter(H=>jn(H,"cli")).map(H=>({type:H.type,displayName:H.displayName||H.type,icon:H.icon})),[ce]),le=l.useMemo(()=>ce.filter(H=>jn(H,"acp")).map(H=>({type:H.type,displayName:H.displayName||H.type,icon:H.icon})),[ce]),je=l.useMemo(()=>Qj(Z,O),[O,Z]),de=l.useCallback(async H=>{q&&await ue.handleOpenRecent(q.id,H)},[ue,q]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:T==="chat"&&I?s.jsx(Fj,{selectedConversation:I,isAcp:lt(I),isStandalone:i,selectedIdeEntry:G,actionLogs:r,userName:u,isSendingChat:ne.isSendingChat,sendFeedbackMessage:ne.sendFeedbackMessage,isFocusingAgent:ne.isFocusingAgent,handleModalButton:ne.handleModalButton,handleRelaunch:ne.handleRelaunch,onBack:X.backFromConversation,onOpenNativeConversation:X.openNativeConversation,onOpenMachine:X.openConversationMachine,onOpenHistory:v,onOpenRemote:f,onOpenMeshGraph:k,onStopCli:y,cliViewMode:Y,onSetCliViewMode:async H=>{await _p({conversation:I,mode:H,ides:n,sendDaemonCommand:a,setCliViewModeOverrides:S})},handleSendChat:ne.handleSendChat,handleForceSendChat:ne.handleForceSendChat,handleFocusAgent:ne.handleFocusAgent}):T==="machine"&&q?s.jsx(Vj,{selectedMachineEntry:q,selectedMachineConversations:W,selectedMachineRecentLaunches:Q,cliProviders:F,acpProviders:le,selectedMachineNeedsUpgrade:fe,appVersion:$,machineAction:ue.machineAction,isStandalone:i,section:P,showBottomNav:_==="inbox",onBack:X.backFromMachine,onSectionChange:X.changeMachineSection,onOpenConversation:X.openConversation,onOpenRecent:de,onOpenMachineDetails:()=>D(`/machines/${q.id}`),onMachineUpgrade:()=>ue.handleMachineUpgrade(q.id),onLaunchDetectedIde:(H,be)=>ue.handleLaunchDetectedIde(q.id,H,be),onAddWorkspace:(H,be)=>ue.handleAddWorkspace(q.id,H,be),onBrowseDirectory:H=>ue.handleBrowseDirectory(q.id,H),onLaunchWorkspaceProvider:(H,be,Ne)=>ue.handleLaunchWorkspaceProvider(q.id,H,be,Ne),onListSavedSessions:H=>ue.handleListSavedSessions(q.id,H)}):s.jsx(Oj,{section:P,attentionItems:ye,unreadItems:ke,workingItems:me,completedItems:U,hiddenConversations:t,machineCards:je,getAvatarText:aS,actionLogs:r,sendDaemonCommand:a,onOpenConversation:X.openConversation,onShowAllHidden:w,onHideConversation:N,onOpenMeshGraph:k,onStopCli:y,onOpenNewSession:b,onOpenMachine:X.openMachine,onOpenSettings:()=>D("/settings"),onSectionChange:B,wsStatus:j,isConnected:x,isStandalone:i,isConversationMuted:oe,onToggleMuteConversation:Se})})}function bo(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function iS({conversations:e,numGroups:t,onMoveTab:n,onReceiveTab:r,onOwnTabDrop:a,onClearPreviewOrder:o}){const i=l.useRef(0),[u,c]=l.useState(!1),[p,d]=l.useState(null),m=l.useCallback(()=>{i.current=0,c(!1),d(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const h=l.useCallback(y=>{y.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,c(!0))},[]),g=l.useCallback(y=>{if(!y.dataTransfer.types.includes("text/tab-key"))return;if(y.preventDefault(),!bo(t,n)){d("merge");return}const j=y.currentTarget.getBoundingClientRect(),x=y.clientX-j.left,w=j.width/3;x<w?d("split-left"):x>w*2?d("split-right"):d("merge")},[t,n]),v=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,c(!1),d(null))},[]),f=l.useCallback(y=>{i.current=0,c(!1);const j=y.dataTransfer.getData("text/tab-key"),x=j?e.some(N=>N.tabKey===j):!1,w=p;if(d(null),o(),!!j){if(y.preventDefault(),w==="split-left"&&bo(t,n)){n==null||n(j,"split-left");return}if(w==="split-right"&&bo(t,n)){n==null||n(j,"split-right");return}if(x){a(j);return}r==null||r(j)}},[e,p,t,n,r,a,o]);return{dragOver:u,dropAction:p,resetDragState:m,handleDragEnter:h,handleDragOver:g,handleDragLeave:v,handleDrop:f}}function lS(e,t){const n=new Set(t.map(o=>o.tabKey)),r=e.filter(o=>n.has(o)),a=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...r,...a]}function cS({conversations:e,initialActiveTabId:t,initialTabOrder:n,onActiveTabChange:r,onTabOrderChange:a}){const[o,i]=l.useState(t??null),[u,c]=l.useState(n??[]),[p,d]=l.useState(null),m=l.useRef(null),h=l.useRef(null),g=l.useRef(r),v=l.useRef(a);l.useEffect(()=>{g.current=r},[r]),l.useEffect(()=>{v.current=a},[a]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{c(C=>{const S=lS(C,e);return S.length===C.length&&S.every((M,A)=>M===C[A])?C:S})},[e]);const f=l.useMemo(()=>{const C=p??u;if(C.length===0)return e;const S=new Map(C.map((M,A)=>[M,A]));return[...e].sort((M,A)=>{const T=S.get(M.tabKey)??999,L=S.get(A.tabKey)??999;return T-L})},[e,p,u]);l.useEffect(()=>{var S,M;if(f.length===0){o!==null&&(i(null),(S=g.current)==null||S.call(g,null));return}if(o&&f.some(A=>A.tabKey===o))return;const C=f[0].tabKey;C!==o&&(i(C),(M=g.current)==null||M.call(g,C))},[f,o]);const y=l.useMemo(()=>f.find(C=>C.tabKey===o),[f,o]),j=l.useCallback(C=>{var S;i(C),(S=g.current)==null||S.call(g,C)},[]),x=l.useCallback((C,S,M)=>{c(A=>{var B;const T=A.filter(z=>z!==C),L=T.indexOf(S);if(L<0)return A;const P=M==="left"?L:L+1;return T.splice(P,0,C),(B=v.current)==null||B.call(v,T),T}),d(null)},[]),w=l.useCallback((C,S,M)=>{const T=(u.length>0?u:e.map(B=>B.tabKey)).filter(B=>B!==C),L=T.indexOf(S);if(L<0)return;const P=M==="left"?L:L+1;T.splice(P,0,C),m.current=T,d(T)},[u,e]),N=l.useCallback(()=>{var S;const C=m.current;C&&(c(C),(S=v.current)==null||S.call(v,C))},[]),k=l.useCallback(()=>{m.current=null,d(null)},[]),b=l.useCallback(C=>{c(S=>{var A;const M=S.filter(T=>T!==C);return M.push(C),(A=v.current)==null||A.call(v,M),M})},[]);return{activeTabId:o,activeConv:y,sortedConversations:f,previewOrderRef:m,draggingTabRef:h,selectTab:j,handleTabReorder:x,updatePreviewOrder:w,commitPreviewOrder:N,clearPreviewOrder:k,moveTabToEnd:b,setDraggingTabKey:C=>{h.current=C}}}function dS({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:n,hasRegisteredMachines:r=!1,suppressGuide:a=!1,onOpenNewSession:o}){const{t:i}=Xe("common");if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const u=!n&&!r,c=r&&!!o,p=i(r?"paneGroup.noConversations":n?"paneGroup.waitingForDaemon":"paneGroup.connectYourMachines"),d=i(r?"paneGroup.newSessionDescription":n?"paneGroup.daemonDescription":"paneGroup.installDescription");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:p}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:d}),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:i("paneGroup.newSession"),"aria-label":i("paneGroup.newSession"),children:[s.jsx(Ti,{size:14}),s.jsx("span",{children:i("paneGroup.newSession")})]})}),u&&s.jsx(Yp,{}),u&&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 sh="adhdev-tab-shortcuts";function nh(){try{return JSON.parse(localStorage.getItem(sh)||"{}")}catch{return{}}}function rh({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:r}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>nh()),[u,c]=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]),d=l.useCallback(m=>{i(m);try{localStorage.setItem(sh,JSON.stringify(m))}catch{}},[]);return l.useEffect(()=>{if(!e||!u)return;const m=h=>{if(h.preventDefault(),h.stopPropagation(),h.key==="Escape"){c(null);return}const g=p(h);if(!g)return;const v={...o};for(const[f,y]of Object.entries(v))y===g&&delete v[f];v[u]=g,d(v),c(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,u,o,d,p]),l.useEffect(()=>{if(!e)return;const m=h=>{if(!(!h.ctrlKey&&!h.metaKey&&!h.altKey)){for(const[g,v]of Object.entries(o))if(t.includes(g)&&p(h)===v){h.preventDefault(),n(),r(g);return}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,o,t,n,r,p]),{isMac:a,tabShortcuts:o,shortcutListening:u,setShortcutListening:c,saveShortcuts:d}}const go=e=>{e.preventDefault()},uS=l.memo(function({conv:t,isActive:n,isDraggedTab:r,isTaskCompleteUnread:a,shortcut:o,conversationKeys:i,draggingTabRef:u,onFocus:c,onSelectTab:p,onConversationActivated:d,onPreviewReorder:m,onReorderTab:h,onCommitPreviewOrder:g,onClearPreviewOrder:v,onDragStateReset:f,onDragTabKeyChange:y,onReceiveTab:j,onOpenContextMenu:x,longPressTimer:w,isGroupActive:N}){const k=Mn(t),b=k.isGenerating?"agent-tab-generating":k.isWaiting?"agent-tab-waiting":"",C=k.isReconnecting,S=A0(t),M=I0(t),A=ap(t),T=l.useCallback(D=>{u.current=t.tabKey,y(t.tabKey),D.dataTransfer.setData("text/tab-key",t.tabKey),D.dataTransfer.effectAllowed="move"},[t.tabKey,u,y]),L=l.useCallback(()=>{u.current=null,y(null),g(),v(),f()},[u,y,g,v,f]),P=l.useCallback(D=>{const $=u.current;if(!(!$||$===t.tabKey)&&D.dataTransfer.types.includes("text/tab-key")){D.preventDefault(),D.stopPropagation();const I=D.currentTarget.getBoundingClientRect(),G=D.clientX<I.left+I.width/2?"left":"right";m($,t.tabKey,G)}},[t.tabKey,u,m]),B=l.useCallback(D=>{D.preventDefault(),D.stopPropagation();const $=D.dataTransfer.getData("text/tab-key");if($&&$!==t.tabKey){const I=D.currentTarget.getBoundingClientRect(),G=D.clientX<I.left+I.width/2?"left":"right";i.includes($)?h($,t.tabKey,G):j&&j($)}v()},[t.tabKey,i,h,j,v]),z=l.useCallback(D=>{D.stopPropagation(),c(),p(t.tabKey),d(t)},[t,d,c,p]),R=l.useCallback(D=>{D.preventDefault(),x(D.clientX,D.clientY,t.tabKey)},[t.tabKey,x]),_=l.useCallback(D=>{const $=D.touches[0];w.current=setTimeout(()=>{x($.clientX,$.clientY,t.tabKey)},600)},[t.tabKey,w,x]),K=l.useCallback(()=>{w.current&&clearTimeout(w.current)},[w]),E=["adhdev-dockview-tab",b,n&&"is-active",N&&"is-group-active",C&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:E,draggable:!0,onDragStart:T,onDragEnd:L,onDragOver:P,onDrop:B,onClick:z,onContextMenu:R,onTouchStart:_,onTouchEnd:K,onTouchMove:K,style:{position:"relative",cursor:"pointer",opacity:r?.4:void 0},children:[A&&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(es,{size:11})}),a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:k.isGenerating?s.jsx("div",{className:"tab-spinner"}):k.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):C?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):k.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),S.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:M,"aria-label":M||S.join(" · "),children:S.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:gt(t),children:gt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[C?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:Ks(t)}):k.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[Ks(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:Ks(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 pS({conversations:e,activeTabId:t,groupIndex:n,unreadTabKeys:r,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:u,onPreviewReorder:c,onReorderTab:p,onCommitPreviewOrder:d,onClearPreviewOrder:m,onDragStateReset:h,onDragTabKeyChange:g,onReceiveTab:v,onHideTab:f,isGroupActive:y,allowTabShortcuts:j=!0}){const[x,w]=l.useState(null),N=l.useRef(null),k=l.useRef(null),b=l.useMemo(()=>e.map(P=>P.tabKey),[e]);mr("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(x==null?void 0:x.tabKey)||null});const{isMac:C,tabShortcuts:S,shortcutListening:M,setShortcutListening:A,saveShortcuts:T}=rh({enabled:j,sortedTabKeys:e.map(P=>P.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!x)return;const P=B=>{const z=document.querySelector("[data-pane-context-menu]");z&&z.contains(B.target)||w(null)};return window.addEventListener("mousedown",P,!0),()=>window.removeEventListener("mousedown",P,!0)},[x]),l.useEffect(()=>{const P=k.current;if(!P)return;const B=z=>{Math.abs(z.deltaY)<=Math.abs(z.deltaX)||(z.preventDefault(),P.scrollLeft+=z.deltaY)};return P.addEventListener("wheel",B,{passive:!1}),()=>P.removeEventListener("wheel",B)},[]);const L=l.useCallback((P,B,z)=>{w({x:P,y:B,tabKey:z})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:k,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(P=>s.jsx(uS,{conv:P,isActive:t===P.tabKey,isDraggedTab:a.current===P.tabKey,isTaskCompleteUnread:r.has(P.tabKey),shortcut:j?S[P.tabKey]:void 0,conversationKeys:b,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:u,onPreviewReorder:c,onReorderTab:p,onCommitPreviewOrder:d,onClearPreviewOrder:m,onDragStateReset:h,onDragTabKeyChange:g,onReceiveTab:v,onOpenContextMenu:L,longPressTimer:N,isGroupActive:y},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:[j&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:go,onClick:P=>{P.stopPropagation(),A(x.tabKey),w(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],T(P),w(null)},children:"✕ Remove shortcut"})]}),f&&s.jsxs(s.Fragment,{children:[j&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:go,onClick:()=>{f(x.tabKey),w(null)},children:"🚫 Hide from Dashboard"})]})]}),j&&M&&s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>A(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. ",C?"⌘+1":"Ctrl+1",", ",C?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function hS({conversations:e,ides:t,clearedTabs:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:u,userName:c,groupIndex:p,onFocus:d,isSplitMode:m,numGroups:h,onMoveTab:g,onReceiveTab:v,style:f,onActiveTabChange:y,initialActiveTabId:j,initialTabOrder:x,onTabOrderChange:w,onHideTab:N,isFocused:k,allowTabShortcuts:b=!0,onOpenNewSession:C,liveSessionInboxState:S}){const{sendCommand:M}=yt(),A=l.useRef(null),{activeTabId:T,activeConv:L,sortedConversations:P,draggingTabRef:B,selectTab:z,handleTabReorder:R,updatePreviewOrder:_,commitPreviewOrder:K,clearPreviewOrder:E,moveTabToEnd:D,setDraggingTabKey:$}=cS({conversations:e,initialActiveTabId:j,initialTabOrder:x,onActiveTabChange:y,onTabOrderChange:w}),I=Pa({sendDaemonCommand:a,activeConv:L,setActionLogs:o,isStandalone:i}),{dragOver:G,dropAction:Y,resetDragState:Z,handleDragEnter:q,handleDragOver:ne,handleDragLeave:ue,handleDrop:ae}=iS({conversations:e,numGroups:h,onMoveTab:g,onReceiveTab:v,onOwnTabDrop:D,onClearPreviewOrder:E}),O=L&&!lt(L)&&An(L)==="terminal",se=l.useMemo(()=>L?t.find(ye=>ye.id===L.routeId):void 0,[t,L]),X=l.useMemo(()=>L?r.filter(ye=>ye.routeId===L.tabKey):[],[r,L]),oe=l.useMemo(()=>new Set(P.filter(ye=>Dx(ye,S,{isOpenConversation:ye.tabKey===T})).map(ye=>ye.tabKey)),[T,S,P]);mr("PaneGroup",{groupIndex:p,conversationCount:e.length,activeTabId:T,dragOver:G});const Se=l.useCallback(ye=>{ye.streamSource==="agent-stream"&&ye.agentType&&M(ye.routeId,Hu(),{agentType:ye.agentType,...ye.sessionId&&{targetSessionId:ye.sessionId}}).catch(()=>{})},[M]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:d,style:{...f,outline:G?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(pS,{conversations:P,activeTabId:T,groupIndex:p,numGroups:h,unreadTabKeys:oe,draggingTabRef:B,onFocus:d,onSelectTab:z,onConversationActivated:Se,onPreviewReorder:_,onReorderTab:R,onCommitPreviewOrder:K,onClearPreviewOrder:E,onDragStateReset:Z,onDragTabKeyChange:$,onMoveTab:g,onReceiveTab:v,onHideTab:N,isGroupActive:k??!1,allowTabShortcuts:b}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:q,onDragOver:ne,onDragLeave:ue,onDrop:ae,children:[G&&s.jsx(dS,{dropAction:Y,canSplit:!!(h<4&&g)}),L?s.jsx(nl,{activeConv:L,clearToken:n[L.tabKey]||0,isCliTerminal:!!O,ideEntry:se,terminalRef:A,handleModalButton:I.handleModalButton,handleRelaunch:I.handleRelaunch,handleSendChat:I.handleSendChat,handleForceSendChat:I.handleForceSendChat,isSendingChat:I.isSendingChat,sendFeedbackMessage:I.sendFeedbackMessage,handleFocusAgent:I.handleFocusAgent,isFocusingAgent:I.isFocusingAgent,actionLogs:X,userName:c,isInputActive:!m||!!k}):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:u,onOpenNewSession:C})})]})]})}function mS({containerRef:e,isSplitMode:t,numGroups:n,groupSizes:r,groupedConvs:a,clearedTabs:o,ides:i,actionLogs:u,sendDaemonCommand:c,setActionLogs:p,isStandalone:d,hasRegisteredMachines:m,userName:h,focusedGroup:g,focusGroup:v,moveTabToGroup:f,splitTabRelative:y,closeGroup:j,handleResizeStart:x,groupActiveTabIds:w,setGroupActiveTab:N,groupTabOrders:k,setGroupTabOrder:b,toggleHiddenTab:C,onOpenNewSession:S,allowTabShortcuts:M=!0,liveSessionInboxState:A}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((T,L)=>{const P=t&&r.length===n?`${r[L]}%`:void 0;return s.jsxs(Rt.Fragment,{children:[t&&L>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:B=>x(L-1,B),onDoubleClick:()=>j(L),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(hS,{style:t?{flexBasis:P??`${100/n}%`,flexGrow:P?0:1,flexShrink:P?0:1}:void 0,conversations:T,clearedTabs:o,ides:i,actionLogs:u,sendDaemonCommand:c,setActionLogs:p,isStandalone:d,hasRegisteredMachines:m,userName:h,groupIndex:L,isFocused:t&&g===L,onFocus:()=>v(L),isSplitMode:t,numGroups:n,onMoveTab:(B,z)=>{z==="left"&&L>0?f(B,L-1):z==="right"&&L<n-1?f(B,L+1):z==="split-left"&&n<4?y(B,L,"left"):z==="split-right"&&n<4&&y(B,L,"right")},onReceiveTab:B=>f(B,L),onActiveTabChange:B=>N(L,B),initialActiveTabId:w[L],initialTabOrder:k[L],onTabOrderChange:B=>b(L,B),onHideTab:C,onOpenNewSession:S,allowTabShortcuts:M,liveSessionInboxState:A})]},L)})})}const ah="adhdev-dashboard-action-shortcuts",fS=1200,xS=[["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 bS(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function mt(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 oh(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:mt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:mt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:mt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:mt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:mt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:mt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:mt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:mt("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:mt("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:mt("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:mt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:mt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:mt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:mt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:mt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:mt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:mt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:mt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:mt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:mt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:mt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:mt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:mt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:mt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:mt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:mt("toggleCliView",e)}]}function mi(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(oh(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(ah)||"{}"),r={...t,...n};for(const[a,o]of xS)r[a]===o&&(r[a]=t[a]);return r}catch{return t}}function ih(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function gS({enabled:e=!0,onTrigger:t}){const n=bS(),[r,a]=l.useState(()=>ga(n)),[o,i]=l.useState(null),[u,c]=l.useState([]),p=l.useRef({parts:[],timer:null}),d=l.useCallback(f=>{const y=[];return f.metaKey&&y.push(n?"⌘":"Meta"),f.ctrlKey&&y.push("Ctrl"),f.altKey&&y.push(n?"⌥":"Alt"),f.shiftKey&&f.key.length!==1&&y.push(n?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(y.push(ih(f.key)),y.join("+"))},[n]),m=l.useCallback(f=>{a(f);try{localStorage.setItem(ah,JSON.stringify(f))}catch{}},[]);l.useEffect(()=>{const f=ga(n),y=Object.entries(r),j=Object.entries(f);y.length===j.length&&y.every(([x,w])=>f[x]===w)||m(f)},[r,n,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}},fS))},[]);l.useEffect(()=>{if(!o)return;const f=y=>{if(y.preventDefault(),y.stopPropagation(),y.key==="Escape"){i(null),c([]);return}const j=d(y);if(!j)return;const w=!(y.metaKey||y.ctrlKey||y.altKey)&&/^[A-Z0-9]$/.test(j);if(u.length===0&&w){c([j]);return}const k=[...u,j].slice(0,2).join(" "),b={...r};for(const[C,S]of Object.entries(b))S===k&&delete b[C];b[o]=k,m(b),i(null),c([])};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[r,d,m,o,u]),l.useEffect(()=>{if(!e||o)return;const f=y=>{if(y.defaultPrevented)return;const j=d(y);if(!j)return;const x=y.metaKey||y.ctrlKey||y.altKey;if(mi(y.target))return;const w=p.current.parts,N=x?[j]:[...w.slice(-1),j].slice(-2),k=N.join(" "),b=N[N.length-1],C=Object.entries(r).filter(([,L])=>!!L),S=C.find(([,L])=>L===k);if(S){y.preventDefault(),h(),t(S[0]);return}if(C.some(([,L])=>L.startsWith(`${k} `))){y.preventDefault(),p.current.parts=N,g();return}const A=C.find(([,L])=>L===b);if(A){y.preventDefault(),h(),t(A[0]);return}if(C.some(([,L])=>L.startsWith(`${b} `))){y.preventDefault(),p.current.parts=[b],g();return}h()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[r,g,e,d,t,h,o]),l.useEffect(()=>()=>h(),[h]);const v=l.useMemo(()=>oh(n),[n]);return{isMac:n,actionDefinitions:v,actionShortcuts:r,shortcutListening:o,shortcutListeningDraft:u,setShortcutListening:i,setShortcutListeningDraft:c,saveShortcuts:m}}function yS({isTabInPopout:e,isTabFloating:t,tabShortcut:n,actionShortcuts:r}){const a=[];return e?(t&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:r.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:r.dockActiveTab})):t?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:r.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:r.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:r.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:n?`Change shortcut (${n})`:"Set shortcut",shortcut:r.setActiveTabShortcut}),n&&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:r.hideCurrentTab,tone:"muted"}),a}function lh(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Uc({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:r}){return!e||n>0?!1:t?!lh(r):!0}function vS({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:lh(n)}const ch=1e3,wS=4;function Kc(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Gc(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function kS({detachDelayMs:e=ch,stillnessThresholdPx:t=wS,onDetach:n,setTimeoutFn:r=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,u=null,c=null,p=null,d=!1;const m=()=>{p!=null&&(a(p),p=null)},h=()=>{m(),u=null},g=()=>{m(),o=null,i=null,u=null,c=null,d=!1},v=()=>{!o||!u||!c||d||p!=null||(p=r(()=>{p=null,!(!o||!u||!c||d)&&Kc(c,i)&&(Gc(u,c,t)||(d=!0,n({panelId:o,clientX:c.clientX,clientY:c.clientY})))},e))},f=j=>{if(!(!o||d)){if(!Kc(j,i)){c={clientX:j.clientX,clientY:j.clientY},h();return}(!u||Gc(u,j,t))&&(m(),u={clientX:j.clientX,clientY:j.clientY}),c={clientX:j.clientX,clientY:j.clientY},v()}},y=j=>{!o||d||(j&&(c={clientX:j.clientX,clientY:j.clientY}),h())};return{startDrag:j=>{m(),o=j.panelId,i=j.selfPanelBounds??null,u=null,c={clientX:j.clientX,clientY:j.clientY},d=!1},markSelfPanel:f,markNonSelfPanel:y,markNoDropTarget:y,markDockTarget:y,endDrag:g,isDragging:()=>o!=null,hasDetached:()=>d,dispose:g}}function jS(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Jr(e){return gt(e)||e.tabKey}function SS(e){return`remote:${e}`}function rs(e){return e.startsWith("remote:")}function zc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function yo(e){var r;const t=e==null?void 0:e.defaultView;if(!t)return;const n=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{t.focus(),n(e==null?void 0:e.body),n(e==null?void 0:e.documentElement),(r=t.requestAnimationFrame)==null||r.call(t,()=>{try{t.focus(),n(e==null?void 0:e.body)}catch{}})}catch{}}function vo(e,t){e.classList.remove(Bo.className,Ho.className),e.classList.add(t==="light"?Bo.className:Ho.className)}function Vc(e){return e?Array.from(new Set(e.groups.map(t=>{var n,r;return(r=(n=t.element)==null?void 0:n.ownerDocument)==null?void 0:r.defaultView}).filter(t=>!!t&&t!==window))):[]}function NS(e,t,n){var i;const r=[t];let a;for(const u of r){let c;for(const p of u){const d=e.addPanel({id:p.tabKey,component:"conversation",title:Jr(p),params:{kind:"conversation",tabKey:p.tabKey},...c?{position:{referencePanel:c,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});c||(c=d.id)}a=c??a}return n??((i=t[0])==null?void 0:i.tabKey)??null}function qc(e,t){const n=new Set(t.map(a=>a.tabKey)),r=new Map;for(const a of t)r.set(a.tabKey,(r.get(a.tabKey)||0)+1);for(const a of[...e.panels])rs(a.id)||n.has(a.id)||e.removePanel(a);for(const a of t){const o=e.getPanel(a.tabKey);if(o){(r.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!==Jr(a)&&o.api.setTitle(Jr(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:Jr(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,n){var c,p;const r=n?SS(n):null;for(const d of[...e.panels])rs(d.id)&&(!r||d.id!==r)&&e.removePanel(d);if(!n||!r)return;const a=cs(t,n);if(!a&&e.totalPanels===0)return;const o=e.getPanel(r),i=cp(a);if(o){o.title!==i&&o.api.setTitle(i);return}const u=(a==null?void 0:a.tabKey)??((c=e.activePanel)==null?void 0:c.id)??((p=e.panels.find(d=>!rs(d.id)))==null?void 0:p.id);e.addPanel({id:r,component:"remote",title:i,params:{kind:"remote",routeId:n},...u?{position:{referencePanel:u,direction:"right"},inactive:!0}:{}})}function dh({doId:e,targetSessionId:t,connState:n,viewMode:r}){const[a,o]=l.useState(null),[i,u]=l.useState(null);l.useEffect(()=>e?kt.onScreenshot("ide-page",(d,m)=>{if(d!==e)return;const h=new FileReader;h.onload=()=>o(h.result),h.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{n!=="connected"&&o(null)},[n]),l.useEffect(()=>{var d;return e?((d=kt.onStatus)==null?void 0:d.call(kt,(m,h)=>{m===e&&h!=null&&h.screenshotUsage&&u(h.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const p=e?kt.get(e):null;if(!(!p||n!=="connected"))return r!=="chat"&&t?p.startScreenshots(t):p.stopScreenshots(t),()=>{p.stopScreenshots(t)}},[r,n,t,e]);const c=l.useCallback(async(p,d)=>{const m=e?kt.get(e):null;return!m||n!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):m.sendInput(p,d,t)},[e,n,t]);return{connScreenshot:a,screenshotUsage:i,handleRemoteAction:c}}const uh=l.createContext(null);function Ra(){const e=l.useContext(uh);if(!e)throw new Error("DashboardDockviewContext missing");return e}function CS(e){const[,t]=l.useState(0);l.useEffect(()=>{const n=()=>t(a=>a+1),r=[e.api.onDidActiveGroupChange(n),e.api.onDidTitleChange(n),e.api.onDidGroupChange(n),e.containerApi.onDidActivePanelChange(n)];return()=>{for(const a of r)a.dispose()}},[e.api,e.containerApi])}function MS({params:e}){var c;const t=Ra(),n=l.useMemo(()=>cs([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),r=l.useMemo(()=>t.ides.find(p=>p.id===e.routeId),[t.ides,e.routeId]),a=(n==null?void 0:n.daemonId)||((c=n==null?void 0:n.routeId)==null?void 0:c.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:u}=dh({doId:a,targetSessionId:n?Bu(n):(r==null?void 0:r.sessionId)||(r==null?void 0:r.instanceId),connState:(n==null?void 0:n.connectionState)||"new",viewMode:"remote"});return n?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:n.connectionState||"new",connScreenshot:o,screenshotUsage:i,transportType:n.transport,onAction:u})}):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 AS(){const e=Ra();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 IS(e){var x,w;CS(e);const t=Ra(),n=l.useCallback(N=>{"button"in N&&N.button!==0||e.api.setActive()},[e.api]),r=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),a=r==null?void 0:r.sessionId,o=l.useCallback(N=>d0(N),[]),i=l.useCallback(()=>c0(a),[a]),u=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const N=cs([...t.conversationsByTabKey.values()],e.params.routeId),k=((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${k?" is-active":""}${b?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(N==null?void 0:N.tabKey)||"",onMouseDown:n,onTouchStart:n,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:N!=null&&N.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:N.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const c=t.conversationsByTabKey.get(e.params.tabKey);if(!c)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=((w=e.api.group.activePanel)==null?void 0:w.id)===e.api.id,d=e.api.isGroupActive,m=Na(c,t.liveSessionInboxState,{isOpenConversation:p}),h=m.isReconnecting,g=m.isConnecting,v=m.isGenerating||u,f=m.isWaiting,y=m.unread,j=t.tabShortcuts[c.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${d?" is-group-active":""}${h?" is-reconnecting":""}`,title:gt(c),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:N=>{var k;N.preventDefault(),n(N),t.openTabContextMenu({x:N.clientX,y:N.clientY,tabKey:c.tabKey,sourceDocument:((k=N.target)==null?void 0:k.ownerDocument)??document})},children:[y&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:v?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"}):c.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:gt(c)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:h?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Ks(c)}):g?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Ks(c)}):s.jsx("span",{children:Ks(c)})})]}),j&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:j,children:j})]})}function _r(e){return e.isActive}function Jc(e){return e.isVisible}function TS(e){e.preventDefault()}function PS({params:e,api:t}){var g;const n=Ra(),r=l.useRef(null),[a,o]=l.useState(()=>_r(t)),[i,u]=l.useState(()=>Jc(t)),c=n.conversationsByTabKey.get(e.tabKey),p=Pa({sendDaemonCommand:n.sendDaemonCommand,activeConv:c,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{o(_r(t)),u(Jc(t));const v=[t.onDidActiveChange(f=>o(f.isActive)),t.onDidActiveGroupChange(f=>{if(!_r(t)&&!f.isActive){o(!1);return}o(_r(t))}),t.onDidVisibilityChange(f=>u(f.isVisible))];return()=>{for(const f of v)f.dispose()}},[t]);const d=l.useMemo(()=>c?n.ides.find(v=>v.id===c.routeId):void 0,[n.ides,c]),m=l.useMemo(()=>c?n.actionLogs.filter(v=>v.routeId===c.tabKey):[],[n.actionLogs,c]);if(!c)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:n.isStandalone,hasRegisteredMachines:n.hasRegisteredMachines,onOpenNewSession:n.onOpenNewSession,suppressGuide:n.hasDetachedConversationPanels})});const h=!lt(c)&&An(c)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(nl,{activeConv:c,clearToken:n.clearedTabs[c.tabKey]||0,isCliTerminal:h,ideEntry:d,terminalRef:r,handleModalButton:p.handleModalButton,handleRelaunch:p.handleRelaunch,handleSendChat:p.handleSendChat,handleForceSendChat:p.handleForceSendChat,isSendingChat:p.isSendingChat,handleFocusAgent:p.handleFocusAgent,isFocusingAgent:p.isFocusingAgent,actionLogs:m,userName:n.userName,scrollToBottomRequestNonce:((g=n.scrollToBottomRequest)==null?void 0:g.tabKey)===c.tabKey?n.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:i})})}function DS({visibleConversations:e,clearedTabs:t,ides:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:u,initialDataLoaded:c,userName:p,toggleHiddenTab:d,actionShortcuts:m,registerActionHandlers:h,onActiveTabChange:g,onOpenNewSession:v,onRequestScrollToBottom:f,requestedActiveTabKey:y,requestedRemoteIdeId:j,onRequestedActiveTabConsumed:x,scrollToBottomRequest:w,liveSessionInboxState:N,layoutProfile:k}){var ut,ot,pt;const{theme:b}=Ls(),{sendCommand:C}=yt(),S=l.useRef(null),M=l.useRef(null),A=l.useRef(null),T=l.useRef(!1),L=l.useRef(!1),P=l.useRef(!1),B=l.useRef(null),z=l.useRef([]),[R,_]=l.useState(null),[K,E]=l.useState(0),D=l.useRef(typeof window>"u"?{}:Xk(k)),$=l.useMemo(()=>new Map(e.map(J=>[J.tabKey,J])),[e]),I=l.useMemo(()=>{const J=S.current;return J?J.groups.some(te=>{try{const ie=te.model.location.type;return ie!=="floating"&&ie!=="popout"?!1:te.panels.some(pe=>$.has(pe.id))}catch{return!1}}):!1},[$,K,e]),G=l.useCallback(()=>{var J;(J=S.current)==null||J.focus()},[]),Y=l.useCallback((J,te)=>{f==null||f(J,te)},[f]),Z=l.useCallback(J=>{const te=document,ie=J.document;for(const Me of te.querySelectorAll('link[rel="stylesheet"]')){const Be=ie.createElement("link");Be.rel="stylesheet",Be.href=Me.href,Me.crossOrigin&&(Be.crossOrigin=Me.crossOrigin),ie.head.appendChild(Be)}for(const Me of te.querySelectorAll("style")){const Be=ie.createElement("style");Be.textContent=Me.textContent,ie.head.appendChild(Be)}const pe=[];for(const Me of te.styleSheets)try{for(const Be of Me.cssRules)Be instanceof CSSStyleRule&&(Be.selectorText===":root"||Be.selectorText==="html")&&pe.push(Be.cssText)}catch{}if(pe.length>0){const Me=ie.createElement("style");Me.textContent=pe.join(`
66
- `),ie.head.appendChild(Me)}const ge=te.documentElement.getAttribute("data-theme");ge&&ie.documentElement.setAttribute("data-theme",ge),ie.documentElement.style.colorScheme=ge==="light"?"light":"dark",ie.body.className=te.body.className;const Ae=te.documentElement.getAttribute("style");Ae&&ie.documentElement.setAttribute("style",Ae);const De=ie.getElementById("dv-popout-window");De instanceof HTMLElement&&(De.classList.add("adhdev-dockview"),vo(De,b))},[b]),q=l.useCallback(()=>{var te;const J=S.current;if(J)for(const ie of J.groups)try{const pe=(te=ie.element)==null?void 0:te.ownerDocument;if(!pe||pe===document)continue;const ge=pe.getElementById("dv-popout-window");ge instanceof HTMLElement&&(ge.classList.add("adhdev-dockview"),vo(ge,b));const Ae=document.documentElement.getAttribute("data-theme");Ae&&pe.documentElement.setAttribute("data-theme",Ae),pe.documentElement.style.colorScheme=Ae==="light"?"light":"dark",pe.body.className=document.body.className;const De=document.documentElement.getAttribute("style");De?pe.documentElement.setAttribute("style",De):pe.documentElement.removeAttribute("style")}catch{}},[b]),ne=l.useCallback(J=>{const te=S.current;if(!te)return;const ie=te.getPanel(J);ie&&te.addPopoutGroup(ie,{popoutUrl:"/popout.html",onDidOpen:({window:pe})=>{Z(pe),ke();const ge=$.get(J);pe.document.title=ge?`${gt(ge)} — ADHDev`:"ADHDev — Popout"}})},[$,Z]),ue=l.useCallback(J=>{const te=S.current,ie=te==null?void 0:te.getPanel(J);if(!te||!ie)return;const pe=te.groups.filter(ge=>{var Ae;try{return((Ae=ge.element)==null?void 0:Ae.ownerDocument)===document}catch{return!0}});pe.length>0?ie.api.moveTo({group:pe[0],position:"center"}):ie.api.moveTo({position:"center"}),ie.api.setActive()},[]),ae=l.useCallback(J=>{var pe;const te=S.current;if(!te)return!1;const ie=te.getPanel(J);if(!ie)return!1;try{return((pe=ie.group.element)==null?void 0:pe.ownerDocument)!==document}catch{return!1}},[]),O=l.useCallback(J=>{ae(J)&&ue(J),d(J)},[ae,ue,d]),se=l.useCallback(J=>{const te=S.current,ie=te==null?void 0:te.getPanel(J);!te||!ie||te.addFloatingGroup(ie,{width:600,height:500})},[]),X=l.useCallback(J=>{var ie;const te=(ie=S.current)==null?void 0:ie.getPanel(J);if(!te)return!1;try{return te.group.model.location.type==="floating"}catch{return!1}},[]),oe=l.useCallback(()=>{var te,ie;const J=(ie=(te=S.current)==null?void 0:te.activePanel)==null?void 0:ie.id;return!J||rs(J)?null:$.has(J)?J:null},[$]),Se=l.useCallback(J=>{const te=S.current,ie=te==null?void 0:te.getPanel(J);if(!te||!ie)return;const pe=te.groups.filter(ge=>{try{return ge.model.location.type==="grid"}catch{return!0}});pe.length>0?ie.api.moveTo({group:pe[0],position:"center"}):ie.api.moveTo({position:"center"}),ie.api.setActive()},[]),ye=l.useCallback(()=>{var Ae;const J=S.current;if(!J)return;const ie=J.groups.filter(De=>{var Me;try{return((Me=De.element)==null?void 0:Me.ownerDocument)===document&&De.model.location.type==="grid"}catch{return!1}})[0]||null,pe=[...J.panels];for(const De of pe){const Me=(Ae=De.group.element)==null?void 0:Ae.ownerDocument,Be=De.group.model.location.type;Me===document&&Be==="grid"||(ie&&ie.id!==De.group.id?De.api.moveTo({group:ie,position:"center"}):De.api.moveTo({position:"center"}))}const ge=J.activePanel;ge&&(ge.group.model.openPanel(ge),ge.api.setActive()),yo(document)},[]),ke=l.useCallback(()=>{var te,ie;const J=S.current;if(J)for(const pe of J.groups){const ge=(te=pe.element)==null?void 0:te.ownerDocument;if(!ge||ge===document)continue;const Ae=ge.getElementById("dv-popout-window");if(!(Ae instanceof HTMLElement))continue;let De=null,Me=ge.title||"ADHDev",Be="Popout workspace";const We=pe.activePanel;if(We)if(De=We.id,rs(We.id)){const ee=((ie=We.params)==null?void 0:ie.routeId)||We.id.slice(7),xe=cs([...$.values()],ee);Me=cp(xe),Be=xe!=null&&xe.machineName?`Remote view · ${xe.machineName}`:"Remote view"}else{const ee=$.get(We.id);Me=ee?gt(ee):We.title||We.id,Be=ee?Ks(ee):"Dockview panel"}ge.title=`${Me} — ADHDev`;const Ze=Array.from(ge.querySelectorAll("#adhdev-popout-header"));for(const ee of Ze)ee.remove();const _e=ge.createElement("div");_e.id="adhdev-popout-header",ge.body.appendChild(_e),_e.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(";")),_e.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(Me)}</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(Be)}</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
- `,Ae.style.top="52px",Ae.style.height="calc(100% - 52px)";const Ue=_e.querySelector("[data-adhdev-popout-focus]");Ue&&(Ue.onclick=()=>{window.focus()});const et=_e.querySelector("[data-adhdev-popout-dock]");et&&(et.disabled=!De,et.style.opacity=De?"1":"0.5",et.style.cursor=De?"pointer":"default",et.onclick=()=>{var ee;De&&ue(De),(ee=ge.defaultView)==null||ee.focus()})}},[$,ue]),me=l.useCallback(J=>{var pe;const te=S.current,ie=te==null?void 0:te.getPanel(J);if(!(!te||!ie)){ie.group.model.openPanel(ie),ie.api.setActive(),Y(J,"dockview-shortcut");try{const ge=ie.group.model.location;ge.type==="popout"?ge.getWindow().focus():yo((pe=ie.group.element)==null?void 0:pe.ownerDocument)}catch{}}},[Y]),U=l.useCallback(J=>{const te=S.current,ie=te==null?void 0:te.activePanel,pe=(te==null?void 0:te.activeGroup)||(ie==null?void 0:ie.group);if(!te||!ie||!pe)return;const ge=pe.panels||[];if(ge.length<=1)return;const Ae=ge.findIndex(Be=>Be.id===ie.id);if(Ae<0)return;const De=(Ae+J+ge.length)%ge.length,Me=ge[De];Me&&(Me.group.model.openPanel(Me),Me.api.setActive(),rs(Me.id)||Y(Me.id,"dockview-shortcut"))},[Y]),W=l.useCallback(J=>{var Ue;const te=S.current,ie=(te==null?void 0:te.activeGroup)||((Ue=te==null?void 0:te.activePanel)==null?void 0:Ue.group);if(!te||!ie)return;const pe=te.groups||[],ge=pe.find(et=>et.id===ie.id);if(!ge)return;const Ae=ge.element.getBoundingClientRect(),De=Ae.left+Ae.width/2,Me=Ae.top+Ae.height/2,Be=(et,ee,xe,we)=>Math.max(0,Math.min(ee,we)-Math.max(et,xe)),We=et=>{const ee=et.element.getBoundingClientRect(),xe=ee.left+ee.width/2,we=ee.top+ee.height/2;let Ge=0,He=0,tt=0,ze=!1;if(J==="left"?(ze=xe<De,Ge=Math.max(0,Ae.left-ee.right),He=Math.abs(we-Me),tt=Be(Ae.top,Ae.bottom,ee.top,ee.bottom)):J==="right"?(ze=xe>De,Ge=Math.max(0,ee.left-Ae.right),He=Math.abs(we-Me),tt=Be(Ae.top,Ae.bottom,ee.top,ee.bottom)):J==="above"?(ze=we<Me,Ge=Math.max(0,Ae.top-ee.bottom),He=Math.abs(xe-De),tt=Be(Ae.left,Ae.right,ee.left,ee.right)):(ze=we>Me,Ge=Math.max(0,ee.top-Ae.bottom),He=Math.abs(xe-De),tt=Be(Ae.left,Ae.right,ee.left,ee.right)),!ze)return Number.POSITIVE_INFINITY;const qe=tt>0?0:120;return Ge*3+He+qe};let Ze=null,_e=Number.POSITIVE_INFINITY;for(const et of pe){if(et.id===ge.id)continue;const ee=We(et);Number.isFinite(ee)&&(ee>=_e||(_e=ee,Ze=et))}return Ze||void 0},[]),Q=l.useCallback(J=>{var pe;const te=W(J);if(!te)return;const ie=te.activePanel||te.panels[0];ie&&(te.model.openPanel(ie),ie.api.setActive(),rs(ie.id)||Y(ie.id,"dockview-focus"),yo((pe=te.element)==null?void 0:pe.ownerDocument))},[W,Y]),V=l.useCallback((J,te)=>{const ie=S.current,pe=ie==null?void 0:ie.activePanel,ge=(ie==null?void 0:ie.activeGroup)||(pe==null?void 0:pe.group);if(!ie||!pe||!ge)return;let Ae=W(J);!Ae&&(te!=null&&te.createGroupIfMissing)&&(Ae=ie.addGroup({referenceGroup:ge,direction:J})),Ae&&(pe.api.moveTo({group:Ae,position:"center"}),pe.group.model.openPanel(pe),pe.api.setActive(),rs(pe.id)||Y(pe.id,te!=null&&te.createGroupIfMissing?"dockview-split":"dockview-move"))},[W,Y]),{isMac:fe,tabShortcuts:ce,shortcutListening:F,setShortcutListening:le,saveShortcuts:je}=rh({sortedTabKeys:e.map(J=>J.tabKey),onFocus:G,onSelectTab:me}),de=l.useCallback(()=>{var ie;const J=S.current;if(!J)return;const te=J.activePanel;if(te){if(rs(te.id)){const pe=((ie=te.params)==null?void 0:ie.routeId)||te.id.slice(7),ge=cs(e,pe);ge!=null&&ge.tabKey&&le(ge.tabKey);return}$.has(te.id)&&le(te.id)}},[$,me,le,e]),H=l.useCallback(J=>{const te=[];return J.metaKey&&te.push(fe?"⌘":"Meta"),J.ctrlKey&&te.push("Ctrl"),J.altKey&&te.push(fe?"⌥":"Alt"),J.shiftKey&&J.key.length!==1&&te.push(fe?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(J.key)?null:(te.push(ih(J.key)),te.join("+"))},[fe]),be=l.useCallback(J=>{var te,ie;switch(J){case"splitActiveTabRight":V("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":V("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const pe=oe();pe&&se(pe);return}case"popoutActiveTab":{const pe=oe();pe&&ne(pe);return}case"dockActiveTab":{const pe=oe();if(!pe)return;ae(pe)?ue(pe):X(pe)&&Se(pe);return}case"focusLeftPane":Q("left");return;case"focusRightPane":Q("right");return;case"focusUpPane":Q("above");return;case"focusDownPane":Q("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":de();return;case"hideCurrentTab":{const pe=(ie=(te=S.current)==null?void 0:te.activePanel)==null?void 0:ie.id;pe&&!rs(pe)&&O(pe);return}default:return}},[U,Se,Q,se,oe,O,X,ae,ue,V,ne,de]);l.useEffect(()=>{if(!R)return;const J=R.sourceDocument,te=J.defaultView??window,ie=pe=>{const ge=J.querySelector("[data-dockview-tab-context-menu]");ge&&ge.contains(pe.target)||_(null)};return te.addEventListener("mousedown",ie,!0),te!==window&&window.addEventListener("mousedown",()=>_(null),!0),()=>{te.removeEventListener("mousedown",ie,!0),te!==window&&window.removeEventListener("mousedown",()=>_(null),!0)}},[R]);const Ne=l.useMemo(()=>({actionLogs:r,clearedTabs:t,conversationsByTabKey:$,hasDetachedConversationPanels:I,ides:n,isStandalone:i,hasRegisteredMachines:u,onOpenNewSession:v,liveSessionInboxState:N,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:O,userName:p,scrollToBottomRequest:w,tabShortcuts:ce,openTabContextMenu:({x:J,y:te,tabKey:ie,sourceDocument:pe})=>_({x:J,y:te,tabKey:ie,sourceDocument:pe??document}),popoutTab:ne,moveTabBackToMain:ue,isTabInPopout:ae,floatTab:se,isTabFloating:X}),[r,t,$,I,n,i,u,v,N,a,o,O,p,w,ce,ne,ue,ae,se,X]),Ce=R?yS({isTabInPopout:ae(R.tabKey),isTabFloating:X(R.tabKey),tabShortcut:ce[R.tabKey],actionShortcuts:m}):[],$e=l.useCallback(J=>{var pe;const te=S.current;if((((pe=te==null?void 0:te.activePanel)==null?void 0:pe.id)??null)===J.id){J.group.model.openPanel(J);return}J.group.model.openPanel(J),J.api.setActive()},[]),Qe=l.useCallback((J,te="requested-tab")=>{if(!J)return!1;const ie=S.current;if(!ie)return!1;const pe=ie.getPanel(J);return pe?($e(pe),Y(J,te),x==null||x(),!0):!1},[$e,x,Y]),dt=l.useCallback(()=>{if(P.current)return!1;const J=Qe(B.current,"stored-layout-restore");return J&&(P.current=!0),J},[Qe]),it=l.useCallback(()=>{var te;const J=S.current;J&&Jk(k,{activeTabId:((te=J.activePanel)==null?void 0:te.id)??null,layout:J.toJSON()})},[k]),he=l.useCallback(()=>{Qk(k,D.current)},[k]),Ee=l.useCallback(J=>{var pe,ge,Ae,De;const te=S.current;if(!te)return{kind:"grid"};const ie=te.toJSON();for(const Me of ie.floatingGroups||[])if((ge=(pe=Me.data)==null?void 0:pe.views)!=null&&ge.includes(J)&&Me.position)return{kind:"floating",position:Me.position};for(const Me of ie.popoutGroups||[])if((De=(Ae=Me.data)==null?void 0:Ae.views)!=null&&De.includes(J))return{kind:"popout",position:Me.position,popoutUrl:Me.url};return{kind:"grid"}},[]),Fe=l.useCallback(J=>{const te=S.current;if(!te)return;const ie=te.getPanel(J),pe=D.current[J];if(!ie||!pe||pe.kind==="grid")return;if(ie.group.model.location.type===pe.kind){delete D.current[J],he();return}if(pe.kind==="floating"){te.addFloatingGroup(ie,{x:pe.position.left??24,y:pe.position.top??24,width:pe.position.width,height:pe.position.height}),delete D.current[J],he();return}delete D.current[J],he()},[he]);l.useEffect(()=>(h==null||h({setShortcutForActiveTab:de,restoreHiddenTabToSavedLocation:Fe,activateConversationTab:me,resetAllPanelsToMain:ye,activatePreviousTabInGroup:()=>U(-1),activateNextTabInGroup:()=>U(1),floatActiveTab:()=>{const J=oe();J&&se(J)},popoutActiveTab:()=>{const J=oe();J&&ne(J)},dockActiveTab:()=>{const J=oe();J&&(ae(J)?ue(J):X(J)&&Se(J))},splitActiveTabRight:()=>V("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>V("below",{createGroupIfMissing:!0}),focusLeftPane:()=>Q("left"),focusRightPane:()=>Q("right"),focusUpPane:()=>Q("above"),focusDownPane:()=>Q("below"),moveActiveTabToLeftPane:()=>V("left"),moveActiveTabToRightPane:()=>V("right"),moveActiveTabToUpPane:()=>V("above"),moveActiveTabToDownPane:()=>V("below")}),()=>h==null?void 0:h(null)),[U,Se,se,Q,oe,X,ae,V,ue,ne,h,ye,Fe,me,de]),l.useEffect(()=>()=>{var J;(J=A.current)==null||J.call(A),A.current=null},[]);const Ie=l.useCallback(J=>{var ie,pe;S.current=J.api,(ie=A.current)==null||ie.call(A),A.current=null;const te=Yk(k);if(B.current=(te==null?void 0:te.activeTabId)??null,te!=null&&te.layout&&J.api.fromJSON(te.layout,{reuseExistingPanels:!1}),L.current=Uc({hasStoredLayout:!!(te!=null&&te.layout),initialDataLoaded:c,visibleConversationCount:e.length,ides:n}),L.current||(qc(J.api,e),Yc(J.api,e,j)),J.api.totalPanels===0&&e.length>0){const ge=NS(J.api,e,y);if(ge){const Ae=J.api.getPanel(ge);Ae&&$e(Ae)}}else!L.current&&!Qe(y)&&dt();if(T.current=!0,J.api.onDidActivePanelChange(ge=>{var De;if(B.current=(ge==null?void 0:ge.id)??null,P.current=!0,ke(),ge&&rs(ge.id)){const Me=((De=ge.params)==null?void 0:De.routeId)||ge.id.slice(7),Be=cs(e,Me);g((Be==null?void 0:Be.tabKey)??null),it();return}if(g((ge==null?void 0:ge.id)??null),it(),!ge)return;const Ae=$.get(ge.id);(Ae==null?void 0:Ae.streamSource)==="agent-stream"&&Ae.agentType&&C(Ae.routeId,Hu(),{agentType:Ae.agentType,...Ae.sessionId&&{targetSessionId:Ae.sessionId}}).catch(()=>{})}),J.api.onDidLayoutChange(()=>{it(),ke(),E(ge=>ge+1)}),jS()){const ge=_e=>({clientX:_e.clientX,clientY:_e.clientY}),Ae=_e=>{const Ue=_e==null?void 0:_e.getBoundingClientRect();return Ue?{left:Ue.left,right:Ue.right,top:Ue.top,bottom:Ue.bottom}:null},De=_e=>{var et;const Ue=(et=M.current)==null?void 0:et.getBoundingClientRect();return Ue?_e.clientX<Ue.left||_e.clientX>Ue.right||_e.clientY<Ue.top||_e.clientY>Ue.bottom:!1},Me=kS({detachDelayMs:ch,onDetach:({panelId:_e,clientX:Ue,clientY:et})=>{var tt,ze;const ee=J.api.getPanel(_e);if(!ee)return;try{if(ee.group.model.location.type!=="grid")return}catch{return}const xe=(tt=M.current)==null?void 0:tt.getBoundingClientRect(),we=(ze=ee.group.element)==null?void 0:ze.getBoundingClientRect(),Ge=Math.round(Math.min(Math.max((we==null?void 0:we.width)??600,360),720)),He=Math.round(Math.min(Math.max((we==null?void 0:we.height)??500,260),640));J.api.addFloatingGroup(ee,{x:xe?Math.max(0,Ue-xe.left-32):void 0,y:xe?Math.max(0,et-xe.top-18):void 0,width:Ge,height:He}),ee.api.setActive(),it(),ke(),E(qe=>qe+1)}}),Be=[J.api.onWillDragPanel(_e=>{if(!(_e.nativeEvent.defaultPrevented||_e.nativeEvent.shiftKey)){try{if(_e.panel.group.model.location.type!=="grid")return}catch{return}Me.startDrag({panelId:_e.panel.id,selfPanelBounds:Ae(_e.panel.group.element),...ge(_e.nativeEvent)})}}),J.api.onWillShowOverlay(_e=>{if(Me.hasDetached()){_e.preventDefault();return}Me.markDockTarget(ge(_e.nativeEvent))}),J.api.onWillDrop(_e=>{if(Me.hasDetached()){_e.preventDefault(),Me.endDrag();return}Me.markDockTarget(ge(_e.nativeEvent))}),J.api.onDidDrop(()=>Me.endDrag()),J.api.onUnhandledDragOverEvent(_e=>{Me.isDragging()&&Me.markSelfPanel(ge(_e.nativeEvent))})],We=_e=>{if(!Me.isDragging())return;const Ue=ge(_e);De(Ue)&&Me.markNonSelfPanel(Ue)},Ze=()=>Me.endDrag();window.addEventListener("dragover",We,!0),window.addEventListener("drop",Ze,!0),window.addEventListener("dragend",Ze,!0),A.current=()=>{Me.dispose();for(const _e of Be)_e.dispose();window.removeEventListener("dragover",We,!0),window.removeEventListener("drop",Ze,!0),window.removeEventListener("dragend",Ze,!0)}}J.api.onDidAddGroup(ge=>{requestAnimationFrame(()=>{var Ae,De;try{const Me=(Ae=ge.element)==null?void 0:Ae.ownerDocument;if(!Me||Me===document)return;(De=Me.getElementById("dv-popout-window"))==null||De.classList.add("adhdev-dockview");const Be=document.documentElement.getAttribute("data-theme");Be&&Me.documentElement.setAttribute("data-theme",Be),Me.body.className=document.body.className;const We=document.documentElement.getAttribute("style");We&&Me.documentElement.setAttribute("style",We)}catch{}ke(),E(Me=>Me+1)})}),g(((pe=J.api.activePanel)==null?void 0:pe.id)??null)},[$e,Qe,$,n,c,k,g,it,y,j,C,ke,e]);l.useLayoutEffect(()=>{const J=S.current;if(!J||!T.current||L.current&&Uc({hasStoredLayout:!0,initialDataLoaded:c,visibleConversationCount:e.length,ides:n}))return;L.current&&(L.current=!1);const te=z.current,ie=new Set(te),pe=e.map(Ze=>Ze.tabKey),ge=new Set(pe),Ae=vS({previousVisibleConversationCount:te.length,visibleConversationCount:e.length,ides:n});let De=!1;for(const Ze of te)ge.has(Ze)||Ae||(D.current[Ze]=Ee(Ze),De=!0);De&&he(),Ae||(qc(J,e),Yc(J,e,j));const Me=pe.filter(Ze=>!ie.has(Ze));let Be=!1;for(const Ze of Me){const _e=J.getPanel(Ze),Ue=D.current[Ze];if(!_e||!Ue||Ue.kind==="grid")continue;if(_e.group.model.location.type===Ue.kind){delete D.current[Ze],Be=!0;continue}if(Ue.kind==="floating"){J.addFloatingGroup(_e,{x:Ue.position.left??24,y:Ue.position.top??24,width:Ue.position.width,height:Ue.position.height}),delete D.current[Ze],Be=!0;continue}}if(Be&&he(),z.current=pe,y&&Qe(y))return;!J.activePanel&&J.panels[0]&&$e(J.panels[0]),!!(J.activePanel&&J.getPanel(J.activePanel.id))||dt()},[$e,Qe,dt,n,c,he,Ee,y,j,e]),l.useEffect(()=>{T.current&&Qe(y)},[Qe,y]),l.useEffect(()=>{const J=ie=>{const pe=ie.target;if(!pe)return;const ge=pe.querySelector("[data-tab-key]")||pe.closest("[data-tab-key]");if(ge){const Ae=ge.getAttribute("data-tab-key");if(Ae&&ie.dataTransfer){const De=pe.closest(".dv-tab")||ge.closest(".dv-tab")||ge;ie.dataTransfer.effectAllowed="move",ie.dataTransfer.setData("text/tab-key",Ae),De instanceof HTMLElement&&ie.dataTransfer.setDragImage(De,Math.max(12,Math.round(De.clientWidth/2)),Math.max(10,Math.round(De.clientHeight/2)))}}};window.addEventListener("dragstart",J);const te=Vc(S.current);for(const ie of te)ie.addEventListener("dragstart",J);return()=>{window.removeEventListener("dragstart",J);for(const ie of te)ie.removeEventListener("dragstart",J)}},[K]),l.useEffect(()=>{var te;const J=(te=M.current)==null?void 0:te.querySelector(".adhdev-dockview");J instanceof HTMLElement&&vo(J,b),q(),ke()},[ke,q,b]),l.useEffect(()=>{ke()},[ke]),l.useEffect(()=>{const J=te=>{if(te.defaultPrevented||F)return;const ie=H(te);if(!ie)return;const pe=te.metaKey||te.ctrlKey||te.altKey;mi(te.target)&&!pe||ga(fe).setActiveTabShortcut!==ie||(te.preventDefault(),te.stopPropagation(),de())};return window.addEventListener("keydown",J,!0),()=>window.removeEventListener("keydown",J,!0)},[H,fe,F,de]),l.useEffect(()=>{const J=M.current;if(!J)return;const te=ie=>{var Me,Be;if(!ie.isTrusted)return;const pe=(Be=(Me=ie.target)==null?void 0:Me.closest)==null?void 0:Be.call(Me,".dv-scrollable");if(!pe)return;ie.preventDefault(),ie.stopPropagation();const ge=Math.abs(ie.deltaX),Ae=Math.abs(ie.deltaY),De=ge>Ae?ie.deltaX:ie.deltaY;pe.dispatchEvent(new WheelEvent("wheel",{deltaY:De,deltaMode:ie.deltaMode,bubbles:!1,cancelable:!0}))};return J.addEventListener("wheel",te,{passive:!1,capture:!0}),()=>J.removeEventListener("wheel",te,{capture:!0})},[]),l.useEffect(()=>{const J=Vc(S.current);if(J.length===0)return;const te=J.map(ie=>{let pe=[],ge=null;const Ae=()=>{ge!=null&&ie.clearTimeout(ge),ge=null,pe=[]},De=()=>{ge!=null&&ie.clearTimeout(ge),ge=ie.setTimeout(()=>{ge=null,pe=[]},1200)},Me=We=>{if(!We.ctrlKey&&!We.metaKey&&!We.altKey)return;const Ze=H(We);if(!Ze)return;const _e=nh();for(const[Ue,et]of Object.entries(_e))if(e.some(ee=>ee.tabKey===Ue)&&et===Ze){We.preventDefault(),me(Ue);return}},Be=We=>{if(We.defaultPrevented||F)return;const Ze=H(We);if(!Ze)return;const _e=We.metaKey||We.ctrlKey||We.altKey;if(mi(We.target))return;const Ue=ga(fe),et=Object.entries(Ue).filter(([qe,At])=>!!At&&(qe==="splitActiveTabRight"||qe==="splitActiveTabDown"||qe==="floatActiveTab"||qe==="popoutActiveTab"||qe==="dockActiveTab"||qe==="focusLeftPane"||qe==="focusRightPane"||qe==="focusUpPane"||qe==="focusDownPane"||qe==="moveActiveTabToLeftPane"||qe==="moveActiveTabToRightPane"||qe==="moveActiveTabToUpPane"||qe==="moveActiveTabToDownPane"||qe==="selectPreviousGroupTab"||qe==="selectNextGroupTab"||qe==="setActiveTabShortcut"||qe==="hideCurrentTab")),ee=_e?[Ze]:[...pe.slice(-1),Ze].slice(-2),xe=ee.join(" "),we=ee[ee.length-1],Ge=et.find(([,qe])=>qe===xe);if(Ge){We.preventDefault(),Ae(),be(Ge[0]);return}if(et.some(([,qe])=>qe.startsWith(`${xe} `))){We.preventDefault(),pe=ee,De();return}const tt=et.find(([,qe])=>qe===we);if(tt){We.preventDefault(),Ae(),be(tt[0]);return}if(et.some(([,qe])=>qe.startsWith(`${we} `))){We.preventDefault(),pe=[we],De();return}Ae()};return ie.addEventListener("keydown",Me),ie.addEventListener("keydown",Be),()=>{Ae(),ie.removeEventListener("keydown",Me),ie.removeEventListener("keydown",Be)}});return()=>{for(const ie of te)ie()}},[H,fe,K,me,F,be,e]);const ve=b==="light"?Bo:Ho,Oe=((pt=(ot=(ut=S.current)==null?void 0:ut.activePanel)==null?void 0:ot.group.element)==null?void 0:pt.ownerDocument)??document;return s.jsxs(uh.Provider,{value:Ne,children:[s.jsx("div",{ref:M,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(Nm,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:PS,remote:MS},defaultTabComponent:IS,watermarkComponent:AS,onReady:Ie,singleTabMode:"default",tabAnimation:"smooth",theme:ve,popoutUrl:"/popout.html"})}),R&&fn.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:R.x,top:R.y},children:Ce.map(J=>{if(J.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},J.id);let te=s.jsx(Yf,{size:13,className:"shrink-0 opacity-70"}),ie=()=>{};switch(J.id){case"dockInWindow":case"dockBackToGrid":te=s.jsx(Xf,{size:13,className:"shrink-0 opacity-70"}),ie=()=>{Se(R.tabKey),_(null)};break;case"moveBackToMain":te=s.jsx(qf,{size:13,className:"shrink-0 opacity-70"}),ie=()=>{ue(R.tabKey),_(null)};break;case"floatAsPanel":te=s.jsx(Jf,{size:13,className:"shrink-0 opacity-70"}),ie=()=>{se(R.tabKey),_(null)};break;case"openInNewWindow":te=s.jsx(Vf,{size:13,className:"shrink-0 opacity-70"}),ie=()=>{ne(R.tabKey),_(null)};break;case"setShortcut":ie=pe=>{pe.stopPropagation(),le(R.tabKey),_(null)};break;case"removeShortcut":te=s.jsx(Mt,{size:13,className:"shrink-0 opacity-70"}),ie=()=>{const pe={...ce};delete pe[R.tabKey],je(pe),_(null)};break;case"hideTab":te=s.jsx(Ai,{size:13,className:"shrink-0 opacity-70"}),ie=()=>{O(R.tabKey),_(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 ${J.tone==="muted"?"text-text-muted":""}`,onMouseDown:TS,onClick:ie,children:[te,s.jsx("span",{className:"flex-1 min-w-0",children:J.label}),J.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:J.shortcut}):null]},J.id)})}),R.sourceDocument.body),F&&fn.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:()=>le(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:J=>J.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. ",fe?"⌘+1":"Ctrl+1",", ",fe?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),Oe.body)]})}const ph="adhdev-recent-launch-args-v1",LS=8;function RS(e){return String(e||"").trim().replace(/\s+/g," ")}function hh(e,t){return`${e.trim()}::${t.trim()}`}function mh(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(ph)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function _S(e){if(!(typeof window>"u"))try{window.localStorage.setItem(ph,JSON.stringify(e))}catch{}}function ES(e,t){var o;const n=String(e||"").trim(),r=String(t||"").trim();return!n||!r?[]:((o=mh().byKey[hh(n,r)])==null?void 0:o.items)||[]}function $S(e,t,n){var d;const r=String(e||"").trim(),a=String(t||"").trim(),o=RS(n);if(!r||!a||!o)return;const i=mh(),u=hh(r,a),c=((d=i.byKey[u])==null?void 0:d.items)||[],p=[o,...c.filter(m=>m!==o)].slice(0,LS);i.byKey[u]={items:p},_S(i)}function FS(e){return!e.hasLoadedInitialResults&&!e.isLoading}function qn({title:e,description:t,action:n,children:r,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})]}),n?s.jsx("div",{className:"flex items-center gap-2",children:n}):null]}),r?s.jsx("div",{className:t||n?`mt-3 ${o}`.trim():o,children:r}):null]})}function BS({savedSessionsLoading:e,savedSessionsLoaded:t,savedSessionsCount:n=0}){return e?"Refreshing saved history…":t?n>0?`${n} saved ${n===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 HS({busy:e,savedSessionsLoading:t,savedSessionsError:n,savedSessionsLoaded:r,savedSessionsCount:a=0,selectedSession:o,onRefresh:i,onOpenHistory:u,onClearSelection:c}){const{t:p}=Xe("common"),d=o?Xp(o):null,m=BS({savedSessionsLoading:t,savedSessionsLoaded:r,savedSessionsCount:a});return s.jsxs(qn,{title:"Saved history",description:zi(p),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:u,children:ow(p)})]}),children:[d?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:d.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:d.providerSessionId}),s.jsx("div",{className:"mt-1",children:d.metaLine}),d.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:d.updatedLabel}),d.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:d.preview})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:c,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:m}),n&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:n})]})}function fh({setup:e,providerName:t,className:n=""}){return e?s.jsxs("div",{className:`rounded-xl border border-accent/25 bg-accent/10 px-4 py-3 text-sm text-text-primary ${n}`,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 OS({workspaceMode:e,activeKind:t,cliEnabled:n,ideEnabled:r,acpEnabled:a,busy:o,onSelect:i}){const{t:u}=Xe();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:u("newSession.category")}),s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:wo.cli,enabled:n},{id:"ide",label:wo.ide,enabled:r},{id:"acp",label:wo.acp,enabled:a}].map(c=>s.jsx("button",{type:"button",className:`btn btn-sm ${t===c.id?"btn-primary":"btn-secondary"}`,onClick:()=>i(c.id),disabled:!c.enabled||o,children:c.label},c.id))})]})}function ko(e){var r;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>jn(a,"cli"))?"cli":(((r=e.detectedIdes)==null?void 0:r.length)||0)>0?"ide":t.some(a=>jn(a,"acp"))?"acp":null}function Er(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function WS({machines:e,ides:t,onClose:n,onBrowseDirectory:r,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:i,onListMeshes:u,onLaunchMeshCoordinator:c,onListSavedSessions:p}){var Nt,Wt;const{t:d}=Xe(),m=In(),h=l.useMemo(()=>[...e].sort(_i),[e]),[g,v]=l.useState(((Nt=h[0])==null?void 0:Nt.id)||""),f=l.useMemo(()=>h.find(re=>re.id===g)||h[0],[g,h]),y=l.useMemo(()=>((f==null?void 0:f.workspaces)||[]).map(re=>({id:re.id,path:re.path,label:re.label})),[f]),j=(f==null?void 0:f.defaultWorkspaceId)||null,[x,w]=l.useState("workspace"),[N,k]=l.useState(""),[b,C]=l.useState(""),[S,M]=l.useState([]),[A,T]=l.useState(""),[L,P]=l.useState(!1),[B,z]=l.useState(null),[R,_]=l.useState(""),[K,E]=l.useState(ko(h[0])),[D,$]=l.useState(""),[I,G]=l.useState(""),[Y,Z]=l.useState(""),[q,ne]=l.useState(""),[ue,ae]=l.useState(!1),[O,se]=l.useState([]),[X,oe]=l.useState(""),[Se,ye]=l.useState([]),[ke,me]=l.useState(!1),[U,W]=l.useState(!1),[Q,V]=l.useState(""),[fe,ce]=l.useState(!1),[F,le]=l.useState(()=>Bt()),[je,de]=l.useState(null),[H,be]=l.useState(!1),[Ne,Ce]=l.useState(""),[$e,Qe]=l.useState("error"),[dt,it]=l.useState(null),[he,Ee]=l.useState(!1),[Fe,Ie]=l.useState(""),[ve,Oe]=l.useState([]),[ut,ot]=l.useState(!1),[pt,J]=l.useState(""),[te,ie]=l.useState(!1),pe=l.useRef(null),ge=l.useRef(0);l.useEffect(()=>{var re;!g&&((re=h[0])!=null&&re.id)&&v(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 Ae=l.useCallback(re=>{re&&m(re,{minFreshMs:3e4}).catch(()=>{})},[m]),De=l.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(re=>jn(re,"cli")),[f]),Me=l.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(re=>jn(re,"acp")),[f]),Be=l.useMemo(()=>((f==null?void 0:f.detectedIdes)||[]).map(re=>({id:re.type,label:re.name||re.type,meta:re.running?d("newSession.detectedLocally"):d("newSession.availableToOpen")})),[f,d]),We=l.useMemo(()=>K==="cli"?De.map(re=>({id:re.type,label:re.displayName||re.type,meta:""})):K==="acp"?Me.map(re=>({id:re.type,label:re.displayName||re.type,meta:""})):Be,[Me,K,De,Be]),Ze=l.useMemo(()=>S.find(re=>re.id===A)||null,[S,A]),_e=l.useMemo(()=>De.find(re=>re.type===D)||null,[De,D]),Ue=l.useMemo(()=>[...De,...Me].find(re=>re.type===D),[De,Me,D]),et=l.useMemo(()=>gw(Ue?[Ue]:[],Ue==null?void 0:Ue.type),[Ue]),ee=l.useMemo(()=>{const re=yw(Ue?[Ue]:[],Ue==null?void 0:Ue.type);return re.length?re:["low","medium","high"]},[Ue]),xe=l.useMemo(()=>Gp(_e==null?void 0:_e.meshCoordinator,{meshId:(Ze==null?void 0:Ze.id)||"",workspace:(Ze==null?void 0:Ze.workspace)||""}),[_e,Ze]),we=dt||xe,Ge=l.useCallback(async re=>{P(!0),_("");try{const Ke=await u(re);M(Ke),T(Re=>{var vt;return Ke.some(Jt=>Jt.id===Re)?Re:((vt=Ke[0])==null?void 0:vt.id)||""}),z(re)}catch(Ke){M([]),T(""),z(re),_(Ke instanceof Error?Ke.message:d("newSession.errorLoadMeshes"))}finally{P(!1)}},[u,d]);l.useEffect(()=>{var Ke;if(!f)return;if(pe.current!==f.id){pe.current=f.id,w("workspace"),k(j||((Ke=y[0])==null?void 0:Ke.id)||"__home__"),C(""),M([]),T(""),z(null),_(""),E(ko(f)),$(""),G(""),Z(""),ne(""),ae(!1),oe(""),ye([]),W(!1),V(""),le(Bt()),Ce(""),it(null);return}k(Re=>{var vt;return Re==="__custom__"||Re==="__home__"||y.some(Jt=>Jt.id===Re)?Re:j||((vt=y[0])==null?void 0:vt.id)||"__home__"}),E(Re=>Re==="ide"&&Be.length>0||Re==="cli"&&De.length>0||Re==="acp"&&Me.length>0?Re:ko(f))},[Me.length,De.length,j,Be.length,f,y]),l.useEffect(()=>{!f||x!=="mesh"||B===f.id||L||Ge(f.id)},[Ge,B,L,f,x]),l.useEffect(()=>{x==="mesh"&&K!=="cli"&&De.length>0&&E("cli")},[K,De.length,x]),l.useEffect(()=>{var re;K&&(We.some(Ke=>Ke.id===D)||$(((re=We[0])==null?void 0:re.id)||""))},[K,We,D]),l.useEffect(()=>{it(null)},[f==null?void 0:f.id,A,D,x]),l.useEffect(()=>{Z(""),ne(""),ae(!1)},[D]);const He=l.useCallback(async(re,Ke)=>{const Re=ge.current+1;return ge.current=Re,me(!0),V(""),p(re,Ke).then(vt=>{ge.current===Re&&ye(vt)}).catch(vt=>{ge.current===Re&&(ye([]),V(vt instanceof Error?vt.message:d("newSession.errorLoadSavedSessions")))}).finally(()=>{ge.current===Re&&(me(!1),W(!0))})},[p,d]),tt=l.useCallback((re,Ke)=>{se(ES(re,Ke))},[]);l.useEffect(()=>{ge.current+=1,oe(""),le(Bt()),!f||!D||K==="ide"?se([]):tt(f.id,D),W(!1),ye([]),V(""),me(!1)},[K,tt,He,f,D]),l.useEffect(()=>{if(!X)return;const re=Se.find(Ke=>Ke.providerSessionId===X);re!=null&&re.canResume||oe("")},[Se,X]);const ze=N==="__custom__"?b.trim():N==="__home__"?"":((Wt=y.find(re=>re.id===N))==null?void 0:Wt.path)||"",qe=l.useMemo(()=>f?t.filter(re=>re.id!==f.id&&re.daemonId===f.id).map(re=>re.workspace):[],[t,f]),At=l.useMemo(()=>((f==null?void 0:f.recentLaunches)||[]).map(re=>re.workspace),[f]),Ot=l.useCallback(re=>{const Ke=String(re.workspace||"").trim();if(!Ke)return;const Re=y.find(vt=>Er(vt.path)===Er(Ke));if(Re){k(Re.id),C("");return}k("__custom__"),C(Ke)},[y]),ss=l.useCallback(re=>{const Ke=String(re.workspace||"").trim();if(!Ke)return{workspaceId:null,workspacePath:null};const Re=y.find(vt=>Er(vt.path)===Er(Ke));return Re?{workspaceId:Re.id,workspacePath:null}:{workspaceId:null,workspacePath:Ke}},[y]),Te=l.useMemo(()=>Se.find(re=>re.providerSessionId===X)||null,[Se,X]),Je=l.useMemo(()=>{var Ke;if(K!=="cli"||!f||!D)return null;const re=((Ke=De.find(Re=>Re.type===D))==null?void 0:Ke.displayName)||D;return{routeId:f.id,daemonId:f.id,providerSessionId:X||void 0,transport:"pty",mode:"chat",agentName:re,agentType:D,status:"idle",title:re,messages:[],ideType:D,workspaceName:ze,workspacePath:ze,displayPrimary:re,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${f.id}:${D}`,machineName:ts(f,{fallbackId:f.id})}},[K,De,ze,f,X,D]),Pt=l.useCallback(()=>{var Ke;if(!f)return;k("__custom__"),Ee(!0),J("");const re=tl(f.platform,el(b.trim(),ze,qe,At,f.defaultWorkspacePath,(Ke=y.find(Re=>Re.id===j))==null?void 0:Ke.path,y.map(Re=>Re.path)));ot(!0),r(f.id,re).then(Re=>{Ie(Re.path),C(Re.path),Oe(Re.directories)}).catch(Re=>{J(Re instanceof Error?Re.message:d("newSession.errorLoadFolder"))}).finally(()=>ot(!1))},[b,j,At,qe,r,ze,f,y]),It=l.useCallback(re=>{f&&(ot(!0),J(""),r(f.id,re).then(Ke=>{Ie(Ke.path),C(Ke.path),Oe(Ke.directories)}).catch(Ke=>{J(Ke instanceof Error?Ke.message:d("newSession.errorLoadFolder"))}).finally(()=>ot(!1)))},[r,f]),Vt=l.useCallback(async()=>{if(!f||!ze)return;ie(!0),Ce("");const re=await a(f.id,ze);if(ie(!1),!re.ok){Qe("error"),Ce(re.error||d("newSession.errorSaveWorkspace"));return}Qe("info"),Ce(d("newSession.workspaceSaved"))},[a,ze,f,d]),qt=l.useCallback(async()=>{if(!f)return;if(x==="mesh"){if(!A||!D)return;be(!0),Ce(""),it(null);const Re=await c(f.id,A,D,{initialModel:Y.trim()?Y.trim():null,initialThinkingLevel:q.trim()?q.trim():null});if(be(!1),!Re.ok){if(Re.code==="mesh_coordinator_manual_mcp_setup_required"&&Re.manualSetup){it(Re.manualSetup),Qe("info"),Ce(d("newSession.errorManualMcpSetup"));return}Qe("error"),Ce(Re.error||d("newSession.errorStartMeshCoordinator"));return}n();return}if(!K||!D)return;be(!0),Ce("");const re=I.trim()?I.trim().split(/\s+/).filter(Boolean):[],Ke=K==="ide"?await o(f.id,D,{workspacePath:ze||null}):await i(f.id,K,D,{workspaceId:N!=="__home__"&&N!=="__custom__"?N:null,workspacePath:N==="__custom__"&&ze||null,resumeSessionId:K==="cli"&&X?X:null,cliArgs:re,initialModel:Y.trim()?Y.trim():null,initialThinkingLevel:q.trim()?q.trim():null});if(be(!1),!Ke.ok){Qe("error"),Ce(Ke.error||d("newSession.errorStartSession"));return}K!=="ide"&&I.trim()&&($S(f.id,D,I),tt(f.id,D)),n()},[K,I,Y,q,tt,n,o,c,i,ze,f,A,X,D,N,x,d]),Yt=K==="cli"&&!!X,gs=d(x==="mesh"?"newSession.startMeshCoordinator":K==="cli"?Yt?"newSession.resumeSavedHistory":"newSession.startFresh":K==="ide"?"newSession.startIde":K==="acp"?"newSession.startAcpSession":"newSession.start"),Le=d(x==="mesh"?"newSession.startingCoordinator":K==="cli"?Yt?"newSession.resumingSavedHistory":"newSession.startingFresh":K==="ide"?"newSession.startingIde":K==="acp"?"newSession.startingAcpSession":"newSession.starting"),rt=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:d("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:n,"aria-label":d("newSession.close"),children:s.jsx(Mt,{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(qn,{title:d("newSession.machine"),children:rt?s.jsx("select",{"aria-label":d("newSession.machine"),value:f.id,onChange:re=>v(re.target.value),onFocus:()=>h.forEach(re=>Ae(re.id)),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:H,children:h.map(re=>s.jsx("option",{value:re.id,children:ts(re,{fallbackId:re.id})},re.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":d("newSession.machine"),children:h.map(re=>{const Ke=ts(re,{fallbackId:re.id}),Re=f.id===re.id;return s.jsxs("button",{type:"button","aria-label":d("newSession.selectMachine",{name:Ke}),"aria-pressed":Re,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${Re?"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:()=>v(re.id),onMouseEnter:()=>Ae(re.id),onFocus:()=>Ae(re.id),disabled:H,title:Ke,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${re.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:Ke})]},re.id)})})}),s.jsxs(qn,{title:d("newSession.workspace"),action:x==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Pt,disabled:H,children:d("newSession.browse")}):void 0,children:[s.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2",role:"radiogroup","aria-label":d("newSession.launchTargetType"),children:[{id:"workspace",label:d("newSession.modeWorkspace"),desc:d("newSession.modeWorkspaceDesc")},{id:"mesh",label:d("newSession.modeMesh"),desc:d("newSession.modeMeshDesc")}].map(re=>s.jsxs("button",{type:"button",role:"radio","aria-checked":x===re.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${x===re.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:()=>{w(re.id),Ce(""),re.id==="mesh"&&f&&B!==f.id&&!L&&Ge(f.id)},disabled:H,children:[s.jsx("div",{className:"text-sm font-semibold",children:re.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:re.desc})]},re.id))}),x==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:N,onChange:re=>{const Ke=re.target.value;k(Ke),Ke==="__custom__"?Pt():Ce("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:H,children:[s.jsx("option",{value:"__home__",children:d("newSession.homeDirectory")}),y.map(re=>s.jsxs("option",{value:re.id,children:[re.id===j?"⭐ ":"",gu(re.path,re.label)||re.path]},re.id)),s.jsx("option",{value:"__custom__",children:d("newSession.customFolder")})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:N==="__home__"?d("newSession.launchWithoutWorkspace"):ze||d("newSession.selectWorkspaceFolder")}),N==="__custom__"&&ze&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Pt,disabled:H,children:[s.jsx(gn,{size:14}),d("newSession.selectFolder")]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Vt,disabled:H||te,children:d(te?"newSession.saving":"newSession.saveWorkspace")})]})]}):s.jsxs("div",{className:"space-y-3",children:[L&&s.jsx("div",{className:"text-sm text-text-muted",children:d("newSession.loadingMeshes")}),!L&&R&&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:R}),!L&&!R&&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:d("newSession.noMeshes")}),S.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":d("newSession.mesh"),children:S.map(re=>s.jsxs("button",{type:"button",role:"radio","aria-checked":A===re.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${A===re.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>T(re.id),disabled:H,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:re.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[re.repoIdentity||d("newSession.repoMesh"),typeof re.nodesCount=="number"?` · ${d("newSession.nodeCount",{count:re.nodesCount})}`:""]}),re.workspace&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:d("newSession.coordinatorWorkspace",{path:re.workspace})})]},re.id))})]})]}),s.jsx(OS,{workspaceMode:x,activeKind:K,cliEnabled:De.length>0,ideEnabled:Be.length>0,acpEnabled:Me.length>0,busy:H,onSelect:E}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:d(K==="ide"?"newSession.chooseIde":K==="cli"?"newSession.chooseCliProvider":"newSession.chooseAcpProvider")}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[We.map(re=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${D===re.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>$(re.id),disabled:H,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:re.label}),re.meta&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:re.meta})]},re.id)),We.length===0&&s.jsx("div",{className:"text-sm text-text-muted",children:d("newSession.noProviders")})]})]}),x==="mesh"&&we&&s.jsx(fh,{setup:we,providerName:(_e==null?void 0:_e.displayName)||(_e==null?void 0:_e.name)||D}),x!=="mesh"&&K!=="ide"&&s.jsxs(qn,{title:d("newSession.startupArguments"),children:[s.jsx("input",{type:"text",value:I,onChange:re=>G(re.target.value),placeholder:d("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:H}),O.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:O.map(re=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>G(re),disabled:H,title:re,children:re},re))})]}),(x==="mesh"&&!!D||x!=="mesh"&&K!=="ide")&&s.jsx(qn,{title:d("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:d("newSession.model")}),et.length>0&&!ue?s.jsxs("select",{value:et.includes(Y)?Y:"",onChange:re=>{re.target.value==="__custom__"?(ae(!0),Z("")):Z(re.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:H,children:[s.jsx("option",{value:"",children:d("newSession.providerDefault")}),et.map(re=>s.jsx("option",{value:re,children:re},re)),s.jsx("option",{value:"__custom__",children:d("newSession.custom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:Y,onChange:re=>Z(re.target.value),placeholder:d("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:H,autoFocus:ue}),et.length>0&&s.jsx("button",{type:"button",className:"self-start text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{ae(!1),Z("")},disabled:H,children:d("newSession.backToModelList")})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:d("newSession.thinkingLevel")}),s.jsxs("select",{value:q,onChange:re=>ne(re.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:H,children:[s.jsx("option",{value:"",children:d("newSession.providerDefault")}),ee.map(re=>s.jsx("option",{value:re,children:re},re))]})]})]})}),x!=="mesh"&&K==="cli"&&s.jsx(HS,{busy:H,savedSessionsLoading:ke,savedSessionsError:Q,selectedSession:Te,onRefresh:()=>{!f||!D||He(f.id,D)},onOpenHistory:()=>{!f||!D||(ce(!0),FS({hasLoadedInitialResults:U,isLoading:ke})&&He(f.id,D))},onClearSelection:()=>oe("")}),Ne&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${$e==="info"?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:Ne})]}),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:n,disabled:H,children:d("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:qt,disabled:H||(x==="mesh"?!A||!D||K!=="cli"||L:!K||!D||N==="__custom__"&&!ze),children:[s.jsx(Xd,{size:14}),H?Le:gs]})]})]})}),he&&s.jsx(rl,{title:d("newSession.selectWorkspaceTitle"),description:d("newSession.selectWorkspaceDescription"),currentPath:Fe,directories:ve,busy:ut,error:pt,onClose:()=>Ee(!1),onNavigate:It,onConfirm:re=>{C(re),Ie(re),k("__custom__"),Ee(!1)}}),fe&&Je&&s.jsx(xp,{activeConv:Je,ides:[],isCreatingChat:!1,isRefreshingHistory:ke,savedSessions:Se,isSavedSessionsLoading:ke,isResumingSavedSessionId:je,savedHistoryFilters:F,missingWorkspaceResumePath:ze||null,onSavedHistoryFiltersChange:le,onClose:()=>ce(!1),onNewChat:()=>{oe(""),ce(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!f||!D||He(f.id,D)},onResumeSavedSession:re=>{if(!f||!D||je||!re.canResume)return;const Ke=ss(re);oe(re.providerSessionId),Ot(re),de(re.providerSessionId),ce(!1),be(!0),Ce(""),i(f.id,"cli",D,{workspaceId:Ke.workspaceId,workspacePath:Ke.workspacePath,resumeSessionId:re.providerSessionId}).then(Re=>{if(!Re.ok){Qe("error"),Ce(Re.error||d("newSession.errorResumeSession"));return}n()}).finally(()=>{be(!1),de(Re=>Re===re.providerSessionId?null:Re)})}})]}):null}function xh(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 n=xh(e);return n?{label:n,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 bh(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 $r(e){return[...new Set(e.filter(t=>!!t))]}function US(e){const t=e.nodes.find(i=>i.type==="defaultBranchNode")??null,n=(t==null?void 0:t.branch)??null,r=e.nodes.filter(i=>i.type!=="defaultBranchNode"&&i.type!=="submoduleNode"&&!i.isOrphan&&!!n&&i.branch===n),a=e.nodes.filter(i=>i.type!=="submoduleNode"&&!i.isOrphan),o=e.nodes.filter(i=>i.type!=="submoduleNode");return t||r.length>0?$r([t==null?void 0:t.id,...r.map(i=>i.id)]):a.length>0?$r(a.map(i=>i.id)):o.length>0?$r(o.map(i=>i.id)):$r(e.nodes.map(i=>i.id))}function gh(e){const t=[...e.nodes].sort((r,a)=>r.id.localeCompare(a.id)).map(r=>[r.id,r.type,r.branch??"",r.parentNodeId??"",r.submodulePath??""].join(":")).join("|"),n=[...e.edges].sort((r,a)=>r.id.localeCompare(a.id)).map(r=>[r.id,r.source,r.target,r.type].join(":")).join("|");return`${e.meshId}::${t}::${n}`}function KS(e,t,n){const r=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(n));return`${gh(e)}::${r}x${a}`}const GS={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"},zS={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"},VS={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"},qS={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 Rs(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=>zS[t],actionButton:t=>qS[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=>GS[t],actionButton:t=>VS[t]}}const Sn={worktreeCardWidth:256,submoduleCardWidth:228,minWorktreeCardHeight:174,minSubmoduleCardHeight:146,maxEstimatedCardHeight:304,layerGap:220,nodeGap:82,edgeLabelBuffer:180,placeholderTopOffset:0},gr={worktreeCardWidth:188,submoduleCardWidth:188,minWorktreeCardHeight:88,minSubmoduleCardHeight:88,maxEstimatedCardHeight:178,layerGap:160,nodeGap:52,edgeLabelBuffer:120},YS={maxWidth:180};function JS(e){return e==="TB"?"DOWN":"RIGHT"}function ll(e,t){return{"elk.algorithm":"layered","elk.direction":JS(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 XS=ll(Sn,"LR");ll(gr,"LR");function QS(e){const t=e.nodes.length;if(t<8)return"LR";const n=new Map;for(const a of e.edges)n.set(a.source,(n.get(a.source)??0)+1);let r=0;for(const a of n.values())a>r&&(r=a);return r>=Math.max(6,Math.floor(t/2))?"TB":"LR"}const ZS=new Cm;function ur(e,t=!1){const n=t?gr:Sn;return e.type==="submoduleNode"?n.submoduleCardWidth:n.worktreeCardWidth}function Xr(e){var n;if(e.type==="defaultBranchNode")return e.nextStepHint||"Default branch anchor";if(e.type==="submoduleNode"){const r=[e.machineLabel?`parent ${e.machineLabel}`:null];return e.outOfSync?r.push("out of sync"):e.dirty?r.push("local changes"):r.push("synced"),r.filter(Boolean).join(" · ")}const t=[];if(e.upstream&&t.push(e.upstream),e.upstream&&e.upstreamStatus!=="fresh")t.push("upstream unverified");else{const r=xh(e);r&&t.push(r)}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?(n=e.branchConvergence)!=null&&n.needsConvergence?"Needs follow-up":"Clean and even with upstream":t.join(" · ")}function yh(e,t=!1){const n=t?gr:Sn,r=ur(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(eN(e)/o),u=Fr(e.label,a,2),c=Fr(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,a,2),p=Fr(Xr(e),a+(t?1:4),t?2:3),d=ol(e),m=bh(e)?il(e):null,h=t?0:Fr(m,Math.max(24,Math.floor(r/8)),4),g=t?40+u*16+c*12+(d?22:0)+Math.max(0,i-1)*18+Math.max(18,p*16):52+u*18+c*14+(d?30:0)+i*24+Math.max(22,p*18)+(h>0?22+h*16:0),v=e.type==="submoduleNode"?n.minSubmoduleCardHeight:n.minWorktreeCardHeight;return Math.min(n.maxEstimatedCardHeight,Math.max(v,Math.ceil(g)))}function Fr(e,t,n){const r=(e||"").trim();return r?Math.max(1,Math.min(n,Math.ceil(r.length/t))):0}function eN(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 tN(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 sN(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.id.localeCompare(t.id)}function nN(e,t,n,r=!0){return{id:e.id,type:"meshNode",position:{x:t,y:n},graphNode:e,selected:!1,draggable:!1,selectable:r}}function rN(e,t,n){return{id:e.id,x:t,y:n,width:ur(e),height:yh(e)}}function aN(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 vh(e){const t=[...e.nodes].sort(tN),n=t.find(a=>a.type==="defaultBranchNode")??null,r=t.some(a=>a.id!==(n==null?void 0:n.id)&&a.type!=="submoduleNode");return!n||r?t:[...t,aN(n,e)]}function oN(e,t=XS,n=!1,r="LR"){const a=vh(e),o=new Set(a.map(c=>c.id)),i=a.map(c=>({id:c.id,width:ur(c,n),height:yh(c,n)})),u=e.edges.filter(c=>o.has(c.source)&&o.has(c.target)).sort(sN).map(c=>({id:c.id,sources:[c.source],targets:[c.target]}));return{id:`${e.meshId||"mesh"}__elk_root`,layoutOptions:{...t},children:i,edges:u}}function iN(e,t=!1){const n=[...new Set(e.map(a=>Math.round(a.x)))].sort((a,o)=>a-o),r=t?gr.layerGap:Sn.layerGap;return n.length<2?r:Math.min(...n.slice(1).map((a,o)=>a-n[o]))}async function wh(e,t=!1,n="LR",r){var v,f;const o=ll(t?gr:Sn,n),i=vh(e),u=new Map(i.map(y=>[y.id,y])),c=oN(e,o,t,n);if(r&&r.size>0)for(const y of c.children??[]){const j=r.get(y.id);j&&j>0&&(y.height=j)}const p=await ZS.layout(c),d=(p.children??[]).map(y=>{const j=u.get(y.id);return j?nN(j,Math.round(y.x??0),Math.round(y.y??Sn.placeholderTopOffset),!y.id.endsWith("__placeholder")):null}).filter(Boolean),m=new Map(i.map((y,j)=>[y.id,j]));d.sort((y,j)=>(m.get(y.id)??0)-(m.get(j.id)??0));const h=d.map(y=>rN(y.graphNode,y.position.x,y.position.y)),g=new Map;for(const y of p.edges??[]){const j=y.sections;if(!j||j.length===0)continue;const x=j[0],w=(v=y.sources)==null?void 0:v[0],N=(f=y.targets)==null?void 0:f[0];if(!w||!N)continue;const k=[];k.push({x:Math.round(x.startPoint.x),y:Math.round(x.startPoint.y)});for(const b of x.bendPoints??[])k.push({x:Math.round(b.x),y:Math.round(b.y)});k.push({x:Math.round(x.endPoint.x),y:Math.round(x.endPoint.y)}),g.set(y.id,{id:y.id,source:w,target:N,points:k})}return{nodes:d,bounds:h,edgeRoutes:g,columnGap:iN(h,t),layoutOptions:{...o}}}function lN(e){var t,n;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(r=>[r.sessionId,r.providerType??"",r.state??"",r.chatStatus??"",r.lifecycle??"",r.role??"",r.isSelfCoordinator?1:0,r.statusNote??"",r.startedAt??"",r.createdAt??""].join("/")).join(","),e.isOrphan?1:0,e.outOfSync?1:0,e.snapshotCompleteness,((t=e.branchConvergence)==null?void 0:t.status)??"",(n=e.branchConvergence)!=null&&n.needsConvergence?1:0,e.nextStepHint??"",e.error??"",e.parentNodeId??"",e.submodulePath??"",e.submoduleCommit??""].join("|")}function kh(e){return[e.id,e.source,e.target,e.type,e.label??"",e.direction].join("|")}function cN(e){return[e.meshId,e.refreshedAt,e.nodes.length,e.edges.length,...e.nodes.map(lN),...e.edges.map(kh)].join("::")}function dN(e){return[e.meshId,e.nodes.length,e.edges.length,...e.nodes.map(t=>{var n,r;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,((n=t.branchConvergence)==null?void 0:n.status)??"",(r=t.branchConvergence)!=null&&r.needsConvergence?1:0,t.nextStepHint??"",t.parentNodeId??"",t.submodulePath??"",t.submoduleCommit??""].join("|")}),...e.edges.map(kh)].join("::")}const uN=5*60*1e3;function jh(e){return typeof e.daemonId=="string"&&e.daemonId.trim()?e.daemonId.trim():null}function Sh(e){return typeof e.machineId=="string"&&e.machineId.trim()?e.machineId.trim():null}function pN(e){var t,n,r;return((t=e.connection)==null?void 0:t.state)==="self"||e.isLocalWorktree===!0?"local":((n=e.connection)==null?void 0:n.transport)==="direct"||((r=e.connection)==null?void 0:r.transport)==="relay"||jh(e)||Sh(e)?"remote":"unknown"}function hN(e){const t=e.connection;if(!t)return{connectionTransport:null,connectionState:null,connectionReason:null,connectionReported:!1,connectionRttMs:null};const n=t.rttMs,r=typeof n=="number"&&Number.isFinite(n)&&n>=0?n: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:r}}function Nh(e){const t=e.connectionTransport;if(t==="direct"||t==="relay"||t==="local")return t;const n=e.connectionState;return n==="connecting"?"connecting":n==="disconnected"?"disconnected":n==="failed"?"failed":n==="closed"?"closed":null}function mN(e){if(e.connectionTransport==="local"||e.connectionState==="self")return null;const t=Nh(e);return!t||t==="local"||typeof e.connectionRttMs!="number"||!Number.isFinite(e.connectionRttMs)?null:`${Math.round(e.connectionRttMs)}ms`}function fN(e){return Bi(e)}function Ch(e){var t;return fN(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function Mh(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function xN(e){return e.activeSessionDetails&&e.activeSessionDetails.length>0?e.activeSessionDetails:(e.activeSessions??[]).map(t=>({sessionId:t,workspace:e.workspace,isCached:!0}))}function Ah(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function Ih(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 bN(e){return cl(e)?"degraded":Ih(e)?"dirty":"online"}function gN(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 jo(e){return e.length===0?"unknown":e.reduce((t,n)=>Xc(n)>Xc(t)?n:t)}function yN(e){var o,i,u,c,p;const t=new Map,n=new Map;for(const d of e){const m=(i=(o=d.git)==null?void 0:o.branch)==null?void 0:i.trim();m&&(n.set(m,(n.get(m)??0)+1),(u=d.git)!=null&&u.upstream&&t.set(m,(t.get(m)??0)+1))}const r=[...t.entries()].sort((d,m)=>{if(m[1]!==d[1])return m[1]-d[1];const h=["main","master","develop","dev"],g=h.indexOf(d[0]),v=h.indexOf(m[0]);return g!==-1||v!==-1?g===-1?1:v===-1?-1:g-v:d[0].localeCompare(m[0])});return(c=r[0])!=null&&c[0]?r[0][0]:((p=[...n.entries()].sort((d,m)=>m[1]-d[1])[0])==null?void 0:p[0])??null}function vN(e,t){const n=[],r=e.git;return r?r.isGitRepo?(!r.branch&&r.headCommit&&n.push("Detached HEAD"),r.hasConflicts&&n.push("Merge conflicts need resolution"),r.branch&&t&&r.branch!==t&&!r.upstream&&n.push(`No upstream tracking for ${r.branch}`),r.upstream&&r.upstreamStatus&&r.upstreamStatus!=="fresh"&&n.push(`Upstream freshness unverified for ${r.branch??"workspace"}`),e.error&&n.push(e.error),n):(n.push("Not a git repository"),n):(n.push("No git status available"),n)}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 wN(e){return e.reduce((t,n)=>Qc(n.status)>Qc(t.status)?n:t)}function kN(e){const t=e.branchConvergenceSummary;if(Array.isArray(t==null?void 0:t.followUps))return t.followUps;const n=e.followUps;return Array.isArray(n)?n:(t==null?void 0:t.needsFollowUp)===!1||(t==null?void 0:t.unresolvedCount)===0?[]:null}function jN(e){var a,o,i;const t=e.sourceOfTruth,n=[],r=(a=t==null?void 0:t.fallback)==null?void 0:a.warning;return typeof r=="string"&&r.trim()&&n.push(r.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&&!n.some(u=>u.includes("direct mesh truth"))&&n.push("Direct mesh truth is not confirmed yet; this graph is drawn from setup inventory only."),n}function SN(e){const t=e.asyncRefineJobs;if(!Array.isArray(t))return[];const n=[];for(const r of t){if(!r||typeof r!="object")continue;const a=r,o=typeof a.jobId=="string"?a.jobId:null,i=a.status;o&&(i!=="accepted"&&i!=="running"&&i!=="completed"&&i!=="failed"||n.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 n}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 Mh(t)??0}function NN(e){return e.length===0?null:e.reduce((t,n)=>{const r=Zc(t.status),a=Zc(n.status);return a!==r?a<r?n:t:ed(n)>ed(t)?n:t})}function CN(e){var n,r;const t=new Map;for(const a of e){const o=((n=a.nodeId)==null?void 0:n.trim())||((r=a.targetNodeId)==null?void 0:r.trim());if(!o)continue;const i=t.get(o)??[];i.push(a),t.set(o,i)}return t}function MN(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 AN(e,t){var n,r;return{status:"merged_to_main",needsConvergence:!1,reason:"clean_default_branch_aggregate",nextStep:null,branch:e,defaultBranch:e,upstream:((n=t.find(a=>a.upstream))==null?void 0:n.upstream)??null,upstreamStatus:((r=t.find(a=>a.upstreamStatus))==null?void 0:r.upstreamStatus)??null,ahead:0,behind:0,dirty:!1,hasConflicts:!1}}function IN(e,t){if(Ch(e))return null;const n=e.branchConvergence;if(!n||typeof n!="object")return null;const r=n.status;if(!r||!["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"].includes(r))return null;const a=e.git,o=Ah(a)||Ih(a),i=!!(a!=null&&a.hasConflicts)||cl(a),u=(a==null?void 0:a.ahead)??0,c=(a==null?void 0:a.behind)??0,p=(a==null?void 0:a.branch)??null,d=(a==null?void 0:a.upstream)??null,m=(a==null?void 0:a.upstreamStatus)??null,h=n.defaultBranch??t??null;return{status:r,needsConvergence:n.needsConvergence??r!=="merged_to_main",reason:n.reason??"provided_by_coordinator",nextStep:n.nextStep??null,branch:n.branch??p,defaultBranch:h,upstream:n.upstream??d,upstreamStatus:n.upstreamStatus??m,ahead:n.ahead??u,behind:n.behind??c,dirty:n.dirty??o,hasConflicts:n.hasConflicts??i}}function TN(e,t){const n=IN(e,t);return n?{...n,defaultBranch:n.defaultBranch??t}:null}function PN(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function DN(e){var c,p,d;const{nodeStatus:t,expectedSubmodulePaths:n,refreshedAtMs:r}=e,a=[],o=t.machineLabel||t.nodeId,i=t.git;if(!i){if(Ch(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"||((c=t.connection)==null?void 0:c.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 u=new Set((i.submodules??[]).map(m=>m.path));if(n.size>0){const m=[...n].filter(h=>!u.has(h));m.length>0&&a.push(`${o} is missing submodule visibility for ${m.join(", ")} even though another peer reported it.`)}return((d=t.connection)==null?void 0:d.state)!=="self"&&r!==null&&typeof i.lastCheckedAt=="number"&&r-i.lastCheckedAt>uN&&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 Th(e){const t=Tu(e),r=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??yN(t.nodes),a=Mh(t.refreshedAt),o=new Set(t.nodes.flatMap(R=>{var _;return(((_=R.git)==null?void 0:_.submodules)??[]).map(K=>K.path)})),i=[],u=[],c=jN(t),p=new Map,d=CN(SN(t));for(const R of t.nodes){const _=R.git,K=(_==null?void 0:_.branch)??null,E=bN(_),D=Ah(_)||E==="dirty",$=vN(R,r),I=TN(R,r),G=DN({nodeStatus:R,expectedSubmodulePaths:o,refreshedAtMs:a}),Y=typeof R.clonedFromNodeId=="string"?R.clonedFromNodeId:null,Z=xN(R),q=NN(d.get(R.nodeId)??[]),ne=hN(R),ue={id:R.nodeId,type:$.length>0?"orphanNode":"worktreeNode",label:R.machineLabel||R.nodeId.slice(0,8),workspace:R.workspace,branch:K,upstream:(_==null?void 0:_.upstream)??null,upstreamStatus:(_==null?void 0:_.upstreamStatus)??null,daemonId:jh(R),machineId:Sh(R),machineLabel:R.machineLabel||null,locality:pN(R),connectionTransport:ne.connectionTransport,connectionState:ne.connectionState,connectionReason:ne.connectionReason,connectionReported:ne.connectionReported,connectionRttMs:ne.connectionRttMs,health:jo([R.health,E]),ahead:(_==null?void 0:_.ahead)??0,behind:(_==null?void 0:_.behind)??0,dirty:D,dirtyFiles:gN(_),hasConflicts:(_==null?void 0:_.hasConflicts)??!1,activeSessionCount:Z.length,activeSessions:Z.map(ae=>ae.sessionId),sessionDetails:Z,providers:R.providers??[],isOrphan:$.length>0,orphanReasons:$,error:R.error,nextStepHint:G.snapshotWarnings[0]??$[0]??(I==null?void 0:I.nextStep)??void 0,parentNodeId:null,clonedFromNodeId:Y,worktreeBranch:R.worktreeBranch??null,submodulePath:null,submoduleCommit:(_==null?void 0:_.headCommit)??null,outOfSync:cl(_),snapshotCompleteness:G.snapshotCompleteness,snapshotWarnings:G.snapshotWarnings,branchConvergence:I,refineJobStatus:(q==null?void 0:q.status)??null,refineJobId:(q==null?void 0:q.jobId)??null,refineJobBranch:(q==null?void 0:q.branch)??null,refineJobInto:(q==null?void 0:q.into)??null,source:R};if(i.push(ue),K){const ae=p.get(K)??[];ae.push(ue.id),p.set(K,ae)}for(const ae of(_==null?void 0:_.submodules)??[]){const O=`${ue.id}::submodule::${ae.path}`,se=ae.path.split("/").filter(Boolean).pop()||ae.path;i.push({id:O,type:"submoduleNode",label:se,workspace:ae.repoPath,branch:null,upstream:null,upstreamStatus:null,daemonId:ue.daemonId,machineId:ue.machineId,machineLabel:ue.machineLabel,locality:ue.locality,connectionTransport:ue.connectionTransport,connectionState:ue.connectionState,connectionReason:ue.connectionReason,connectionReported:ue.connectionReported,connectionRttMs:ue.connectionRttMs,health:PN(ae),ahead:0,behind:0,dirty:ae.dirty,dirtyFiles:ae.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],error:ae.error,nextStepHint:ae.error||(ae.outOfSync?`${ae.path} is out of sync with the parent checkout`:ae.dirty?`${ae.path} has local changes`:`${ae.path} is in sync with the parent checkout`),parentNodeId:ue.id,submodulePath:ae.path,submoduleCommit:ae.commit,outOfSync:ae.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:ue.id,parentWorkspace:R.workspace,submodule:ae}}),u.push({id:`${ue.id}--${O}`,source:ue.id,target:O,type:"submoduleLink",label:ae.outOfSync?"submodule out of sync":"submodule",direction:"directed"})}}const m=r?`__branch_${r}`:null;if(m&&r){const _=(p.get(r)??[]).map(Y=>i.find(Z=>Z.id===Y)).filter(Boolean),K=_.map(Y=>Y.branchConvergence).filter(Boolean),E=kN(t),D=_.length>0&&_.every(Y=>MN(Y,r)),$=(E==null?void 0:E.length)===0&&D?AN(r,_):K.length>0?wN(K):null,I=(E==null?void 0:E.length)===0&&D?0:K.filter(Y=>Y.needsConvergence).length,G={id:m,type:"defaultBranchNode",label:r,workspace:t.repoIdentity,branch:r,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:"default branch",locality:"unknown",connectionTransport:null,connectionState:null,connectionReason:null,connectionReported:!1,connectionRttMs:null,health:jo(_.map(Y=>Y.health)),ahead:0,behind:0,dirty:_.some(Y=>Y.dirty),dirtyFiles:_.reduce((Y,Z)=>Y+Z.dirtyFiles,0),hasConflicts:_.some(Y=>Y.hasConflicts),activeSessionCount:_.reduce((Y,Z)=>Y+Z.activeSessionCount,0),activeSessions:_.flatMap(Y=>Y.activeSessions),sessionDetails:_.flatMap(Y=>Y.sessionDetails),providers:[...new Set(_.flatMap(Y=>Y.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:I>0?`${I} workspace(s) on ${r} still need follow-up`:_.length>0?`${_.length} workspace(s) currently on ${r}`:"No workspaces currently checked out to the default branch",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:$,source:{nodeId:m,machineLabel:r,workspace:t.repoIdentity,health:jo(_.map(Y=>Y.health)),providers:[],activeSessions:[],activeSessionDetails:[]}};i.push(G);for(const Y of i)if(!(Y.id===m||Y.type==="submoduleNode")){if(Y.branch===r){u.push({id:`${m}--${Y.id}`,source:m,target:Y.id,type:"parentBranch",label:"checked out",direction:"undirected"});continue}if(Y.branch){u.push({id:`${m}--${Y.id}`,source:m,target:Y.id,type:Y.isOrphan?"orphanLink":"parentBranch",label:Y.branch,direction:"undirected"});continue}Y.isOrphan&&u.push({id:`${m}--${Y.id}`,source:m,target:Y.id,type:"orphanLink",label:"detached",direction:"undirected"})}}const h=new Set(i.map(R=>R.id)),g=new Set;for(const R of i){if(!R.clonedFromNodeId||R.type==="submoduleNode"||!h.has(R.clonedFromNodeId))continue;const _=`clone_${R.clonedFromNodeId}--${R.id}`;if(g.has(_))continue;g.add(_);const K=R.worktreeBranch??R.branch??void 0;u.push({id:_,source:R.clonedFromNodeId,target:R.id,type:"cloneLink",label:K?`cloned · ${K}`:"cloned",direction:"directed"})}const v=i.filter(R=>R.type!=="defaultBranchNode"),f=v.filter(R=>R.isOrphan).length,y=v.filter(R=>R.hasConflicts).length,j=v.filter(R=>R.health==="offline").length,x=v.filter(R=>R.type==="submoduleNode"&&R.outOfSync).length,w=v.filter(R=>{var _;return R.type!=="submoduleNode"&&((_=R.branchConvergence)==null?void 0:_.needsConvergence)}).length,N=v.filter(R=>{var _;return((_=R.branchConvergence)==null?void 0:_.status)==="blocked_review"}).length,k=v.filter(R=>{var _;return((_=R.branchConvergence)==null?void 0:_.status)==="pushed_feature_branch_needs_merge"}).length,b=v.filter(R=>{var _;return((_=R.branchConvergence)==null?void 0:_.status)==="cleanup_candidate"}).length,C=v.filter(R=>{var _;return((_=R.branchConvergence)==null?void 0:_.status)==="not_mergeable"}).length,S=v.filter(R=>R.snapshotWarnings.length>0).length,M=v.filter(R=>R.snapshotCompleteness==="pending_git").length,A=v.filter(R=>R.snapshotCompleteness==="missing_git").length,T=v.filter(R=>R.snapshotCompleteness==="missing_submodule_report").length,L=v.filter(R=>R.snapshotCompleteness==="stale").length,P=v.filter(R=>R.refineJobStatus==="running"||R.refineJobStatus==="accepted").length,B=v.filter(R=>R.refineJobStatus==="failed").length,z=[M>0?`${M} node(s) are still waiting for a live peer git snapshot`:null,A>0?`${A} node(s) have no visible peer git snapshot`:null,T>0?`${T} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,L>0?`${L} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return w>0&&c.push(`${w} workspace(s) still need follow-up before the mesh is converged`),f>0&&c.push(`${f} workspace(s) need attention before safe coordination`),N>0&&c.push(`${N} workspace(s) are blocked on branch convergence or upstream sync`),k>0&&c.push(`${k} clean feature branch workspace(s) still need merge follow-up`),b>0&&c.push(`${b} worktree workspace(s) are ready for refine / cleanup`),C>0&&c.push(`${C} workspace(s) have local changes or conflicts blocking convergence`),y>0&&c.push(`${y} workspace(s) report merge conflicts`),j>0&&c.push(`${j} node(s) are currently offline`),x>0&&c.push(`${x} submodule(s) are out of sync with their parent checkout`),c.push(...z),r||c.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:u,stats:{totalNodes:v.length,onlineNodes:v.filter(R=>R.health==="online").length,dirtyNodes:v.filter(R=>R.dirty).length,orphanNodes:f,errorNodes:v.filter(R=>!!R.error||R.outOfSync).length,offlineNodes:j,followUpNodes:w,blockedReviewNodes:N,mergeReadyNodes:k,cleanupCandidateNodes:b,notMergeableNodes:C,incompleteSnapshotNodes:S,pendingGitSnapshotNodes:M,missingGitSnapshotNodes:A,missingSubmoduleSnapshotNodes:T,staleGitSnapshotNodes:L,activeRefineNodes:P,failedRefineNodes:B,totalActiveSessions:v.reduce((R,_)=>R+_.activeSessionCount,0)},warnings:c,snapshotWarnings:z}}function LN(e){return!e.nodes.some(t=>t.snapshotCompleteness==="pending_git"||t.snapshotCompleteness==="missing_git"||t.snapshotCompleteness==="missing_submodule_report")}const RN=7,_N=640,dl=l.createContext(Rs("dark")),Ph=l.createContext(!1),Dh=l.createContext("LR"),Lh={overflowWrap:"anywhere",wordBreak:"break-word"},EN={...Lh,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:3,overflow:"hidden"},$N={...Lh,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:4,overflow:"hidden"};function Rh(e){return e.activeSessionCount>0}function FN(e){return e.health==="offline"||e.snapshotCompleteness==="stale"&&e.activeSessionCount===0}function td(e,t,n){const r=Rh(e),a=FN(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)]":r?o=n?"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=n?"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=n?"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} ${n?"bg-rose-500/12":"bg-rose-50/95"}`;if((i==null?void 0:i.tone)==="warn")return`${o} ${n?"bg-amber-500/10":"bg-amber-50/95"}`;if((i==null?void 0:i.tone)==="info")return`${o} ${n?"bg-violet-500/10":"bg-violet-50/95"}`;switch(e.health){case"online":return`${o} ${n?r?"bg-emerald-500/10":"bg-emerald-500/8":r?"bg-emerald-50":"bg-emerald-50/95"}`;case"dirty":return`${o} ${n?"bg-amber-500/8":"bg-amber-50/95"}`;case"degraded":return`${o} ${n?"bg-rose-500/10":"bg-rose-50/95"}`;case"wrong_branch":return`${o} ${n?"bg-violet-500/10":"bg-violet-50/95"}`;case"offline":return`${o} ${n?"bg-slate-500/10":"bg-slate-100/90"}`;default:return`${o} ${n?"bg-slate-950/78":"bg-white/96"}`}}function Lt(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 nd(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 BN(e){return e.replace(/_/g," ")}function ps(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const n=t.toLowerCase().replace(/[\s-]+/g,"_");return n.includes("approval")?"awaiting approval":n.includes("generating")||n.includes("running")||n.includes("busy")?"generating":n.includes("failed")||n.includes("stopped")||n.includes("interrupted")?n.replace(/_/g," "):n.includes("idle")||n.includes("ready")||n.includes("waiting_input")?"idle":n.replace(/_/g," ")}function HN(e){var t;return((t=e.sessionDetails)==null?void 0:t.some(n=>ps(n)==="generating"))??!1}function So(e,t){const n=ps(e);return n.includes("approval")?t?"border-amber-400/30 bg-amber-500/12 text-amber-100":"border-amber-300 bg-amber-50 text-amber-700":n==="generating"?t?"border-cyan-400/30 bg-cyan-500/12 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700":n==="idle"?t?"border-emerald-400/30 bg-emerald-500/12 text-emerald-100":"border-emerald-300 bg-emerald-50 text-emerald-700":n.includes("failed")||n.includes("stopped")||n.includes("interrupted")?t?"border-rose-400/30 bg-rose-500/12 text-rose-100":"border-rose-300 bg-rose-50 text-rose-700":Lt("health",t)}function ON(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function rd(e){const t=ON(e);if(t===null)return"runtime age not reported";const n=Math.max(0,Math.floor((Date.now()-t)/1e3));if(n<60)return`${n}s`;const r=Math.floor(n/60);if(r<60)return`${r}m`;const a=Math.floor(r/60);return a<48?`${a}h ${r%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 Wn(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function WN(e){if(e.sessionDetails.length===0)return null;const t=e.sessionDetails.filter(o=>ps(o)==="generating").length,n=e.sessionDetails.filter(o=>o.isSelfCoordinator).length,r=e.sessionDetails.length-n,a=[`${e.sessionDetails.length} chat${e.sessionDetails.length===1?"":"s"}`];return t>0&&a.push(`${t} generating`),n>0&&a.push(n===1?"coordinator attached":`${n} coordinators`),r>0&&a.push(`${r} worker${r===1?"":"s"}`),t===0&&n>0&&a.push("sampled status"),a.join(" · ")}function ad(e){return e==="local"?"local":e==="remote"?"remote":"machine unknown"}function UN(e){return e.locality==="remote"?"meta":"health"}function KN({data:e,selected:t}){const{t:n}=Xe("common"),r=l.useContext(dl),a=l.useContext(Ph),o=l.useContext(Dh),i=e.graphNode,u=i.type==="defaultBranchNode",c=i.type==="submoduleNode",p=bh(i),d=u?"default branch anchor":c?i.submodulePath||"submodule checkout":[i.machineLabel,ad(i.locality)].filter(Boolean).join(" · ")||i.workspace,m=i.submoduleCommit?i.submoduleCommit.slice(0,7):null,h=!c&&!u&&i.connectionState!=="self",g=h?Nh(i):null,v=g==="local"?null:g,f=h?mN(i):null,y=ol(i),j=il(i),x=Rh(i),w=i.sessionDetails,N=i.sessionDetails,k=WN(i),b=i.sessionDetails.map(S=>{const M=ps(S),A=S.providerType||"provider unknown",T=Wn(S),L=S.startedAt||S.createdAt||null,P=S.statusNote?` · ${S.statusNote}`:"";return`Session: ${S.sessionId} · ${A} · ${M} · ${T} · ${rd(L)}${P}`});if(a)return s.jsxs("div",{className:`rounded-xl border px-3 py-2.5 backdrop-blur-sm transition-all ${td(i,t,r.isDark)}`,style:{width:ur(i,!0)},title:[i.label,i.branch?`Branch: ${i.branch}`:null,i.machineLabel?`Machine: ${i.machineLabel}`:null,i.workspace?`Workspace: ${i.workspace}`:null,y?`Status: ${y.label}`:null,Xr(i),...b].filter(Boolean).join(`
77
- `),children:[s.jsx(vr,{type:"target",position:o==="TB"?Ss.Top:Ss.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:i.label}),!u&&s.jsx("div",{className:`truncate text-[10px] leading-3.5 ${r.textMuted}`,children:d})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[x&&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:nd(i.health)},"aria-hidden":!0})]})]}),i.health==="unknown"&&!y&&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 ${Lt("health",r.isDark)}`,children:s.jsx("span",{className:"truncate",children:n("meshGraph.obs.connecting")})}),y&&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(y.tone,r.isDark)}`,title:y.label,children:s.jsx("span",{className:"truncate",children:y.label})}),!y&&i.branch&&!c&&i.health!=="unknown"&&s.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[10px] ${Lt("meta",r.isDark)} rounded-full border px-2 py-0.5 inline-block`,title:i.branch,children:i.branch}),k&&s.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[9px] ${r.isDark?"text-cyan-100/85":"text-sky-700"}`,title:b.join(`
78
- `),children:k}),N.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:N.map(S=>s.jsxs("div",{className:`min-w-0 rounded-md border px-1.5 py-1 ${r.isDark?"border-cyan-400/15 bg-cyan-500/[0.055]":"border-sky-200 bg-white/80"}`,title:[`Session ID: ${S.sessionId}`,S.providerType?`Provider: ${S.providerType}`:null,`Status: ${ps(S)}`,`Role: ${Wn(S)}`].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:S.providerType||n("meshGraph.panel.providerUnknown")}),s.jsx("span",{className:`shrink-0 rounded-full border px-1 py-0 text-[8px] font-semibold uppercase tracking-[0.1em] ${So(S,r.isDark)}`,children:ps(S)})]}),s.jsxs("div",{className:`mt-0.5 flex min-w-0 items-center gap-1.5 text-[8px] ${r.textMuted}`,children:[s.jsx("span",{className:"min-w-0 truncate font-mono",children:No(S.sessionId)}),s.jsx("span",{className:"shrink-0",children:Wn(S)})]})]},S.sessionId))}),s.jsx(vr,{type:"source",position:o==="TB"?Ss.Bottom:Ss.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]});const C=[i.label,d,y?`Status: ${y.label}`:null,Xr(i),i.branch?`Branch: ${i.branch}`:null,i.dirty?c?"Local changes":`${i.dirtyFiles} dirty`:null,i.hasConflicts?"Has conflicts":null,i.outOfSync?"Out of sync":null,!c&&i.upstream&&i.upstreamStatus!=="fresh"?"Upstream unverified":null,i.isOrphan?"Needs follow-up":null,p&&j?`Note: ${j}`:null,...b].filter(Boolean).join(`
80
- `);return s.jsxs("div",{className:`rounded-2xl border px-4 py-3 backdrop-blur-sm transition-all ${td(i,t,r.isDark)}${HN(i)?" mesh-node-generating":""}`,style:{width:ur(i)},title:C,children:[s.jsx(vr,{type:"target",position:o==="TB"?Ss.Top:Ss.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:i.label}),s.jsx("div",{className:`truncate text-[11px] ${r.textMuted}`,children:d})]}),s.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 shrink-0",children:[x&&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:nd(i.health)},"aria-hidden":!0})]})]}),y?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(y.tone,r.isDark)}`,title:y.label,children:s.jsx("span",{className:"truncate",children:y.label})}):i.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] ${Lt("meta",r.isDark)}`,title:i.branch,children:s.jsx("span",{className:"truncate",children:i.branch})}):null,k&&s.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[10px] font-medium ${r.isDark?"border-cyan-400/20 bg-cyan-500/8 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700"}`,title:b.join(`
81
- `),children:s.jsx("span",{className:"truncate",children:k})}),N.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:N.map(S=>{const M=Wn(S);return s.jsxs("div",{className:`min-w-0 rounded-lg border px-2.5 py-1.5 ${r.isDark?"border-cyan-400/15 bg-cyan-500/[0.055]":"border-sky-200 bg-white/85"}`,title:[`Session ID: ${S.sessionId}`,S.providerType?`Provider: ${S.providerType}`:null,`Status: ${ps(S)}`,`Role: ${M}`].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:S.providerType||"provider unknown"}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${So(S,r.isDark)}`,children:ps(S)})]}),s.jsxs("div",{className:`mt-0.5 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${r.textMuted}`,children:[s.jsx("span",{className:"min-w-0 truncate font-mono",children:No(S.sessionId)}),s.jsx("span",{children:M})]})]},S.sessionId)})}),s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"flex min-w-0 flex-wrap gap-1.5 text-[10px]",children:[i.health==="unknown"?s.jsx("span",{className:`rounded-full border px-2 py-0.5 italic ${Lt("health",r.isDark)}`,children:n("meshGraph.obs.connecting")}):s.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${Lt("health",r.isDark)}`,children:BN(i.health)}),c&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("submodule",r.isDark)}`,children:n("meshGraph.panel.submoduleBadge")}),!u&&i.health==="unknown"&&!i.locality&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 italic ${Lt("health",r.isDark)}`,children:"..."}),!u&&(i.health!=="unknown"||i.locality)&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt(UN(i),r.isDark)}`,children:ad(i.locality)}),v&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("meta",r.isDark)}`,title:v==="relay"?"P2P link relayed through TURN (slower path)":`P2P transport: ${v}`,children:v}),f&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("meta",r.isDark)}`,title:"P2P round-trip latency",children:f}),m&&c&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("meta",r.isDark)}`,children:m}),i.dirty&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("dirty",r.isDark)}`,children:c?"local changes":`${i.dirtyFiles} dirty`}),i.outOfSync&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("conflict",r.isDark)}`,children:n("meshGraph.panel.outOfSyncBadge")}),i.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("conflict",r.isDark)}`,children:n("meshGraph.panel.conflictBadge")}),!c&&i.upstream&&i.upstreamStatus!=="fresh"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("orphan",r.isDark)}`,children:n("meshGraph.panel.upstreamUnverified")}),i.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("orphan",r.isDark)}`,children:n("meshGraph.panel.needsFollowUp")}),!c&&i.refineJobStatus==="completed"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("refineDone",r.isDark)}`,title:i.refineJobBranch?`refined ${i.refineJobBranch}${i.refineJobInto?` → ${i.refineJobInto}`:""}`:"refine completed",children:n("meshGraph.panel.refined")})]}),s.jsx("div",{className:`mt-3 text-[11px] leading-5 ${r.textSecondary}`,style:EN,children:Xr(i)}),w.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:n("meshGraph.panel.attachedChats")}),s.jsx("div",{className:"flex max-h-56 flex-col gap-1.5 overflow-y-auto pr-1",children:w.map(S=>{const M=S.startedAt||S.createdAt||null,A=Wn(S);return s.jsxs("div",{className:`min-w-0 rounded-lg border px-2.5 py-1.5 ${r.isDark?"border-white/8 bg-white/[0.035]":"border-slate-200 bg-white/80"}`,title:[`Session ID: ${S.sessionId}`,S.providerType?`Provider: ${S.providerType}`:null,`Status: ${ps(S)}`,`Role: ${A}`,M?`Started: ${M}`:"Started: not reported",S.statusNote?`Note: ${S.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(S.sessionId)}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${So(S,r.isDark)}`,children:ps(S)})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${r.textMuted}`,children:[s.jsx("span",{className:"truncate",children:S.providerType||n("meshGraph.panel.providerUnknown")}),s.jsx("span",{children:A}),s.jsx("span",{children:rd(M)})]}),S.statusNote&&s.jsx("div",{className:`mt-1 text-[9px] leading-4 ${r.textMuted}`,children:S.statusNote})]},S.sessionId)})})]}),p&&j&&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:$N,children:j})]}),s.jsx(vr,{type:"source",position:o==="TB"?Ss.Bottom:Ss.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const GN={meshNode:KN},zN=8;function VN(e){if(e.length<2)return null;if(e.length===2){const[p,d]=e;return{d:`M ${p.x},${p.y} L ${d.x},${d.y}`,labelX:(p.x+d.x)/2,labelY:(p.y+d.y)/2}}const t=zN,n=[`M ${e[0].x},${e[0].y}`];for(let p=1;p<e.length-1;p+=1){const d=e[p-1],m=e[p],h=e[p+1],g=Math.sign(m.x-d.x),v=Math.sign(m.y-d.y),f=Math.sign(h.x-m.x),y=Math.sign(h.y-m.y),j=Math.hypot(m.x-d.x,m.y-d.y),x=Math.hypot(h.x-m.x,h.y-m.y),w=Math.min(t,j/2,x/2);if(w<1||g===f&&v===y){n.push(`L ${m.x},${m.y}`);continue}const N=m.x-g*w,k=m.y-v*w,b=m.x+f*w,C=m.y+y*w;n.push(`L ${N},${k}`),n.push(`Q ${m.x},${m.y} ${b},${C}`)}const r=e[e.length-1];n.push(`L ${r.x},${r.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 u=e[0].x,c=e[0].y;for(let p=1;p<e.length;p+=1)if(o[p]>=i){const d=o[p]-o[p-1],m=d===0?0:(i-o[p-1])/d;u=e[p-1].x+(e[p].x-e[p-1].x)*m,c=e[p-1].y+(e[p].y-e[p-1].y)*m;break}return{d:n.join(" "),labelX:u,labelY:c}}function qN(e){const t=e.data.routePoints;if(t&&t.length>=2){const o=VN(t);if(o)return[o.d,o.labelX,o.labelY]}const n={sourceX:e.sourceX,sourceY:e.sourceY,sourcePosition:e.sourcePosition,targetX:e.targetX,targetY:e.targetY,targetPosition:e.targetPosition},r=e.data.graphEdge;let a;return r.type==="parentBranch"?a=Bm(n):r.type==="worktreeLink"||r.type==="submoduleLink"||r.type==="cloneLink"?a=$m(n):a=Fm(n),[a[0],a[1],a[2]]}function YN(e,t){const n="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?`${n} border-orange-400/35 bg-orange-500/14 text-orange-100`:`${n} border-orange-300 bg-orange-50 text-orange-700`;case"submoduleLink":return t?`${n} border-violet-400/30 bg-violet-500/14 text-violet-100`:`${n} border-violet-300 bg-violet-50 text-violet-700`;case"sessionLink":return t?`${n} border-emerald-400/30 bg-emerald-500/14 text-emerald-100`:`${n} border-emerald-300 bg-emerald-50 text-emerald-700`;case"cloneLink":return t?`${n} border-teal-400/30 bg-teal-500/14 text-teal-100`:`${n} border-teal-300 bg-teal-50 text-teal-700`;default:return t?`${n} border-sky-400/25 bg-slate-950/78 text-sky-100`:`${n} border-sky-300 bg-white/95 text-sky-700`}}function JN(e){const t=l.useContext(dl),n=e.data.graphEdge,[r,a,o]=qN(e),i=typeof e.label=="string"?e.label:void 0;return s.jsxs(s.Fragment,{children:[s.jsx(Dm,{id:e.id,path:r,markerEnd:e.markerEnd,style:e.style,interactionWidth:24}),e.label&&s.jsx(Lm,{children:s.jsx("div",{className:YN(n,t.isDark),title:i,style:{position:"absolute",transform:`translate(-50%, -50%) translate(${a}px, ${o}px)`,pointerEvents:"none",maxWidth:YS.maxWidth},children:s.jsx("span",{className:"block truncate",children:e.label})})})]})}const XN={meshEdge:JN};async function QN(e,t,n,r,a){const o=await wh(e,n,r,a);return _h(e,o,t,n)}async function ZN(e,t=Rs("dark"),n=!1,r="LR"){const a=await wh(e,n,r);return _h(e,a,t,n)}function _h(e,t,n,r=!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:r},selected:p.selected,draggable:p.draggable,selectable:p.selectable})),i=e.edges.filter(p=>a.has(p.source)&&a.has(p.target)),u=s1(i),c=i.map(p=>{var d;return{id:p.id,source:p.source,target:p.target,label:u.has(p.id)?p.label:void 0,type:"meshEdge",data:{graphEdge:p,routePoints:(d=t.edgeRoutes.get(p.id))==null?void 0:d.points},animated:p.type==="orphanLink",markerEnd:p.direction==="directed"?{type:Em.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:n.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:n.edgeLabelBackgroundColor,fillOpacity:1,stroke:n.edgeLabelBorderColor},labelBgPadding:[6,4],labelBgBorderRadius:7}});return{nodes:o,edges:c}}const e1=3,t1=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 s1(e){const t=new Set,n=new Map;for(const r of e){if(!r.label)continue;const a=n.get(r.source);a?a.push(r):n.set(r.source,[r])}for(const r of n.values()){if(r.length<e1){for(const o of r)t.add(o.id);continue}const a=[...r].sort((o,i)=>{const u=od(i)-od(o);return u!==0?u:o.id.localeCompare(i.id)});for(const o of a.slice(0,t1))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 n1(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 r1(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 a1({data:e,viewportKey:t}){const n=Rm(),r=_m(),a=l.useRef(null),o=l.useMemo(()=>gh(e),[e]),i=l.useMemo(()=>US(e),[e]);return l.useEffect(()=>{if(!n||e.nodes.length===0||a.current===t)return;let u=!1;const c=requestAnimationFrame(()=>{if(u)return;const p=i.length>0&&i.length<e.nodes.length;r.fitView({nodes:p?i.map(d=>({id:d})):void 0,padding:p?.24:.2,maxZoom:p?.98:.9,duration:260}),a.current=t});return()=>{u=!0,cancelAnimationFrame(c)}},[e.nodes.length,i,o,n,r,t]),null}const o1=12;function i1(e){return e>=16?"min-h-[720px]":e>=10?"min-h-[580px]":"min-h-[460px]"}function l1({data:e,selectedNodeId:t=null,directionPref:n,onNodeClick:r,onEdgeClick:a,onNodeHoverChange:o,onEdgeHoverChange:i}){const{theme:u}=Ls(),c=l.useMemo(()=>Rs(u),[u]),p=l.useMemo(()=>cN(e),[e]),d=l.useMemo(()=>dN(e),[e]),m=l.useRef(null),[h,g]=l.useState({width:0,height:0}),v=h.width>0&&h.width<_N,f=e.nodes.length>=RN||v,[y]=l.useState("LR"),j=n??y,x=l.useMemo(()=>n==="LR"||n==="TB"?n:v?"TB":j==="auto"?QS(e):j,[j,n,p,e,v]),w=e.nodes.length>=o1,[N,k]=l.useState({nodes:[],edges:[]}),b=l.useMemo(()=>`${KS(e,h.width,h.height)}::${x}`,[p,e,h.height,h.width,x]);l.useEffect(()=>{let S=!1;return ZN(e,c,f,x).then(M=>{if(S)return;k(M);const A=requestAnimationFrame(()=>{if(S)return;const T=m.current;if(!T)return;const L=new Map;for(const P of M.nodes){const B=T.querySelector(`.react-flow__node[data-id="${CSS.escape(P.id)}"]`);B&&B.offsetHeight>0&&L.set(P.id,B.offsetHeight)}L.size!==0&&QN(e,c,f,x,L).then(P=>{S||k(P)})});return()=>cancelAnimationFrame(A)}),()=>{S=!0}},[e,d,c,f,x]);const C=l.useMemo(()=>N.nodes.map(S=>({...S,selected:S.id===t})),[N.nodes,t]);return l.useEffect(()=>{const S=m.current;if(!S)return;const M=()=>{const T=Math.max(0,Math.round(S.clientWidth)),L=Math.max(0,Math.round(S.clientHeight));g(P=>P.width===T&&P.height===L?P:{width:T,height:L})};M();const A=typeof ResizeObserver=="function"?new ResizeObserver(()=>M()):null;return A==null||A.observe(S),window.addEventListener("resize",M),()=>{A==null||A.disconnect(),window.removeEventListener("resize",M)}},[]),s.jsx(dl.Provider,{value:c,children:s.jsx(Ph.Provider,{value:f,children:s.jsx(Dh.Provider,{value:x,children:s.jsxs("div",{ref:m,className:`${c.graphShellClass} ${i1(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] ${c.graphStatChipClass}`,children:"drag or scroll to pan"}),s.jsx("div",{className:"w-full min-w-0 flex-1",style:{height:"100%"},children:s.jsxs(Mm,{nodes:C,edges:N.edges,nodeTypes:GN,edgeTypes:XN,minZoom:v?.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,M)=>r==null?void 0:r(M.data.graphNode),onEdgeClick:(S,M)=>{var T;const A=(T=M.data)==null?void 0:T.graphEdge;A&&(a==null||a(A))},onNodeMouseEnter:(S,M)=>o==null?void 0:o(M.data.graphNode),onNodeMouseLeave:()=>o==null?void 0:o(null),onEdgeMouseEnter:(S,M)=>{var A;return i==null?void 0:i(((A=M.data)==null?void 0:A.graphEdge)??null)},onEdgeMouseLeave:()=>i==null?void 0:i(null),className:"h-full w-full",colorMode:c.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(a1,{data:e,viewportKey:b}),s.jsx(Am,{className:c.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),w&&s.jsx(Im,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:n1,nodeClassName:r1,nodeStrokeWidth:3,className:c.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(Tm,{variant:Pm.Dots,gap:18,size:1.2,color:c.graphBackgroundDotColor})]})})]})})})})}const c1="You are one independent member of a multi-agent cross-verification quorum";function d1(e){var r,a;const t=(e??"").trim();if(!t)return"";if(!t.startsWith(c1))return t;const n=(a=(r=t.match(/\n## Question\n([\s\S]*?)(?:\n## |$)/))==null?void 0:r[1])==null?void 0:a.trim().replace(/\s+/g," ");return n?`MAGI cross-verify — ${n}`:"MAGI cross-verification task"}function u1(e){return`${e.state??""} ${e.chatStatus??""} ${e.lifecycle??""}`.toLowerCase()}function p1(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=n.activeSessionDetails;if(Array.isArray(r))for(const a of r)a!=null&&a.sessionId&&u1(a).includes("approval")&&t.push({nodeId:n.nodeId,sessionId:a.sessionId,providerType:a.providerType,machineLabel:n.machineLabel||n.nodeId,detail:a.statusNote??a.title??null})}return t}function h1({approvals:e,nodes:t,onResolve:n,hideWhenEmpty:r=!0}){const{t:a}=Xe(),o=l.useMemo(()=>e??p1(t),[e,t]),[i,u]=l.useState({});if(r&&o.length===0)return null;const c=(p,d)=>{i[p.sessionId]||(u(m=>({...m,[p.sessionId]:d})),Promise.resolve(n(p.nodeId,p.sessionId,d)).finally(()=>{u(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 d=i[p.sessionId]??null,m=d!==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:()=>c(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:d==="approve"?"⏳ ...":a("meshGraph.approvals.approve")}),s.jsx("button",{onClick:()=>c(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:d==="reject"?"⏳ ...":a("meshGraph.approvals.reject")})]})]},`${p.nodeId}:${p.sessionId}`)})})]})}const m1=5,f1=40,x1={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};function _a(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function Eh(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const n=t.toLowerCase().replace(/[\s-]+/g,"_");return n.includes("approval")?"awaiting approval":n.includes("generating")||n.includes("running")||n.includes("busy")?"generating":n.includes("idle")||n.includes("ready")||n.includes("waiting_input")?"idle":n.replace(/_/g," ")}function $h(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 b1(e){const t=e.git;if(!t)return e.gitProbePending?"git probe pending":"no git probe";const n=(t.staged??0)+(t.modified??0)+(t.untracked??0)+(t.deleted??0)+(t.renamed??0),r=[];return t.upstreamStatus==="fresh"&&((t.ahead??0)>0||(t.behind??0)>0)&&r.push(`↑${t.ahead??0}/↓${t.behind??0}`),n>0&&r.push(`✎${n}`),t.hasConflicts&&r.push("conflicts"),r.join(" · ")||"clean"}function Fh(e){switch(e){case"active":return"emerald";case"paused":return"amber";case"completed":return"sky";case"abandoned":return"rose";default:return"muted"}}function g1(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 Bh(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 ds(e){if(!e)return null;const t=Date.parse(e);if(!Number.isFinite(t))return null;const n=Math.max(0,Math.floor((Date.now()-t)/1e3));if(n<60)return`${n}s ago`;const r=Math.floor(n/60);if(r<60)return`${r}m ago`;const a=Math.floor(r/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),n=t%60,r=Math.floor(t/60),a=r%60,o=Math.floor(r/60),i=[];return o>0&&i.push(`${o}h`),a>0&&i.push(`${a}m`),(n>0||i.length===0)&&i.push(`${n}s`),i.join(" ")}function ul(e){return e.replace(/[_-]+/g," ")}function Hh(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 Oh(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 y1({status:e,daemonId:t=null,meshId:n=null,sendDaemonCommand:r=null}){var N,k,b,C;const{theme:a}=Ls(),o=l.useMemo(()=>Rs(a),[a]),i=((N=e.queue)==null?void 0:N.summary)??null,u=((k=e.queue)==null?void 0:k.tasks)??[],c=((b=e.ledger)==null?void 0:b.summary)??x1,p=((C=e.ledger)==null?void 0:C.entries)??[],d=e.missions??[],m=d.filter(S=>S.status==="active"||S.status==="paused"),h=d.filter(S=>S.status==="completed"||S.status==="abandoned"),g=e.asyncRefineJobs??[],[v,f]=l.useState(null),y=l.useCallback(()=>f(null),[]),j=l.useCallback(async(S,M,A)=>{!t||!r||await r(t,"mesh_approve",{meshId:n??void 0,node_id:S,session_id:M,action:A})},[t,n,r]),x=l.useCallback(S=>{if(!S)return"";const M=e.nodes.find(A=>A.nodeId===S);return(M==null?void 0:M.machineLabel)||S},[e.nodes]),w=l.useMemo(()=>{const S=[];for(const M of e.nodes){const A=M.activeSessionDetails&&M.activeSessionDetails.length>0?M.activeSessionDetails:(M.activeSessions??[]).map(T=>({sessionId:T,workspace:M.workspace,isCached:!0}));for(const T of A)S.push({node:M,session:T})}return S},[e.nodes]);return s.jsxs("div",{className:"flex flex-col gap-3 pb-2",children:[s.jsx(h1,{nodes:e.nodes,onResolve:j}),s.jsx(A1,{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(I1,{meshTheme:o,ledgerSummary:c,entries:p,resolveNodeLabel:x,onSelect:S=>f({kind:"ledger",entry:S})}),s.jsx(T1,{meshTheme:o,queueSummary:i,tasks:u,onSelect:S=>f({kind:"queue",task:S})})]}),s.jsx(D1,{meshTheme:o,nodes:e.nodes}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(L1,{meshTheme:o,entries:w,onSelect:(S,M)=>f({kind:"session",node:S,session:M})}),s.jsx(R1,{meshTheme:o,jobs:g})]}),v&&s.jsx(w1,{meshTheme:o,detail:v,onClose:y,daemonId:t,meshId:n??e.meshId??null,sendDaemonCommand:r,resolveNodeLabel:x})]})}function Xs({meshTheme:e,title:t,count:n,children:r,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}),n!==void 0&&s.jsx("span",{className:`tabular-nums text-[11px] ${e.textMuted}`,children:n}),a&&s.jsx("span",{className:"ml-auto",children:a})]}),r]})}function Gt({meshTheme:e,label:t,tone:n}){const r=e.isDark,a=n==="rose"?r?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700":n==="sky"?r?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700":n==="amber"?r?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700":n==="emerald"?r?"border-emerald-400/25 bg-emerald-500/10 text-emerald-200":"border-emerald-300 bg-emerald-50 text-emerald-700":r?"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 jt({meshTheme:e,label:t,value:n,tone:r}){const a=e.isDark,o=r==="rose"?a?"text-rose-300":"text-rose-600":r==="sky"?a?"text-sky-300":"text-sky-600":r==="amber"?a?"text-amber-300":"text-amber-600":r==="emerald"?a?"text-emerald-300":"text-emerald-600":r==="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:n}),s.jsx("span",{className:`mt-1 text-[9px] uppercase tracking-wide ${e.textMuted}`,children:t})]})}function yr({meshTheme:e,children:t}){return s.jsx("div",{className:`text-xs ${e.textMuted}`,children:t})}function Ea({meshTheme:e,onClick:t,children:n}){const r=e.isDark,a=t?r?"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:n})}function $a({meshTheme:e,expanded:t,hiddenCount:n,onToggle:r}){return n<=0?null:s.jsx("button",{type:"button",onClick:r,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":`+${n} more`})}function Fa(e,t=m1){const[n,r]=l.useState(!1),a=n?e:e.slice(0,t),o=Math.max(0,e.length-t),i=l.useCallback(()=>r(u=>!u),[]);return{visible:a,hiddenCount:o,expanded:n,toggle:i}}function bt({meshTheme:e,label:t,value:n}){return s.jsxs("div",{className:e.rowClass,children:[s.jsx("span",{className:e.rowLabelClass,children:t}),s.jsx("span",{className:e.rowValueClass,children:n})]})}function v1(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:_a(e.session.sessionId)}}}function w1({meshTheme:e,detail:t,onClose:n,daemonId:r,meshId:a,sendDaemonCommand:o,resolveNodeLabel:i}){l.useEffect(()=>{const h=g=>{g.key==="Escape"&&n()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[n]);const u=e.isDark,{kicker:c,title:p}=v1(t),d=u?"bg-[#030617]/[0.92]":"bg-[rgba(15,23,42,0.82)]",m=u?"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 ${d}`,role:"dialog","aria-modal":"true",onClick:n,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 ${u?"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:c}),s.jsx("div",{className:`mt-0.5 break-all text-sm font-semibold ${e.textPrimary}`,children:p})]}),s.jsx("button",{type:"button",onClick:n,"aria-label":"Close detail",className:u?"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(S1,{meshTheme:e,mission:t.mission,daemonId:r,meshId:a,sendDaemonCommand:o}),t.kind==="ledger"&&s.jsx(N1,{meshTheme:e,entry:t.entry,resolveNodeLabel:i}),t.kind==="queue"&&s.jsx(C1,{meshTheme:e,task:t.task}),t.kind==="session"&&s.jsx(M1,{meshTheme:e,node:t.node,session:t.session})]})]})})}const k1=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function j1(e){const t=k1(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function S1({meshTheme:e,mission:t,daemonId:n,meshId:r,sendDaemonCommand:a}){var N;const o=t.tasks,i="goal"in t&&typeof t.goal=="string"&&t.goal?t.goal:"goalPreview"in t?t.goalPreview:"",u="goalTruncated"in t?t.goalTruncated===!0:!1,[c,p]=l.useState(null),[d,m]=l.useState(!1),[h,g]=l.useState(null),v=u&&!c&&!!n&&!!a,f=l.useCallback(async()=>{if(!(!n||!a)){m(!0),g(null);try{const k=await a(n,"mesh_status",{meshId:r??void 0,verbose:!0}),b=j1(k),S=(Array.isArray(b==null?void 0:b.missions)?b.missions:[]).find(A=>(A==null?void 0:A.id)===t.id),M=typeof(S==null?void 0:S.goal)=="string"&&S.goal?S.goal:null;M?p(M):g("Full goal unavailable")}catch(k){g(k instanceof Error?k.message:"Failed to fetch full mission goal")}finally{m(!1)}}},[n,r,a,t.id]),y=c??i,j=u&&!c,x=t.stats??null,w=((N=x==null?void 0:x.incompleteTaskIds)==null?void 0:N.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(Gt,{meshTheme:e,label:t.status,tone:Fh(t.status)}),s.jsx(Gt,{meshTheme:e,label:`${o.total} tasks`,tone:"muted"})]}),y&&s.jsxs("div",{className:`max-h-64 overflow-y-auto whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:[y,j&&!v&&s.jsx("span",{className:e.textMuted,children:" … (truncated)"})]}),h&&s.jsx("div",{className:"text-[11px] text-amber-400",children:h}),v&&s.jsx("button",{type:"button",className:"self-start text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:f,disabled:d,children:d?"Loading…":"Show full goal"}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5 sm:grid-cols-6",children:[s.jsx(jt,{meshTheme:e,label:"Completed",value:o.completed,tone:"emerald"}),s.jsx(jt,{meshTheme:e,label:"Assigned",value:o.assigned,tone:o.assigned>0?"sky":void 0}),s.jsx(jt,{meshTheme:e,label:"Pending",value:o.pending}),s.jsx(jt,{meshTheme:e,label:"Failed",value:o.failed,tone:o.failed>0?"rose":void 0}),s.jsx(jt,{meshTheme:e,label:"Blocked",value:o.blocked,tone:o.blocked>0?"amber":void 0}),s.jsx(jt,{meshTheme:e,label:"Cancelled",value:o.cancelled,tone:"muted"})]}),x&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(jt,{meshTheme:e,label:"Wall clock",value:cd(x.wallClockMs)??"—"}),s.jsx(jt,{meshTheme:e,label:"Total runtime",value:cd(x.totalDurationMs)??"—"}),s.jsx(jt,{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(bt,{meshTheme:e,label:"Mission id",value:t.id}),s.jsx(bt,{meshTheme:e,label:"Created",value:ds(t.createdAt)??t.createdAt}),s.jsx(bt,{meshTheme:e,label:"Updated",value:ds(t.updatedAt)??t.updatedAt}),o.lastActivityAt&&s.jsx(bt,{meshTheme:e,label:"Last task activity",value:ds(o.lastActivityAt)??o.lastActivityAt}),w>0&&x&&s.jsx(bt,{meshTheme:e,label:"Incomplete evidence",value:s.jsxs("details",{children:[s.jsxs("summary",{className:"cursor-pointer select-none",children:[w," task",w===1?"":"s"]}),s.jsx("div",{className:"mt-1 flex flex-col gap-0.5 break-all",children:x.incompleteTaskIds.map(k=>s.jsx("span",{className:`font-mono text-[10px] ${e.textMuted}`,children:k},k))})]})})]})]})}function N1({meshTheme:e,entry:t,resolveNodeLabel:n}){const r=Oh(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(Gt,{meshTheme:e,label:ul(t.kind),tone:Hh(t.kind)})}),r&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:r}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(bt,{meshTheme:e,label:"Entry id",value:t.id}),s.jsx(bt,{meshTheme:e,label:"When",value:ds(t.timestamp)??t.timestamp}),t.nodeId&&s.jsx(bt,{meshTheme:e,label:"Node",value:n(t.nodeId)}),t.sessionId&&s.jsx(bt,{meshTheme:e,label:"Session",value:_a(t.sessionId)}),t.providerType&&s.jsx(bt,{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 C1({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(Gt,{meshTheme:e,label:t.status,tone:Bh(t.status)}),(t.requeueCount??0)>0&&s.jsx(Gt,{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(bt,{meshTheme:e,label:"Task id",value:t.id}),s.jsx(bt,{meshTheme:e,label:"Created",value:ds(t.createdAt)??t.createdAt}),s.jsx(bt,{meshTheme:e,label:"Updated",value:ds(t.updatedAt)??t.updatedAt}),(t.assignedNodeId||t.targetNodeId)&&s.jsx(bt,{meshTheme:e,label:"Node",value:t.assignedNodeId||t.targetNodeId}),(t.assignedSessionId||t.targetSessionId)&&s.jsx(bt,{meshTheme:e,label:"Session",value:_a(t.assignedSessionId||t.targetSessionId)}),t.cancelReason&&s.jsx(bt,{meshTheme:e,label:"Cancel reason",value:t.cancelReason}),t.requeueReason&&s.jsx(bt,{meshTheme:e,label:"Requeue reason",value:t.requeueReason}),t.autoLaunch&&s.jsx(bt,{meshTheme:e,label:"Auto launch",value:`${t.autoLaunch.status}${t.autoLaunch.reason?` · ${t.autoLaunch.reason}`:""}`})]})]})}function M1({meshTheme:e,node:t,session:n}){var a,o;const r=Eh(n);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(Gt,{meshTheme:e,label:r,tone:$h(r)}),s.jsx(Gt,{meshTheme:e,label:n.providerType||"provider unknown",tone:"muted"})]}),n.statusNote&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:n.statusNote}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(bt,{meshTheme:e,label:"Session id",value:n.sessionId}),s.jsx(bt,{meshTheme:e,label:"Node",value:t.machineLabel}),s.jsx(bt,{meshTheme:e,label:"Workspace",value:n.workspace||t.workspace}),(((a=t.git)==null?void 0:a.branch)??t.worktreeBranch)&&s.jsx(bt,{meshTheme:e,label:"Branch",value:((o=t.git)==null?void 0:o.branch)??t.worktreeBranch}),typeof n.role=="string"&&n.role&&s.jsx(bt,{meshTheme:e,label:"Role",value:n.role}),(n.startedAt||n.createdAt)&&s.jsx(bt,{meshTheme:e,label:"Started",value:ds(n.startedAt||n.createdAt)??(n.startedAt||n.createdAt)})]})]})}function dd({meshTheme:e,mission:t,onSelect:n}){const r=t.tasks,a=ds(r.lastActivityAt);return s.jsxs(Ea,{meshTheme:e,onClick:n,children:[s.jsx(Gt,{meshTheme:e,label:t.status,tone:Fh(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:["✓",r.completed,"/",r.total]}),a&&s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:a})]})}function A1({meshTheme:e,liveMissions:t,historyMissions:n,hasMissionField:r,onSelect:a}){const[o,i]=l.useState(!1),u=e.isDark,c=Fa(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:[c.visible.map(p=>s.jsx(dd,{meshTheme:e,mission:p,onSelect:()=>a(p)},p.id)),s.jsx($a,{meshTheme:e,expanded:c.expanded,hiddenCount:c.hiddenCount,onToggle:c.toggle})]}):s.jsx(yr,{meshTheme:e,children:r?"No active missions. The coordinator creates a mission for multi-task work.":"Mission data unavailable from this daemon — update the daemon to see missions."}),n.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${u?"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:n.length})]}),o&&s.jsx("div",{className:"mt-2 flex flex-col gap-0.5",children:n.map(p=>s.jsx(dd,{meshTheme:e,mission:p,onSelect:()=>a(p)},p.id))})]})]})}function I1({meshTheme:e,ledgerSummary:t,entries:n,resolveNodeLabel:r,onSelect:a}){const o=ds(t.lastActivityAt),i=l.useMemo(()=>[...n].reverse(),[n]),u=Fa(i);return s.jsxs(Xs,{meshTheme:e,title:"Ledger",children:[s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(jt,{meshTheme:e,label:"Dispatched",value:t.taskDispatched}),s.jsx(jt,{meshTheme:e,label:"Completed",value:t.taskCompleted,tone:"emerald"}),s.jsx(jt,{meshTheme:e,label:"Failed",value:t.taskFailed,tone:t.taskFailed>0?"rose":void 0}),s.jsx(jt,{meshTheme:e,label:"Stalled",value:t.taskStalled,tone:t.taskStalled>0?"amber":void 0}),s.jsx(jt,{meshTheme:e,label:"Sessions",value:t.sessionLaunched}),s.jsx(jt,{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:[u.visible.map(c=>{const p=Oh(c.payload);return s.jsxs(Ea,{meshTheme:e,onClick:()=>a(c),children:[s.jsx(Gt,{meshTheme:e,label:ul(c.kind),tone:Hh(c.kind)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:c.nodeId||void 0,children:p||r(c.nodeId)||c.sessionId||"—"}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:ds(c.timestamp)??""})]},c.id)}),s.jsx($a,{meshTheme:e,expanded:u.expanded,hiddenCount:u.hiddenCount,onToggle:u.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 T1({meshTheme:e,queueSummary:t,tasks:n,onSelect:r}){const a=l.useMemo(()=>[...n].sort((i,u)=>{const c=ld(i.status)-ld(u.status);return c!==0?c:(u.updatedAt||"").localeCompare(i.updatedAt||"")}).slice(0,f1),[n]),o=Fa(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(jt,{meshTheme:e,label:"Pending",value:t.pending}),s.jsx(jt,{meshTheme:e,label:"Assigned",value:t.assigned,tone:t.assigned>0?"sky":void 0}),s.jsx(jt,{meshTheme:e,label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(jt,{meshTheme:e,label:"Completed",value:t.completed,tone:"emerald"}),s.jsx(jt,{meshTheme:e,label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0}),s.jsx(jt,{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(Ea,{meshTheme:e,onClick:()=>r(i),children:[s.jsx(Gt,{meshTheme:e,label:i.status,tone:Bh(i.status)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:i.message||void 0,children:d1(i.message)||i.id}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:ds(i.updatedAt)??""})]},i.id)),s.jsx($a,{meshTheme:e,expanded:o.expanded,hiddenCount:o.hiddenCount,onToggle:o.toggle})]})]})]}):s.jsx(Xs,{meshTheme:e,title:"Queue",children:s.jsx(yr,{meshTheme:e,children:"No queue activity."})})}function P1(e){return e.autoFastForwardEligible||e.suggestedAction==="auto_fast_forward"?{label:"fast-forward",tone:"sky"}:e.launchBlockedReason?{label:"blocked",tone:"rose"}:null}function D1({meshTheme:e,nodes:t}){const n=e.isDark;return s.jsx(Xs,{meshTheme:e,title:"Nodes",count:t.length,children:t.length===0?s.jsx(yr,{meshTheme:e,children:"No nodes in this mesh yet."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:t.map(r=>{var u,c,p;const a=(((u=r.activeSessionDetails)==null?void 0:u.length)??0)||(((c=r.activeSessions)==null?void 0:c.length)??0),o=P1(r),i=((p=r.git)==null?void 0:p.branch)??r.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 ${n?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsx(Gt,{meshTheme:e,label:r.health,tone:g1(r.health)}),s.jsx("span",{className:`min-w-0 max-w-full flex-1 truncate text-sm font-medium ${e.textPrimary}`,title:r.workspace,children:r.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:b1(r)}),a>0&&s.jsxs("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:[a," session",a>1?"s":""]}),typeof r.daemonBuildVersion=="string"&&r.daemonBuildVersion&&s.jsxs("span",{className:`shrink-0 font-mono text-[10px] ${e.textMuted}`,title:"Daemon build version reported by this node",children:["v",r.daemonBuildVersion]}),o&&s.jsx(Gt,{meshTheme:e,label:o.label,tone:o.tone})]},r.nodeId)})})})}function L1({meshTheme:e,entries:t,onSelect:n}){const r=Fa(t);return s.jsx(Xs,{meshTheme:e,title:"Active sessions",count:t.length||void 0,children:t.length===0?s.jsx(yr,{meshTheme:e,children:"No active sessions."}):s.jsxs("div",{className:"flex flex-col gap-0.5",children:[r.visible.map(({node:a,session:o})=>{const i=Eh(o);return s.jsxs(Ea,{meshTheme:e,onClick:()=>n(a,o),children:[s.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${e.textMuted}`,children:_a(o.sessionId)}),s.jsx("span",{className:`shrink-0 ${e.textMuted}`,children:o.providerType||"?"}),s.jsx(Gt,{meshTheme:e,label:i,tone:$h(i)})]},o.sessionId)}),s.jsx($a,{meshTheme:e,expanded:r.expanded,hiddenCount:r.hiddenCount,onToggle:r.toggle})]})})}function R1({meshTheme:e,jobs:t}){const n=e.isDark,r=t.filter(a=>a.status==="failed").length;return s.jsx(Xs,{meshTheme:e,title:"Refine jobs",count:t.length||void 0,action:r>0?s.jsx(Gt,{meshTheme:e,label:`${r} failed`,tone:"rose"}):void 0,children:t.length===0?s.jsx(yr,{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"?n?"text-rose-300":"text-rose-600":a.status==="running"||a.status==="accepted"?n?"text-sky-300":"text-sky-600":n?"text-emerald-300":"text-emerald-600"}`,children:a.status})]},a.jobId))})})}const _1=["node","p2p","session","task","mission","refinery","completion","magi","magiPanel","convergence"];function E1({meshTheme:e,open:t,onToggle:n}){const{t:r}=Xe(),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:n,"aria-label":r("meshGraph.help.toggleAria"),"aria-expanded":t,title:r("meshGraph.help.toggleTitle"),className:`${o} ${i}`,children:s.jsx(Df,{size:15})})}function $1({meshTheme:e,onClose:t}){const{t:n}=Xe(),r=e.isDark,a=l.useMemo(()=>_1.map(o=>({term:n(`meshGraph.help.sections.${o}.term`),summary:n(`meshGraph.help.sections.${o}.summary`),details:n(`meshGraph.help.sections.${o}.details`,{returnObjects:!0})})),[n]);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 ${r?"border-white/10 bg-white/[0.03]":"border-slate-200 bg-white/80"}`,role:"region","aria-label":n("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:n("meshGraph.help.kicker")}),s.jsx("div",{className:`mt-0.5 text-sm font-semibold ${e.textPrimary}`,children:n("meshGraph.help.title")})]}),s.jsx("button",{type:"button",onClick:t,"aria-label":n("meshGraph.help.close"),className:r?"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-white/10 bg-white/[0.04] text-slate-300 transition hover:bg-white/[0.08] hover:text-white":"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",children:s.jsx(Mt,{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 ${r?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsx("dt",{className:`text-xs font-semibold ${e.textPrimary}`,children: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,u)=>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})]},u))})]},o.term))})]})}const tn=l.createContext(Rs("dark"));function Ve({label:e,tone:t="default",className:n,title:r}){const a=l.useContext(tn);return s.jsx("span",{title:r,className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${a.badge(t)}${n?` ${n}`:""}`,children:e})}function Dt({label:e,value:t}){const n=l.useContext(tn);return s.jsxs("div",{className:n.rowClass,children:[s.jsx("span",{className:n.rowLabelClass,children:e}),s.jsx("span",{className:n.rowValueClass,children:t})]})}const F1={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};function Wh(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 Qr(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const n=t.toLowerCase().replace(/[\s-]+/g,"_");return n.includes("approval")?"awaiting approval":n.includes("generating")||n.includes("running")||n.includes("busy")?"generating":n.includes("idle")||n.includes("ready")||n.includes("waiting_input")?"idle":n.replace(/_/g," ")}function B1(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function H1(e){return e.startedAt||e.createdAt||null}function O1(e){const t=H1(e);if(!t)return"runtime age not reported";const n=Date.parse(t);if(!Number.isFinite(n))return"runtime age not reported";const r=Math.max(0,Math.floor((Date.now()-n)/1e3));if(r<60)return`${r}s`;const a=Math.floor(r/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 Uh(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function W1(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 U1(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 K1(e){const t=e.git;if(!t)return e.gitProbePending?"Git probe pending":"No git probe";const n=(t.staged??0)+(t.modified??0)+(t.untracked??0)+(t.deleted??0)+(t.renamed??0),r=[];t.branch&&r.push(t.branch),t.upstream&&t.upstreamStatus!=="fresh"&&r.push("upstream unverified"),t.upstreamStatus==="fresh"&&((t.ahead??0)>0||(t.behind??0)>0)&&r.push(`↑${t.ahead??0}/↓${t.behind??0}`),n>0&&r.push(`${n} dirty`);const a=(t.submodules??[]).filter(i=>i.dirty),o=(t.submodules??[]).filter(i=>i.outOfSync||i.error);return a.length>0&&r.push(`${a.length} submodule dirty`),o.length>0&&r.push(`${o.length} submodule drift`),t.hasConflicts&&r.push("conflicts"),r.join(" · ")||"Clean"}const G1={first_eligible:"In order",least_loaded:"Spread",round_robin:"Spread (round-robin)",priority_only:"Spread (priority)"};function z1(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 V1(e){var n;const t=[];for(const r of e.nodes){const a=r.activeSessionDetails&&r.activeSessionDetails.length>0?r.activeSessionDetails:(r.activeSessions??[]).map(o=>({sessionId:o,workspace:r.workspace,isCached:!0}));for(const o of a)t.push({nodeId:r.nodeId,machineLabel:r.machineLabel,workspace:r.workspace,branch:((n=r.git)==null?void 0:n.branch)??null,nodeHealth:r.health,session:o})}return t}function q1(e){return e.assignedNodeId||e.targetNodeId||null}function fi(e){return e?e.slice(0,7):null}function Y1(e,t){var o,i,u;const n=fi((o=e==null?void 0:e.git)==null?void 0:o.headCommit),r=((u=(i=e==null?void 0:e.git)==null?void 0:i.headMessage)==null?void 0:u.trim())||"";if(n||r)return[n,r].filter(Boolean).join(" · ");const a=t[0];return a?[fi(a.commit),a.message].filter(Boolean).join(" · "):null}function J1(e,t){const n=Y1(e,t);return n||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function X1(e){const t=(e==null?void 0:e.result)??e,n=(t==null?void 0:t.log)??(e==null?void 0:e.log)??t;return Array.isArray(n==null?void 0:n.entries)?n.entries:[]}function Q1(e){var n,r,a,o,i,u;const t=((n=e.selectedSessionEntry)==null?void 0:n.session.workspace)||((r=e.selectedSessionEntry)==null?void 0:r.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 c=((u=e.selectedNodeStatus)==null?void 0:u.daemonId)||e.coordinatorDaemonId;return c?{daemonId:c,workspace:t}:null}if(t&&e.selectedNodeStatus){const c=e.selectedNodeStatus.daemonId||e.coordinatorDaemonId;return c?{daemonId:c,workspace:t}:null}return null}function Z1(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":U1(e.connection)}function eC(e){var n;const t=e.source;return t!=null&&t.kind?t.kind:((n=t==null?void 0:t.connection)==null?void 0:n.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 tC(e){return e.direction==="directed"?"directed":"undirected"}function sC(e,t){return t?e.nodes.find(n=>n.id===t)??null:null}function nC(e){var t,n,r,a;return[e.meshId,e.refreshedAt,e.nodes.length,((n=(t=e.queue)==null?void 0:t.summary)==null?void 0:n.active)??"",((a=(r=e.ledger)==null?void 0:r.summary)==null?void 0:a.recentFailures)??"",...e.nodes.map(o=>{var i,u,c,p,d,m,h,g,v,f,y,j,x,w,N,k,b,C,S,M,A,T;return[o.nodeId,o.daemonId??"",o.machineId??"",o.machineLabel,o.machineStatus??"",((i=o.connection)==null?void 0:i.state)??"",((u=o.connection)==null?void 0:u.transport)??"",((c=o.connection)==null?void 0:c.source)??"",o.health,o.gitProbePending?1:0,((p=o.git)==null?void 0:p.branch)??"",((d=o.git)==null?void 0:d.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)??"",((v=o.git)==null?void 0:v.headCommit)??"",((f=o.git)==null?void 0:f.staged)??"",((y=o.git)==null?void 0:y.modified)??"",((j=o.git)==null?void 0:j.untracked)??"",((x=o.git)==null?void 0:x.deleted)??"",((w=o.git)==null?void 0:w.renamed)??"",(N=o.git)!=null&&N.hasConflicts?1:0,((k=o.git)==null?void 0:k.lastCheckedAt)??"",((b=o.activeSessions)==null?void 0:b.join(","))??"",((C=o.activeSessionDetails)==null?void 0:C.length)??"",((S=o.activeSessionDetails)==null?void 0:S.map(L=>[L.sessionId,L.providerType??"",L.state??"",L.chatStatus??"",L.lifecycle??"",L.role??"",L.isSelfCoordinator?1:0,L.statusNote??"",L.startedAt??"",L.createdAt??""].join("/")).join(","))??"",((M=o.providers)==null?void 0:M.join(","))??"",((A=o.providerPriority)==null?void 0:A.join(","))??"",o.error??"",(((T=o.git)==null?void 0:T.submodules)??[]).map(L=>[L.path,L.commit,L.dirty?1:0,L.outOfSync?1:0,L.error??""].join("/")).join(",")].join("|")})].join("::")}function rC(e){return e.nodes.length===0?!1:e.nodes.every(t=>t.health==="unknown"&&(!t.connection||t.connection.state==="unknown"))}function aC({scheduling:e}){const t=l.useContext(tn);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 n=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(Ve,{label:G1[e.strategy]??e.strategy,tone:"info"}),s.jsx(Ve,{label:`write ${e.activeWriteAssigned}/${e.maxParallelTasks}`,tone:n,title:"Active write (non-readonly) assigned tasks vs the global parallel cap"}),s.jsx(Ve,{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 oC({scheduling:e}){return e?s.jsxs(s.Fragment,{children:[s.jsx(Ve,{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(Ve,{label:`priority ${e.schedulingPriority}`,tone:"default",title:"Soft scheduling priority (higher = preferred)"}),(e.providerRoles??[]).map(t=>s.jsx(Ve,{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(Ve,{label:z1(t),tone:"warn",title:"Why this node cannot currently claim a new write task"},t))]}):null}function iC({node:e}){var d,m,h,g;const t=l.useContext(tn),n=((d=e.activeSessionDetails)==null?void 0:d.length)??((m=e.activeSessions)==null?void 0:m.length)??0,r=fi((h=e.git)==null?void 0:h.headCommit),a=e.isLocalWorktree===!0,o=e.worktreeBootstrap,i=e.staleDaemonBuild,u=e.providerVersions&&typeof e.providerVersions=="object"?e.providerVersions:void 0,c=u?Object.entries(u).filter(([,v])=>typeof v=="string"&&v):[],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(Ve,{label:e.health,tone:Wh(e.health)}),a&&s.jsx(Ve,{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(Ve,{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(Ve,{label:e.connection.state,tone:e.connection.state==="connected"?"good":"warn",title:"Mesh peer connection state"}),n>0&&s.jsx(Ve,{label:`${n} session${n===1?"":"s"}`,tone:"default"}),e.autoFastForwardEligible&&s.jsx(Ve,{label:"fast-forward ready",tone:"info",title:"Clean, behind upstream — safe for fast-forward"}),!!i&&s.jsx(Ve,{label:"stale build",tone:"warn",title:"Live daemon was built behind workspace HEAD — merged fixes may not be live"}),p&&s.jsx(Ve,{label:`build ${p}`,tone:"default",title:"Daemon build version reported by this node"}),s.jsx(oC,{scheduling:e.scheduling})]}),c.length>0&&s.jsx("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:c.map(([v,f])=>s.jsx(Ve,{label:`${v}@${f}`,tone:"info",title:"Detected provider version on this node"},v))}),s.jsxs("div",{className:`mt-1.5 text-[11px] ${t.textSecondary}`,children:[K1(e),r?s.jsxs("span",{className:"ml-2 font-mono opacity-70",children:["@",r]}):null]})]})}function lC({status:e}){const t=l.useContext(tn),n=e.meshProtocolMetrics,r=Array.isArray(e.providerVersionSkew)?e.providerVersionSkew:[];return!n&&r.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"}),n&&s.jsx(Ve,{label:`v2 ${Math.round(n.v2Ratio*100)}% (${n.v2}/${n.total})`,tone:n.total>0&&n.v2===n.total?"good":"info",title:"Share of pending coordinator events carrying a mesh-protocol-v2 envelope in this drain"}),r.length>0&&s.jsx(Ve,{label:`${r.length} provider skew`,tone:"warn",title:"Providers running different versions across nodes"})]}),n&&Object.keys(n.scopes).length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:Object.entries(n.scopes).map(([a,o])=>s.jsx(Ve,{label:`${a}: ${o}`,tone:"default",title:"v2 event scope breakdown"},a))}),r.length>0&&s.jsx("div",{className:"mt-2 flex flex-col gap-1.5",children:r.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(Ve,{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 cC({canonicalStatus:e}){const t=l.useContext(tn);return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsx(aC,{scheduling:e.scheduling}),s.jsx(lC,{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(n=>s.jsx(iC,{node:n},n.nodeId))]})]})}function dC({canonicalStatus:e,queueSummary:t,ledgerSummary:n,isBootstrapMode:r,meshTheme:a,sessionEntries:o,inlineMode:i=!1}){var k;const u=t&&(t.active>0||t.historical>0),c=n.recentFailures>0||n.taskFailed>0,p=(k=e.queue)!=null&&k.tasks?e.queue.tasks.filter(b=>b.status==="failed"||b.status==="cancelled").slice(0,5):[],d=e.asyncRefineJobs,m=(d==null?void 0:d.filter(b=>b.status==="running"||b.status==="accepted"))??[],h=(d==null?void 0:d.filter(b=>b.status==="failed"))??[],g=e.staleDirectWorkSummary,v=g&&g.count>0;if(!u&&!c&&e.nodes.length===0&&!r&&m.length===0&&h.length===0&&!v&&o.length===0)return null;const f=a.isDark,y=`border-t ${f?"border-white/8":"border-slate-200"}`,j=`group w-full rounded-lg border text-xs ${f?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,x=`flex cursor-pointer list-none items-center gap-1.5 px-2.5 py-1.5 [&::-webkit-details-marker]:hidden ${a.textSecondary}`;function w({label:b,value:C,tone:S}){const M=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 ${M}`,children:C}),s.jsx("span",{className:`mt-0.5 text-[9px] uppercase tracking-wide ${a.textMuted}`,children:b})]})}const N=s.jsxs("div",{className:"flex flex-col gap-3 text-xs",children:[s.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t?s.jsxs(s.Fragment,{children:[s.jsx(w,{label:"Pending",value:t.pending}),s.jsx(w,{label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(w,{label:"Done",value:t.completed,tone:"emerald"}),s.jsx(w,{label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0})]}):s.jsxs(s.Fragment,{children:[s.jsx(w,{label:"Done",value:n.taskCompleted,tone:"emerald"}),s.jsx(w,{label:"Failed",value:n.taskFailed,tone:n.taskFailed>0?"rose":void 0}),s.jsx(w,{label:"Sessions",value:n.sessionLaunched}),s.jsx(w,{label:"Recent↯",value:n.recentFailures,tone:n.recentFailures>0?"amber":"muted"})]})}),t&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(w,{label:"Ledger done",value:n.taskCompleted,tone:"emerald"}),s.jsx(w,{label:"Sessions",value:n.sessionLaunched}),s.jsx(w,{label:"Recent↯",value:n.recentFailures,tone:n.recentFailures>0?"amber":"muted"})]}),n.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:n.lastActivityAt.slice(5,16)})]}),e.nodes.length>0&&s.jsx("div",{className:`pt-2.5 ${y}`,children:s.jsx("div",{className:"flex flex-col gap-1",children:e.nodes.map(b=>{var L;const C=((L=b.connection)==null?void 0:L.state)??"unknown",S=C==="unknown"||C==="connecting",T=S?"bg-amber-400":C==="failed"||C==="closed"||C==="disconnected"?f?"bg-rose-400":"bg-rose-500":C==="connected"||C==="self"?f?"bg-emerald-400":"bg-emerald-500":f?"bg-slate-500":"bg-slate-400";return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`size-1.5 shrink-0 rounded-full ${T}`}),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?"…":C})]},b.nodeId)})})}),d&&d.length>0&&s.jsx("div",{className:`pt-2.5 ${y}`,children:s.jsxs("details",{className:j,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:d.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:d.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:d&&d.length>0?"":`pt-2.5 ${y}`,children:s.jsxs("details",{className:j,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))})]})}),v&&s.jsxs("div",{className:`flex items-center justify-between pt-2.5 ${y}`,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 ${y}`,children:s.jsxs("details",{className:j,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:Uh(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:Qr(b.session)})]},b.session.sessionId))})]})})]});return i?N:s.jsxs("details",{className:`rounded-2xl border text-xs ${a.isDark?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsxs("summary",{className:`flex cursor-pointer list-none items-center gap-2 px-4 py-3 font-medium [&::-webkit-details-marker]:hidden ${a.textSecondary}`,children:[s.jsx("span",{className:"flex-1",children:"Mesh Health Panel"}),m.length>0&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700"}`,children:[m.length," refining"]}),h.length>0&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[h.length," refine failed"]}),c&&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:[n.recentFailures," recent failures"]}),r&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-amber-400/20 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:"awaiting live data"})]}),N]})}function Kh({meshTheme:e,activeTab:t,onActiveTabChange:n,helpOpen:r,onHelpOpenChange:a}){const{t:o}=Xe("common"),i=u=>u?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:i(t==="overview"),onClick:()=>n("overview"),children:o("meshGraph.obs.tabOverview")}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="status",className:i(t==="status"),onClick:()=>n("status"),children:o("meshGraph.obs.tabStatus")}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="graph",className:i(t==="graph"),onClick:()=>n("graph"),children:o("meshGraph.obs.tabGraph")})]}),s.jsx(E1,{meshTheme:e,open:r,onToggle:()=>a(!r)})]})}function uC({status:e,emptyMessage:t,daemonId:n=null,sendDaemonCommand:r=null,bootstrapFallback:a,activeTab:o,onActiveTabChange:i,helpOpen:u,onHelpOpenChange:c,hideControls:p=!1}){var Qe,dt,it;const{t:d}=Xe("common"),{theme:m}=Ls(),h=l.useMemo(()=>Rs(m),[m]),g=l.useMemo(()=>({merged_to_main:d("meshGraph.obs.convergenceMergedToMain"),pushed_feature_branch_needs_merge:d("meshGraph.obs.convergenceNeedsMerge"),blocked_review:d("meshGraph.obs.convergenceBlockedReview"),cleanup_candidate:d("meshGraph.obs.convergenceCleanup"),not_mergeable:d("meshGraph.obs.convergenceNotMergeable")}),[d]),v=t??d("meshGraph.obs.emptyGraph"),f=l.useMemo(()=>Tu(e),[e]),y=a??rC(f),j=l.useMemo(()=>nC(f),[f]),x=l.useMemo(()=>Th(f),[j]),[w,N]=l.useState("overview"),[k,b]=l.useState(!1),C=o??w,S=u??k,M=l.useCallback(he=>{i?i(he):N(he)},[i]),A=l.useCallback(he=>{c?c(he):b(he)},[c]),[T,L]=l.useState(!1);l.useEffect(()=>{C==="graph"&&L(!0)},[C]);const[P,B]=l.useState(null),[z,R]=l.useState(null),[_,K]=l.useState(null),[E,D]=l.useState({}),[$,I]=l.useState(null),[G,Y]=l.useState(null),Z=l.useMemo(()=>new Map(f.nodes.map(he=>[he.nodeId,he])),[f.nodes]),q=l.useMemo(()=>new Map(x.nodes.map(he=>[he.id,he])),[x.nodes]),ne=((Qe=f.queue)==null?void 0:Qe.summary)??null,ue=((dt=f.ledger)==null?void 0:dt.summary)??F1,ae=l.useMemo(()=>V1(f),[f]),O=l.useMemo(()=>{const he=new Map;for(const Ee of ae){const Fe=Qr(Ee.session);he.set(Fe,(he.get(Fe)??0)+1)}return[...he.entries()].sort((Ee,Fe)=>Fe[1]-Ee[1])},[ae]);l.useEffect(()=>{P&&(q.has(P)||(B(null),K(he=>!he||"nodeId"in he&&he.nodeId===P?null:he)))},[q,P]);const se=P?Z.get(P)??null:null,X=sC(x,P),oe=(_==null?void 0:_.kind)==="edge"&&z?x.edges.find(he=>he.id===z)??null:null,Se=oe?x.nodes.find(he=>he.id===oe.source)??null:null,ye=oe?x.nodes.find(he=>he.id===oe.target)??null:null;l.useEffect(()=>{var he,Ee,Fe;if(P)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:f.meshId,selectedNodeId:P,canonicalNode:Oy(se),graphNode:X?{id:X.id,branch:X.branch,upstream:X.upstream,headCommit:X.submoduleCommit,submoduleCount:((Ee=(he=se==null?void 0:se.git)==null?void 0:he.submodules)==null?void 0:Ee.length)??0,snapshotCompleteness:X.snapshotCompleteness,snapshotWarnings:X.snapshotWarnings,branchConvergence:((Fe=X.branchConvergence)==null?void 0:Fe.status)??null}:null})}catch{}},[f.meshId,X,P,se]);const ke=(_==null?void 0:_.kind)==="session"?ae.find(he=>he.nodeId===_.nodeId&&he.session.sessionId===_.sessionId)??null:null,me=l.useMemo(()=>ae.filter(he=>he.nodeId===P),[P,ae]),U=Q1({coordinatorDaemonId:n,selectedNodeStatus:se,selectedSessionEntry:ke}),W=(U==null?void 0:U.workspace)??null,Q=W?E[W]??null:null,V=J1(se,(Q==null?void 0:Q.entries)??[]),fe=(X==null?void 0:X.daemonId)??(se==null?void 0:se.daemonId)??n??null,ce=!!(X&&r&&fe&&X.type!=="submoduleNode"&&X.behind>0&&X.ahead===0&&X.dirtyFiles===0&&!X.dirty&&!X.hasConflicts&&X.upstreamStatus==="fresh"),F=l.useCallback(()=>{B(null),R(null),K(null),I(null)},[]);l.useEffect(()=>{I(null)},[P]);const le=l.useCallback(async()=>{if(!X||!fe||!r||!ce)return;Y(X.id),I(null);const he=(se==null?void 0:se.workspace)??X.workspace??"";try{const Ee=await r(fe,"fast_forward_mesh_node",{meshId:f.meshId,nodeId:X.id,workspace:he,updateSubmodules:!0,dryRun:!0,execute:!1}),Fe=(Ee==null?void 0:Ee.result)??Ee;if(I({phase:"dry_run",code:typeof(Fe==null?void 0:Fe.code)=="string"?Fe.code:void 0,error:typeof(Fe==null?void 0:Fe.operationError)=="string"?Fe.operationError:null,executed:(Fe==null?void 0:Fe.executed)===!0}),!(Fe!=null&&Fe.success)||Fe.code!=="fast_forward_available"||!window.confirm(`Apply fast-forward for ${X.label}?`))return;const ve=await r(fe,"fast_forward_mesh_node",{meshId:f.meshId,nodeId:X.id,workspace:he,updateSubmodules:!0,dryRun:!1,execute:!0}),Oe=(ve==null?void 0:ve.result)??ve;I({phase:"execute",code:typeof(Oe==null?void 0:Oe.code)=="string"?Oe.code:void 0,error:typeof(Oe==null?void 0:Oe.operationError)=="string"?Oe.operationError:null,executed:(Oe==null?void 0:Oe.executed)===!0})}catch(Ee){I({phase:"dry_run",error:Ee instanceof Error?Ee.message:"fast-forward failed"})}finally{Y(null)}},[ce,f.meshId,X,fe,r]);l.useEffect(()=>{if(!X&&!oe)return;const he=Ee=>{Ee.key==="Escape"&&F()};return window.addEventListener("keydown",he),()=>window.removeEventListener("keydown",he)},[F,oe,X]),l.useEffect(()=>{if(!U||!r)return;const{daemonId:he,workspace:Ee}=U,Fe=E[Ee];if(Fe!=null&&Fe.loading||Fe&&(Fe.entries.length>0||Fe.error))return;let Ie=!1;return D(ve=>{var Oe;return{...ve,[Ee]:{loading:!0,error:null,entries:((Oe=ve[Ee])==null?void 0:Oe.entries)??[]}}}),r(he,"git_log",{workspace:Ee,limit:5}).then(ve=>{Ie||D(Oe=>({...Oe,[Ee]:{loading:!1,error:null,entries:X1(ve)}}))}).catch(ve=>{Ie||D(Oe=>({...Oe,[Ee]:{loading:!1,error:ve instanceof Error?ve.message:"git_log failed",entries:[]}}))}),()=>{Ie=!0}},[E,U,r]);const je=[...x.warnings??[],...f.nodes.filter(he=>he.machineStatus&&he.machineStatus!=="online").map(he=>`${he.machineLabel}: ${he.machineStatus}`)],de=x.stats.incompleteSnapshotNodes>0,H=x.stats.followUpNodes>0?`${x.stats.followUpNodes} need follow-up`:de?"mesh visibility incomplete":"mesh converged",be=x.stats.followUpNodes>0?"danger":de?"warn":"good",[Ne,Ce]=l.useState("LR"),$e=he=>he?h.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":h.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(tn.Provider,{value:h,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(Kh,{meshTheme:h,activeTab:C,onActiveTabChange:M,helpOpen:S,onHelpOpenChange:A})}),S&&s.jsx($1,{meshTheme:h,onClose:()=>A(!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(y1,{status:f,daemonId:n,meshId:f.meshId,sendDaemonCommand:r})}),s.jsx("div",{className:`${C==="status"?"flex":"hidden"} min-h-0 flex-1 flex-col overflow-y-auto`,children:C==="status"&&s.jsx(cC,{canonicalStatus:f})}),s.jsx("div",{className:`${C==="graph"?"flex":"hidden"} min-h-0 flex-1 flex-col gap-4`,children:s.jsxs("div",{className:`${h.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 ${h.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 ${h.textSecondary}`,children:[s.jsx(Ve,{label:H,tone:be,className:"shrink-0"}),x.stats.blockedReviewNodes>0&&s.jsx(Ve,{label:`${x.stats.blockedReviewNodes} blocked`,title:`${x.stats.blockedReviewNodes} blocked review`,tone:"danger",className:"shrink-0"}),x.stats.notMergeableNodes>0&&s.jsx(Ve,{label:`${x.stats.notMergeableNodes} not mergeable`,tone:"danger",className:"shrink-0"}),x.stats.mergeReadyNodes>0&&s.jsx(Ve,{label:`${x.stats.mergeReadyNodes} need merge`,tone:"warn",className:"shrink-0"}),x.stats.cleanupCandidateNodes>0&&s.jsx(Ve,{label:`${x.stats.cleanupCandidateNodes} cleanup`,title:`${x.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info",className:"shrink-0"}),x.stats.offlineNodes>0&&s.jsx(Ve,{label:`${x.stats.offlineNodes} offline`,tone:"danger",className:"shrink-0"}),x.stats.incompleteSnapshotNodes>0&&s.jsx(Ve,{label:`${x.stats.incompleteSnapshotNodes} incomplete`,title:`${x.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn",className:"shrink-0"}),x.stats.missingGitSnapshotNodes>0&&s.jsx(Ve,{label:`${x.stats.missingGitSnapshotNodes} no-git`,title:`${x.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn",className:"shrink-0"}),x.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(Ve,{label:`${x.stats.missingSubmoduleSnapshotNodes} no-submod`,title:`${x.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn",className:"shrink-0"}),x.stats.staleGitSnapshotNodes>0&&s.jsx(Ve,{label:`${x.stats.staleGitSnapshotNodes} stale`,title:`${x.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn",className:"shrink-0"}),((ne==null?void 0:ne.active)??0)>0&&s.jsx(Ve,{label:`${(ne==null?void 0:ne.active)??0} active queue`,tone:"info",className:"shrink-0 hidden sm:inline-flex"}),s.jsx(Ve,{label:`${x.stats.totalNodes} nodes`,tone:"default",className:"shrink-0 hidden sm:inline-flex"}),x.stats.totalActiveSessions>0&&s.jsx(Ve,{label:`${x.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:h.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:()=>Ce("auto"),className:$e(Ne==="auto"),title:"Auto-detect direction",children:"Auto"}),s.jsx("button",{type:"button",onClick:()=>Ce("LR"),className:$e(Ne==="LR"),title:"Left to right",children:"LR"}),s.jsx("button",{type:"button",onClick:()=>Ce("TB"),className:$e(Ne==="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 ${h.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 ${h.textSecondary} [&::-webkit-details-marker]:hidden`,children:(()=>{var Fe;const he=((Fe=f.asyncRefineJobs)==null?void 0:Fe.filter(Ie=>Ie.status==="failed").length)??0,Ee=ue.recentFailures;return he>0?s.jsxs("span",{className:h.isDark?"text-rose-300":"text-rose-600",children:[he," refine failed"]}):Ee>0?s.jsxs("span",{className:h.isDark?"text-amber-300":"text-amber-600",children:[Ee," failures"]}):d("meshGraph.obs.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 ${h.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsx(dC,{canonicalStatus:f,queueSummary:ne,ledgerSummary:ue,isBootstrapMode:y,meshTheme:h,sessionEntries:ae,inlineMode:!0})})]})}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${h.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 ${h.textSecondary} [&::-webkit-details-marker]:hidden`,children:d("meshGraph.obs.legend")}),s.jsx("div",{className:`absolute right-0 z-40 mt-2 w-72 rounded-xl border p-3 shadow-xl backdrop-blur-xl ${h.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(Ve,{label:`${x.stats.dirtyNodes} dirty`,tone:x.stats.dirtyNodes>0?"warn":"good"}),s.jsx(Ve,{label:`${x.stats.orphanNodes} orphan`,tone:x.stats.orphanNodes>0?"warn":"good"}),s.jsx(Ve,{label:`${ue.recentFailures} recent failures`,tone:ue.recentFailures>0?"danger":"good"}),O.length===0?s.jsx(Ve,{label:"no session metadata"}):O.slice(0,2).map(([he,Ee])=>s.jsx(Ve,{label:`${Ee} ${he}`,tone:Co(he)},he))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ve,{label:"Anchor = default branch",tone:"info"}),s.jsx(Ve,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(Ve,{label:"Submodule link = child checkout",tone:"warn"})]}),je.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:je.map(he=>s.jsx("span",{className:h.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:he},he))}),s.jsx("div",{className:`text-xs ${h.textMuted}`,children:"Click a node or edge to pin its drill-down details in the side panel. Click it again to close."})]})})]})})]})]}),y&&x.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 ${h.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 ${h.isDark?"bg-amber-400":"bg-amber-500"}`,"aria-hidden":!0}),s.jsx("span",{children:d("meshGraph.obs.bootstrapBanner")})]}),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:T?x.nodes.length>0?s.jsx(l1,{data:x,selectedNodeId:P,directionPref:Ne,onNodeClick:he=>{if((_==null?void 0:_.kind)==="node"&&P===he.id){F();return}R(null),B(he.id),K({kind:"node",nodeId:he.id})},onEdgeClick:he=>{if((_==null?void 0:_.kind)==="edge"&&z===he.id){F();return}B(null),R(he.id),K({kind:"edge",edgeId:he.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:v}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:d("meshGraph.obs.loadingGraph")})}),X&&(_==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 ${h.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 ${h.textMuted}`,children:d("meshGraph.obs.selectedNode")}),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 ${h.textPrimary}`,children:X.label}),s.jsx("div",{className:`mt-0.5 font-mono text-[11px] ${h.textMuted}`,children:X.id.slice(0,16)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[X.behind>0&&s.jsx("button",{type:"button",onClick:()=>{le()},disabled:!ce||G===X.id,className:h.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:G===X.id?d("meshGraph.obs.checking"):d("meshGraph.obs.heal")}),s.jsx("button",{type:"button",onClick:F,"aria-label":"Close detail panel",className:h.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 he=(se==null?void 0:se.health)??X.health;return he==="unknown"?s.jsx(Ve,{label:d("meshGraph.obs.connecting"),tone:"default"}):s.jsx(Ve,{label:he,tone:Wh(he)})})(),X.branch&&s.jsx(Ve,{label:X.branch,tone:"default"}),X.ahead>0&&s.jsx(Ve,{label:`ahead ${X.ahead}`,tone:"warn"}),X.behind>0&&s.jsx(Ve,{label:`behind ${X.behind}`,tone:"warn"}),X.dirtyFiles>0&&s.jsx(Ve,{label:`${X.dirtyFiles} dirty`,tone:"warn"}),(se==null?void 0:se.connection)&&se.connection.state!=="unknown"&&s.jsx(Ve,{label:Z1(se),tone:W1(se.connection)}),((it=se==null?void 0:se.connection)==null?void 0:it.state)==="unknown"&&s.jsx(Ve,{label:d("meshGraph.obs.meshConnecting"),tone:"warn"}),me.length>0&&s.jsx(Ve,{label:`${me.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[X.machineLabel&&s.jsx(Dt,{label:d("meshGraph.obs.fieldMachine"),value:X.machineLabel}),X.locality&&X.locality!=="unknown"&&s.jsx(Dt,{label:d("meshGraph.obs.fieldLocality"),value:X.locality}),s.jsx(Dt,{label:d("meshGraph.obs.fieldWorkspace"),value:(se==null?void 0:se.workspace)??X.workspace}),V&&s.jsx(Dt,{label:d("meshGraph.obs.fieldHead"),value:V}),(X.dirtyFiles>0||X.ahead>0||X.behind>0)&&s.jsx(Dt,{label:d("meshGraph.obs.fieldDirtyAheadBehind"),value:`${X.dirtyFiles}/${X.ahead}/${X.behind}`}),me.length>0&&s.jsx(Dt,{label:d("meshGraph.obs.fieldSessions"),value:String(me.length)}),X.upstream&&s.jsx(Dt,{label:d("meshGraph.obs.fieldUpstream"),value:X.upstream}),(()=>{var Ee;const he=((Ee=se==null?void 0:se.connection)==null?void 0:Ee.source)??eC(X);return he&&he!=="unknown"?s.jsx(Dt,{label:d("meshGraph.obs.fieldSource"),value:String(he)}):null})(),(()=>{var Ee;const he=(Ee=se==null?void 0:se.connection)==null?void 0:Ee.transport;return he&&he!=="unknown"?s.jsx(Dt,{label:d("meshGraph.obs.fieldTransport"),value:he}):null})(),(()=>{const he=X.machineId??(se==null?void 0:se.machineId);return he?s.jsx(Dt,{label:d("meshGraph.obs.fieldMachineId"),value:he}):null})(),(()=>{const he=X.daemonId??(se==null?void 0:se.daemonId);return he?s.jsx(Dt,{label:d("meshGraph.obs.fieldDaemonId"),value:he}):null})()]}),me.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${h.textMuted}`,children:d("meshGraph.obs.activeSessions")}),s.jsx("div",{className:"flex flex-col gap-1.5",children:me.map(he=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${h.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 ${h.textMuted}`,title:he.session.sessionId,children:Uh(he.session.sessionId)}),s.jsx(Ve,{label:Qr(he.session),tone:Co(Qr(he.session))})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 ${h.textMuted}`,children:[s.jsx("span",{className:"truncate",children:he.session.providerType||d("meshGraph.obs.providerUnknown")}),s.jsx("span",{children:B1(he.session)}),s.jsx("span",{children:O1(he.session)})]}),he.session.statusNote&&s.jsx("div",{className:`mt-1 text-[10px] leading-4 ${h.textMuted}`,children:he.session.statusNote}),s.jsxs("div",{className:`mt-0.5 truncate ${h.textMuted}`,title:he.session.workspace||he.workspace,children:[(he.session.workspace||he.workspace).slice(0,38),he.branch?` · ${he.branch}`:""]})]},he.session.sessionId))})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${h.textMuted}`,children:d("meshGraph.obs.ledger")}),s.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[s.jsx(Dt,{label:d("meshGraph.obs.fieldCompleted"),value:String(ue.taskCompleted)}),s.jsx(Dt,{label:d("meshGraph.obs.fieldFailed"),value:s.jsx("span",{className:ue.taskFailed>0?h.isDark?"text-rose-300":"text-rose-600":"",children:ue.taskFailed})}),s.jsx(Dt,{label:d("meshGraph.obs.fieldLaunched"),value:String(ue.sessionLaunched)}),s.jsx(Dt,{label:d("meshGraph.obs.fieldRecentFailures"),value:s.jsx("span",{className:ue.recentFailures>0?h.isDark?"text-amber-300":"text-amber-600":"",children:ue.recentFailures})})]})]}),(()=>{var Fe,Ie;const he=((Fe=f.queue)==null?void 0:Fe.tasks)??((Ie=f.queue)==null?void 0:Ie.items)??null;if(!Array.isArray(he)||he.length===0)return null;const Ee=he.filter(ve=>q1(ve)===P).slice(0,3);return Ee.length===0?null:s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${h.textMuted}`,children:d("meshGraph.obs.queueTasks")}),s.jsx("div",{className:"flex flex-col gap-1.5",children:Ee.map(ve=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${h.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 ${h.textMuted}`,children:ve.id.slice(0,12)}),s.jsx(Ve,{label:ve.status??"unknown",tone:Co(ve.status)})]}),ve.message&&s.jsx("div",{className:`mt-0.5 truncate ${h.textMuted}`,children:ve.message.slice(0,48)})]},ve.id))})]})})(),X.snapshotWarnings.length>0&&s.jsxs("div",{className:h.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:d("meshGraph.obs.keyWarning")}),s.jsx("div",{className:"mt-1",children:X.snapshotWarnings[0]})]}),X.branchConvergence&&(X.branchConvergence.reason||X.branchConvergence.nextStep)&&s.jsxs("div",{className:h.isDark?"mt-3 rounded-xl border border-sky-400/20 bg-sky-500/10 p-3 text-xs text-sky-100":"mt-3 rounded-xl border border-sky-300 bg-sky-50 p-3 text-xs text-sky-800",children:[s.jsx("div",{className:"font-medium",children:d("meshGraph.obs.followUpLabel",{status:g[X.branchConvergence.status]??X.branchConvergence.status})}),X.branchConvergence.reason&&s.jsx("div",{className:"mt-1",children:X.branchConvergence.reason}),X.branchConvergence.nextStep&&s.jsx("div",{className:`${X.branchConvergence.reason?"mt-1.5 pt-1.5 border-t border-sky-400/20":"mt-1"}`,children:X.branchConvergence.nextStep})]}),$&&s.jsxs("div",{className:h.isDark?"mt-3 rounded-xl border border-emerald-400/20 bg-emerald-500/10 p-3 text-xs text-emerald-100":"mt-3 rounded-xl border border-emerald-300 bg-emerald-50 p-3 text-xs text-emerald-800",children:[s.jsx("div",{className:"font-medium",children:$.phase==="execute"?d("meshGraph.obs.healResult"):d("meshGraph.obs.healPreview")}),s.jsx("div",{className:"mt-1",children:$.code??$.error??d("meshGraph.obs.noResultCode")})]})]}),oe&&(_==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 ${h.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 ${h.textMuted}`,children:d("meshGraph.obs.selectedEdge")}),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 ${h.textPrimary}`,children:oe.label||ud(oe)}),s.jsx("div",{className:`mt-0.5 break-all font-mono text-[11px] ${h.textMuted}`,children:oe.id})]}),s.jsx("button",{type:"button",onClick:F,"aria-label":"Close detail panel",className:h.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(Ve,{label:ud(oe),tone:"default"}),s.jsx(Ve,{label:tC(oe),tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(Dt,{label:d("meshGraph.obs.fieldFrom"),value:(Se==null?void 0:Se.label)??oe.source}),s.jsx(Dt,{label:d("meshGraph.obs.fieldTo"),value:(ye==null?void 0:ye.label)??oe.target}),s.jsx(Dt,{label:d("meshGraph.obs.fieldLabel"),value:oe.label??"none"})]})]})]})]})})]})})}function Ct(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 n of e){const r=Ct(n);r&&t.add(r)}return[...t]}function pC(e,t){var m,h;const n=xi(e==null?void 0:e.settings),r=Ct((m=e==null?void 0:e.coordinator)==null?void 0:m.meshId)||Ct(n.meshCoordinatorFor),a=Ct(n.meshNodeFor),o=!!r||!!a,i=r===t||a===t;if(o&&!i)return null;const u=xi(e==null?void 0:e.activeChat),c=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,u.sessionId,u.session_id,u.providerSessionId,u.provider_session_id),p=c[0]||"";if(!p)return null;const d=r===t?Ct((h=e==null?void 0:e.coordinator)==null?void 0:h.role)||"coordinator":a===t?Ct(n.meshNodeRole)||"worker":Ct(e==null?void 0:e.role)||Ct(n.meshNodeRole)||void 0;return{sessionId:p,aliases:c,meshId:t,nodeId:i&&Ct(n.meshNodeId)||null,providerType:Ct(e==null?void 0:e.providerType)||void 0,state:Ct(e==null?void 0:e.status)||void 0,chatStatus:Ct(u.status)||void 0,lifecycle:Ct(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:Ct(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:Ct(e==null?void 0:e.runtimeRecoveryState)||void 0,...d?{role:d}:{},...i?{isSelfCoordinator:r===t}:{},workspace:Ct(e==null?void 0:e.workspace)||null}}function Gh(e,t){var r;return t?(Array.isArray((r=e.status)==null?void 0:r.sessions)?e.status.sessions:[]).map(a=>pC(a,t)).filter(a=>a!==null):[]}function ya(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function hC(e,t){const n=new Set(ya(t));return ya(e).some(r=>n.has(r))}function mC(e,t){const n=t.filter(a=>!!a);return n.length===0?e:[...e.filter(a=>!n.some(o=>hC(a,o))),...n]}function fC(e,t){if(t.length===0)return e;const n=new Map;for(const i of t)for(const u of ya(i))n.set(u,i);let r=!1;const o=(e.nodes??[]).map((i,u)=>{const c=Array.isArray(i.activeSessionDetails)?i.activeSessionDetails:Array.isArray(i.sessions)?i.sessions:[],p=new Map;for(const h of c){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),v=g[0]||"";if(!v)continue;const f=g.map(y=>n.get(y)).find(Boolean);f&&(r=!0),p.set(v,f?{...h,sessionId:v,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:v})}for(const h of i.activeSessions??[])p.has(h)||p.set(h,{sessionId:h,workspace:i.workspace,isCached:!0});const d=u===0;for(const h of t){if(ya(h).some(y=>p.has(y)))continue;const v=h.nodeId!=null&&h.nodeId===i.nodeId,f=h.isSelfCoordinator&&!h.nodeId&&d;!v&&!f||(r=!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 r?{...e,nodes:o}:e}function xC(e,t){const r=Gh(e,t).map(a=>{var c;const o=(Array.isArray((c=e.status)==null?void 0:c.sessions)?e.status.sessions:[]).find(p=>Ct(p==null?void 0:p.id)===a.sessionId),i=xi(o==null?void 0:o.activeInteractivePrompt),u=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??"",Ct(i.status)||Ct(i.kind)||Ct(i.type),a.nodeId??"",a.isSelfCoordinator?"coordinator":"worker",u].join("|")}).filter(a=>!!a).sort();return r.length>0?r.join(`
84
- `):null}function zh({status:e,daemonId:t,extraDaemonIds:n,meshId:r,sendData:a,extraLiveSessions:o=[]}){const[i,u]=l.useState(new Map),c=l.useRef(new Map),p=l.useMemo(()=>{const g=new Set;if(t&&g.add(t),n)for(const v of n)v&&g.add(v);return[...g].sort()},[t,n]),d=p.join(",");l.useEffect(()=>{c.current=new Map,u(new Map)},[t,r]),l.useEffect(()=>{if(!r||!a||p.length===0)return;const g=p.map(v=>ls.subscribe({sendData:a},v,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${v}`,params:{includeSessions:!0}},f=>{if(f.topic!=="daemon.metadata")return;const y=xC(f,r);if(y===(c.current.get(v)??null))return;c.current.set(v,y);const j=Gh(f,r);u(x=>{const w=new Map(x);return w.set(v,j),w})}));return()=>{for(const v of g)v()}},[d,r,a]);const m=l.useMemo(()=>{const g=[];for(const v of i.values())g.push(...v);return g},[i]),h=l.useMemo(()=>mC(m,o),[o,m]);return l.useMemo(()=>e?fC(e,h):null,[h,e])}const pd=[1500,4e3,9e3];function bC(e){var t,n,r,a,o,i;return!!(((t=e.git)==null?void 0:t.isGitRepo)===!0||(n=e.git)!=null&&n.branch||(r=e.git)!=null&&r.upstream||(a=e.git)!=null&&a.headCommit||(o=e.git)!=null&&o.workspace||(i=e.git)!=null&&i.repoRoot)}function gC(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>{var n;return bC(t)?!1:t.gitProbePending||((n=t.connection)==null?void 0:n.state)==="connecting"?!0:t.machineStatus==="online"||t.launchReady===!0})}function yC(e){return!Number.isInteger(e)||e<0?pd[0]:pd[e]??null}const Mo=new Map;function vC(e,t){return!e||!t?null:`${e}::${t}`}function wC(e,t){var o,i,u,c;if(!t||!e.sessionId)return null;const n=((o=e.coordinator)==null?void 0:o.meshId)??(typeof((i=e.settings)==null?void 0:i.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),r=typeof((u=e.settings)==null?void 0:u.meshNodeFor)=="string"?e.settings.meshNodeFor:null;if(n!==t&&r!==t)return null;const a=typeof((c=e.settings)==null?void 0:c.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:n===t?"coordinator":"worker",isSelfCoordinator:n===t,workspace:e.workspacePath??null}}function Vh({activeConv:e,sendDaemonCommand:t,onClose:n}){var Z,q,ne,ue,ae,O;const r=((Z=e.coordinator)==null?void 0:Z.meshId)??(typeof((q=e.settings)==null?void 0:q.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),a=e.daemonId??null,o=vC(a,r),i=o?Mo.get(o)??null:null,u=Fi(),{sendData:c}=yt(),{theme:p}=Ls(),d=l.useMemo(()=>Rs(p),[p]),[m,h]=l.useState("overview"),[g,v]=l.useState(!1),f=l.useMemo(()=>wC(e,r),[e.agentType,(ne=e.coordinator)==null?void 0:ne.meshId,e.sessionId,(ue=e.settings)==null?void 0:ue.meshCoordinatorFor,(ae=e.settings)==null?void 0:ae.meshNodeFor,(O=e.settings)==null?void 0:O.meshNodeId,e.status,e.workspacePath,r]),[y,j]=l.useState(i),[x,w]=l.useState(!1),[N,k]=l.useState(!1),[b,C]=l.useState(!1),[S,M]=l.useState(null),[A,T]=l.useState((i==null?void 0:i.refreshedAt)??null),L=l.useRef(i!==null),P=l.useRef(!1),B=l.useRef(!1),z=l.useRef(!0),R=l.useRef(0),_=l.useRef(null);l.useEffect(()=>{L.current=y!==null},[y]);const K=l.useCallback(()=>{_.current!==null&&(clearTimeout(_.current),_.current=null)},[]);l.useEffect(()=>{K(),R.current=0;const se=o?Mo.get(o)??null:null;j(se),T((se==null?void 0:se.refreshedAt)??null),L.current=se!==null,B.current=!1,k(!1),M(null)},[o,K]);const E=l.useCallback(async(se=!1,X=!1)=>{if(!a||!r){M("This coordinator does not expose a live mesh id."),j(null);return}if(P.current){se&&(B.current=!0);return}X||(K(),R.current=0),P.current=!0;const oe=!L.current;w(oe),k(se&&L.current),M(null);try{const Se=u!=null&&u.loadMeshStatus?await u.loadMeshStatus(a,r,{refresh:se,retryProfile:X?"interactive":"settled"}):await t(a,"mesh_status",{meshId:r,refresh:se}),ye=Hi(Se);if(!ye){M("mesh_status returned an unexpected payload.");return}if(o&&Mo.set(o,ye),j(ye),L.current=!0,T(ye.refreshedAt||new Date().toISOString()),gC(ye.nodes)){const ke=yC(R.current);ke!==null&&z.current&&(R.current+=1,_.current=setTimeout(()=>{z.current&&E(!0,!0)},ke))}else R.current=0}catch(Se){M(Se instanceof Error?Se.message:"Failed to load live mesh status")}finally{P.current=!1,w(!1),k(!1),B.current&&z.current&&(B.current=!1,window.setTimeout(()=>{z.current&&E(!0)},0))}},[o,K,a,r,u,t]);l.useEffect(()=>(z.current=!0,R.current=0,(async()=>(await E(!1,!0),z.current&&_.current===null&&!P.current&&E(!0,!0)))(),()=>{z.current=!1,K()}),[E,K]),l.useEffect(()=>{const se=X=>{X.key==="Escape"&&n()};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[n]);const D=(y==null?void 0:y.meshName)||r||"Repo Mesh",$=l.useMemo(()=>f?[f]:[],[f]),I=zh({status:y,daemonId:a,meshId:r,sendData:c,extraLiveSessions:$}),G=A?new Date(A).toLocaleTimeString():null,Y=l.useMemo(()=>x?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[x]);return s.jsx("div",{className:d.dialogOverlayClass,onClick:n,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:d.dialogShellClass,onClick:se=>se.stopPropagation(),children:[s.jsxs("div",{className:`relative ${d.dialogHeaderClass}`,children:[s.jsx("button",{type:"button",onClick:n,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 ${d.dialogCloseButtonClass}`,"aria-label":"Close mesh graph",children:s.jsx(Mt,{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(es,{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:d.dialogTitleClass,children:D}),s.jsx("span",{className:d.dialogKickerClass,children:"Mesh observability"}),s.jsx("button",{type:"button",onClick:()=>C(se=>!se),"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:`${d.dialogSubtitleClass} ${b?"block":"hidden"} md:block`,children:[gt(e),e.workspaceName?` · ${e.workspaceName}`:"",y!=null&&y.repoIdentity?` · ${y.repoIdentity}`:""]})]})]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end md:pr-12",children:[s.jsx(Kh,{meshTheme:d,activeTab:m,onActiveTabChange:h,helpOpen:g,onHelpOpenChange:v}),G&&s.jsx("span",{className:`${d.dialogRefreshedChipClass} ${b?"inline-flex":"hidden"} md:inline-flex`,children:`Refreshed ${G}`}),!N&&y&&s.jsx("span",{className:`${d.dialogRefreshedChipClass} ${b?"inline-flex":"hidden"} md:inline-flex`,children:c&&!S?"Live daemon metadata":"Metadata subscription unavailable"}),s.jsx("button",{type:"button",onClick:()=>{E(!0)},disabled:x||N,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:x||N?"Refreshing…":"Refresh"})]})]}),S&&s.jsx("div",{className:d.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:d.dialogBodyClass,children:I?s.jsx(uC,{status:I,emptyMessage:Y,daemonId:a,sendDaemonCommand:t,activeTab:m,onActiveTabChange:h,helpOpen:g,onHelpOpenChange:v,hideControls:!0}):s.jsx("div",{className:d.dialogEmptyClass,children:Y})})]})})}function kC(e,t){const{sendCommand:n}=yt(),[r,a]=l.useState(null),[o,i]=l.useState(!1);l.useEffect(()=>{if(!e||!t){a(null);return}i(!0),n(e,"git_remote_url",{workspace:t}).then(c=>{const p=(c==null?void 0:c.result)??c;a(typeof(p==null?void 0:p.remoteUrl)=="string"?p.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>i(!1))},[e,t,n]);const u=jC(r);return{remoteUrl:r,githubUrl:u,loading:o}}function jC(e){if(!e)return null;const t=e.match(/git@github\.com[:/](.+?)(?:\.git)?$/);if(t)return`https://github.com/${t[1]}`;const n=e.match(/https?:\/\/github\.com\/(.+?)(?:\.git)?$/);return n?`https://github.com/${n[1]}`:null}const qh=5e3;function SC(e){return`git:${e}`}function NC({workspace:e,includeDiffSummary:t=!1,intervalMs:n=qh}){return{type:"subscribe",topic:"workspace.git",key:SC(e),params:{workspace:e,includeDiffSummary:t,intervalMs:n}}}function hl(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 n=e;if(typeof n.error=="string"&&n.error.trim())return n.error;if(typeof n.message=="string"&&n.message.trim())return n.message}return t}function CC(e){const t=hl(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 MC(e){const t=hl(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 AC(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 IC(e){const t=hl(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Qs(t,"Git file diff request failed")}:AC(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 TC({daemonId:e,workspace:t,enabled:n=!0,includeDiffSummary:r=!1,intervalMs:a=qh}){const{sendCommand:o,sendData:i}=yt(),u=typeof t=="string"?t.trim():"",c=!!(n&&e&&u),[p,d]=l.useState(null),[m,h]=l.useState(null),[g,v]=l.useState(!1),[f,y]=l.useState(null),j=l.useCallback(async()=>{if(!(!c||!e||!u)){v(!0),y(null);try{const w=CC(await o(e,"git_status",{workspace:u}));if(w.error){d(null),h(null),y(w.error);return}if(d(w.status),!r){h(null);return}const N=MC(await o(e,"git_diff_summary",{workspace:u}));if(N.error){h(null),y(N.error);return}h(N.diffSummary)}catch(w){y(Qs(w,"Git status request failed"))}finally{v(!1)}}},[c,e,r,o,u]),x=l.useMemo(()=>u?NC({workspace:u,includeDiffSummary:r,intervalMs:a}):null,[r,a,u]);return l.useEffect(()=>{if(!c||!e||!u||!x){d(null),h(null),v(!1),y(null);return}const w=i?ls.subscribe({sendData:i},e,x,N=>{var k,b;N.workspace===u&&(d(N.status),h(N.diffSummary??null),y(((k=N.status)==null?void 0:k.error)||((b=N.diffSummary)==null?void 0:b.error)||null),v(!1))},{retryIntervalMs:1e3}):null;return j(),()=>{w==null||w()}},[c,e,j,x,i,u]),{status:p,diffSummary:m,loading:g,error:f,refresh:j}}const PC={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},DC={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 hd(e){return e.split("/").pop()??e}function LC(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function RC({files:e,truncated:t,onFileClick:n,selectedPath:r,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=r===o.path,u=PC[o.status]??"?",c=DC[o.status]??"text-text-muted",p=LC(o.path),d=hd(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:()=>n==null?void 0:n(o),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${c}`,title:o.status,children:u}),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:d}),o.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",hd(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 _C(e,t){let n="text-text-secondary";return e.startsWith("+")&&!e.startsWith("+++")?n="bg-status-online/10 text-status-online":e.startsWith("-")&&!e.startsWith("---")?n="bg-status-error/10 text-status-error":e.startsWith("@@")?n="text-accent-primary":(e.startsWith("diff ")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ "))&&(n="text-text-secondary"),s.jsx("div",{className:`px-3 ${n}`,children:s.jsx("code",{className:"whitespace-pre font-mono text-[11px] leading-5",children:e})},t)}function EC({diff:e,binary:t,truncated:n,loading:r,error:a,className:o=""}){const i=l.useRef(null);if(l.useEffect(()=>{i.current&&(i.current.scrollTop=0)},[e]),r)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 u=e.split(`
85
- `);return s.jsxs("div",{ref:i,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:u.map((c,p)=>_C(c,p))}),n&&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 $C(e,t){const n=[`Branch: ${e||"unknown"}`];n.push(`Changed: ${t.files.length} file(s) +${t.totalInsertions}/-${t.totalDeletions}`);const r={};for(const a of t.files)r[a.status]||(r[a.status]=[]),r[a.status].push(a.path);for(const[a,o]of Object.entries(r))n.push(`${a}: ${o.slice(0,5).join(", ")}${o.length>5?` (+${o.length-5} more)`:""}`);return n.join(`
86
- `)}function Yh({daemonId:e,workspace:t,onClose:n}){const{sendCommand:r}=yt(),{status:a,diffSummary:o,loading:i,error:u,refresh:c}=TC({daemonId:e,workspace:t,includeDiffSummary:!0}),[p,d]=l.useState(null),[m,h]=l.useState(null),[g,v]=l.useState(""),[f,y]=l.useState(!1),[j,x]=l.useState(!1),[w,N]=l.useState(null),[k,b]=l.useState(null),{githubUrl:C}=kC(e,t),S=l.useCallback(async B=>{if(!((p==null?void 0:p.path)===B.path&&!p.loading)){d({path:B.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const z=await r(e,"git_diff_file",{workspace:t,path:B.path,staged:B.staged}),R=IC(z);if(R.error||!R.diff){d({path:B.path,diff:"",binary:!1,truncated:!1,loading:!1,error:R.error??"Failed to load diff"});return}d({path:B.path,diff:R.diff.diff,binary:R.diff.binary??!1,truncated:R.diff.truncated??!1,loading:!1,error:null})}catch(z){const R=z instanceof Error?z.message:"Failed to load diff";d({path:B.path,diff:"",binary:!1,truncated:!1,loading:!1,error:R})}}},[e,r,p,t]),M=l.useCallback(B=>{v(""),y(!1),N(null),b(null),h(B)},[]),A=l.useCallback(()=>{h(null),N(null),x(!1)},[]),T=l.useCallback(async()=>{var B,z,R;if(m){x(!0),N(null);try{let _;m==="checkpoint"?_=await r(e,"git_checkpoint",{workspace:t,message:g,includeUntracked:f}):m==="stash"?_=await r(e,"git_stash_push",{workspace:t,message:g,includeUntracked:f}):m==="stash_pop"?_=await r(e,"git_stash_pop",{workspace:t}):m==="checkout_files"&&p&&(_=await r(e,"git_checkout_files",{workspace:t,paths:[p.path]}));const K=(_==null?void 0:_.result)??_;if((K==null?void 0:K.success)===!1||K!=null&&K.error){N((K==null?void 0:K.error)??"Action failed"),x(!1);return}m==="checkpoint"?b(`Checkpoint created: ${((z=(B=K==null?void 0:K.checkpoint)==null?void 0:B.commit)==null?void 0:z.slice(0,7))??"done"}`):m==="stash"?b(`Stashed as ${((R=K==null?void 0:K.stash)==null?void 0:R.stashRef)??"stash@{0}"}`):m==="stash_pop"?b("Stash restored"):(b("File reverted"),d(null)),h(null),await c()}catch(_){N(_ instanceof Error?_.message:"Action failed")}finally{x(!1)}}},[m,r,e,t,g,f,p,c]),L=!!(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:B=>{B.target===B.currentTarget&&n()},children:s.jsxs("div",{className:"relative flex h-[80vh] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[s.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??"Git Status"}),s.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),C&&s.jsx("a",{href:`${C}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-accent-primary underline",title:"Open on GitHub",children:"GitHub ↗"})]}),s.jsx("button",{onClick:c,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:n,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:s.jsx(Mt,{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]})]})]}),u&&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:u}),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(RC,{files:o.files,truncated:o.truncated,selectedPath:(p==null?void 0:p.path)??null,onFileClick:S}),!i&&!o&&!u&&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(EC,{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"})})]}),k&&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:k}),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:()=>M("checkpoint"),disabled:L,title:L?"Resolve conflicts before checkpointing":"Create a git commit checkpoint",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkpoint"}),s.jsx("button",{onClick:()=>M("stash"),disabled:L,title:L?"Resolve conflicts before stashing":"Stash current changes",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Stash"}),s.jsx("button",{onClick:()=>M("stash_pop"),disabled:L||!(a!=null&&a.stashCount),title:L?"Resolve conflicts before restoring a stash":a!=null&&a.stashCount?"Restore the latest stash":"No stashes to restore",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Pop stash"}),s.jsx("button",{onClick:()=>M("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 B=$C((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(B),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:B=>v(B.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:B=>y(B.target.checked)}),"Include untracked files"]})]}),w&&s.jsx("p",{className:"text-xs text-status-error",children:w}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:A,disabled:j,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:"Cancel"}),s.jsx("button",{onClick:T,disabled:j||(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:j?"Working…":"Confirm"})]})]})})]})})}function FC({isMobile:e,showMobileChatMode:t,visibleConversationCount:n}){const[r,a]=l.useState(!1),[o,i]=l.useState(!1),[u,c]=l.useState(!1),[p,d]=l.useState(!1),[m,h]=l.useState(!1),[g,v]=l.useState("quickstart"),[f,y]=l.useState("workspace"),j=l.useMemo(()=>!t&&!e,[t,e]),x=l.useCallback(S=>{a(S),S&&i(!1)},[]),w=l.useCallback(S=>{i(S),S&&a(!1)},[]),N=l.useCallback(()=>{v(n===0?"quickstart":"shortcuts"),y("workspace"),c(!0),a(!1),i(!1)},[n]),k=l.useCallback(()=>{c(!1)},[]),b=l.useCallback(()=>{d(!0)},[]),C=l.useCallback(()=>{d(!1)},[]);return l.useEffect(()=>{if(!j){h(!1);return}h(!0);const S=window.setTimeout(()=>{h(!1)},1e4);return()=>window.clearTimeout(S)},[j]),{inboxOpen:r,hiddenOpen:o,shortcutHelpOpen:u,newSessionOpen:p,guideNudgeVisible:m,guideTab:g,shortcutSection:f,isDesktopDashboard:j,setGuideTab:v,setShortcutSection:y,handleInboxOpenChange:x,handleHiddenOpenChange:w,handleOpenShortcutHelp:N,closeShortcutHelp:k,openNewSession:b,closeNewSession:C}}function BC(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 HC(e){return e instanceof Error?e.message:String(e||"")}function OC(e){const t=HC(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function WC({showMobileChatMode:e,isMobile:t,activeConv:n,wsStatus:r,isConnected:a,onOpenHistory:o,onOpenRemote:i,onStopCli:u,activeCliViewMode:c,onSetActiveCliViewMode:p,mobileChatConversations:d,hiddenConversations:m,ides:h,actionLogs:g,sendDaemonCommand:v,setActionLogs:f,setCliViewModeOverrides:y,isStandalone:j,initialDataLoaded:x,userName:w,requestedMobileTabKey:N,onRequestedMobileTabConsumed:k,requestedMachineId:b,onRequestedMachineConsumed:C,requestedMobileSection:S,onRequestedMobileSectionConsumed:M,containerRef:A,isSplitMode:T,numGroups:L,groupSizes:P,groupedConvs:B,clearedTabs:z,focusedGroup:R,focusGroup:_,moveTabToGroup:K,splitTabRelative:E,closeGroup:D,handleResizeStart:$,groupActiveTabIds:I,setGroupActiveTab:G,groupTabOrders:Y,setGroupTabOrder:Z,toggleHiddenTab:q,visibleConversations:ne,requestedDesktopTabKey:ue,onRequestedDesktopTabConsumed:ae,onDesktopActiveTabChange:O,onRequestScrollToBottom:se,onHideConversation:X,onShowHiddenConversation:oe,onShowAllHiddenConversations:Se,scrollToBottomRequest:ye,machineEntries:ke,layoutProfile:me,onBrowseMachineDirectory:U,onSaveMachineWorkspace:W,onLaunchMachineIde:Q,onLaunchMachineProvider:V,onListMachineMeshes:fe,onLaunchMeshCoordinator:ce,onListMachineSavedSessions:F,notifications:le,notificationUnreadCount:je,liveSessionInboxState:de,onMarkNotificationRead:H,onMarkNotificationUnread:be,onDeleteNotification:Ne}){const Ce=Rt.useRef(null),{inboxOpen:$e,hiddenOpen:Qe,shortcutHelpOpen:dt,newSessionOpen:it,guideNudgeVisible:he,guideTab:Ee,shortcutSection:Fe,isDesktopDashboard:Ie,setGuideTab:ve,setShortcutSection:Oe,handleInboxOpenChange:ut,handleHiddenOpenChange:ot,handleOpenShortcutHelp:pt,closeShortcutHelp:J,openNewSession:te,closeNewSession:ie}=FC({isMobile:t,showMobileChatMode:e,visibleConversationCount:ne.length}),[pe,ge]=Rt.useState(null),[Ae,De]=Rt.useState(null),Me=Rt.useCallback((Te,Je)=>{ge({daemonId:Te,workspace:Je})},[]),Be=Rt.useCallback(Te=>{De(Te)},[]),We=Rt.useCallback(Te=>{var Je;fn.flushSync(()=>{oe(Te)}),(Je=Ce.current)==null||Je.restoreHiddenTabToSavedLocation(Te.tabKey)},[oe]),Ze=Rt.useCallback(Te=>{var Pt;const Je=d.find(It=>Jo(It,Te))||m.find(It=>Jo(It,Te));Je&&(m.some(It=>It.tabKey===Je.tabKey)&&We(Je),O(Je.tabKey),(Pt=Ce.current)==null||Pt.activateConversationTab(Je.tabKey),se(Je.tabKey,"notification-open")),H(Te.id),ut(!1)},[We,m,d,O,H,se]),_e=Rt.useCallback(()=>{var Je;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Je=Ce.current)==null||Je.resetAllPanelsToMain(),ot(!1))},[ot]),Ue=Rt.useCallback(async Te=>{var qt;if(!n)return;const Je=(qt=n.modalButtons)==null?void 0:qt[Te];if(!Je)return;const Pt=Us(n);if(!Pt)return;const It=Je.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Vt=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(It);try{await v(Pt,"resolve_action",{button:Je,action:Vt?"approve":"reject",buttonIndex:Te,...Ws(n)})}catch(Yt){OC(Yt)||console.error("[Shortcut approval] Failed:",Yt)}},[n,v]),{isMac:et,actionDefinitions:ee,actionShortcuts:xe,shortcutListening:we,shortcutListeningDraft:Ge,setShortcutListening:He,setShortcutListeningDraft:tt,saveShortcuts:ze}=gS({enabled:Ie&&!dt,onTrigger:Te=>{var Je,Pt,It,Vt,qt,Yt,gs,Le,rt,Nt,Wt,re,Ke,Re,vt,Jt;if(Te==="openShortcutHelp"){pt();return}if(Te==="openNewSession"){te();return}if(Te==="hideCurrentTab"){n&&X(n);return}if(Te==="toggleHiddenTabs"){ot(!Qe);return}if(Te==="openHistoryForActiveTab"){n&&!lt(n)&&o(n);return}if(Te==="openRemoteForActiveTab"){n&&!ct(n)&&!lt(n)&&i(n);return}if(Te==="splitActiveTabRight"){(Je=Ce.current)==null||Je.splitActiveTabRight();return}if(Te==="splitActiveTabDown"){(Pt=Ce.current)==null||Pt.splitActiveTabDown();return}if(Te==="floatActiveTab"){(It=Ce.current)==null||It.floatActiveTab();return}if(Te==="popoutActiveTab"){(Vt=Ce.current)==null||Vt.popoutActiveTab();return}if(Te==="dockActiveTab"){(qt=Ce.current)==null||qt.dockActiveTab();return}if(Te==="focusLeftPane"){(Yt=Ce.current)==null||Yt.focusLeftPane();return}if(Te==="focusRightPane"){(gs=Ce.current)==null||gs.focusRightPane();return}if(Te==="focusUpPane"){(Le=Ce.current)==null||Le.focusUpPane();return}if(Te==="focusDownPane"){(rt=Ce.current)==null||rt.focusDownPane();return}if(Te==="moveActiveTabToLeftPane"){(Nt=Ce.current)==null||Nt.moveActiveTabToLeftPane();return}if(Te==="moveActiveTabToRightPane"){(Wt=Ce.current)==null||Wt.moveActiveTabToRightPane();return}if(Te==="moveActiveTabToUpPane"){(re=Ce.current)==null||re.moveActiveTabToUpPane();return}if(Te==="moveActiveTabToDownPane"){(Ke=Ce.current)==null||Ke.moveActiveTabToDownPane();return}if(Te==="triggerPrimaryApprovalAction"){Ue(0);return}if(Te==="triggerSecondaryApprovalAction"){Ue(1);return}if(Te==="triggerTertiaryApprovalAction"){Ue(2);return}if(Te==="setActiveTabShortcut"){(Re=Ce.current)==null||Re.setShortcutForActiveTab();return}if(Te==="selectPreviousGroupTab"){(vt=Ce.current)==null||vt.activatePreviousTabInGroup();return}if(Te==="selectNextGroupTab"){(Jt=Ce.current)==null||Jt.activateNextTabInGroup();return}!n||!ct(n)||lt(n)||Te==="toggleCliView"&&p(c==="chat"?"terminal":"chat")}}),qe=Rt.useCallback(()=>{J(),He(null),tt([])},[J,He,tt]),At=Rt.useMemo(()=>Fe==="all"?ee:ee.filter(Te=>BC(Te)===Fe),[ee,Fe]),Ot=Rt.useCallback(()=>{const Te=Object.fromEntries(ee.map(Je=>[Je.id,""]));ze(Te)},[ee,ze]),ss=Rt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const Te=Object.fromEntries(ee.map(Je=>[Je.id,Je.defaultShortcut]));ze(Te)},[ee,ze]);return Rt.useEffect(()=>{const Te=Je=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Je.metaKey&&Je.key.toLowerCase()==="w":Je.ctrlKey&&Je.key.toLowerCase()==="w")&&(Je.preventDefault(),n&&X&&X(n))};return window.addEventListener("keydown",Te),()=>window.removeEventListener("keydown",Te)},[n,X]),Rt.useEffect(()=>{if(!dt||we)return;const Te=Je=>{Je.key==="Escape"&&(Je.preventDefault(),qe())};return window.addEventListener("keydown",Te,!0),()=>window.removeEventListener("keydown",Te,!0)},[qe,dt,we]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(ew,{activeConv:n,wsStatus:r,isConnected:a,conversations:ne,hiddenConversations:m,onOpenHistory:o,onHideConversation:X,onShowConversation:We,onShowAllHidden:Se,onResetPanelsToMain:_e,notifications:le,notificationUnreadCount:je,onOpenNotification:Ze,onMarkNotificationRead:H,onMarkNotificationUnread:be,onDeleteNotification:Ne,inboxOpen:$e,onInboxOpenChange:ut,hiddenOpen:Qe,onHiddenOpenChange:ot,onOpenNewSession:t?void 0:te,onOpenDashboardGuide:pt,guideNudgeVisible:he,actionShortcuts:xe,onOpenRemote:()=>{!n||ct(n)||lt(n)||i(n)},onStopCli:u,activeCliViewMode:c,onSetCliViewMode:p,onOpenGitDialog:Me,onOpenMeshGraph:Be}),e?s.jsx(oS,{conversations:d,hiddenConversations:m,ides:h,actionLogs:g,sendDaemonCommand:v,setActionLogs:f,setCliViewModeOverrides:y,isStandalone:j,userName:w,requestedActiveTabKey:N,onRequestedActiveTabConsumed:k,requestedMachineId:b,onRequestedMachineConsumed:C,requestedMobileSection:S,onRequestedMobileSectionConsumed:M,onOpenHistory:o,onOpenRemote:i,onStopCli:u,wsStatus:r,isConnected:a,onShowAllHiddenConversations:Se,onHideConversation:X,onOpenMeshGraph:Be,onOpenNewSession:te,liveSessionInboxState:de}):t?s.jsx(mS,{containerRef:A,isSplitMode:T,numGroups:L,groupSizes:P,groupedConvs:B,clearedTabs:z,ides:h,actionLogs:g,sendDaemonCommand:v,setActionLogs:f,isStandalone:j,hasRegisteredMachines:ke.length>0,userName:w,focusedGroup:R,focusGroup:_,moveTabToGroup:K,splitTabRelative:E,closeGroup:D,handleResizeStart:$,groupActiveTabIds:I,setGroupActiveTab:G,groupTabOrders:Y,setGroupTabOrder:Z,toggleHiddenTab:q,onOpenNewSession:te,allowTabShortcuts:!1,liveSessionInboxState:de}):s.jsx(DS,{visibleConversations:ne,clearedTabs:z,ides:h,actionLogs:g,sendDaemonCommand:v,setActionLogs:f,isStandalone:j,hasRegisteredMachines:ke.length>0,initialDataLoaded:x,userName:w,toggleHiddenTab:q,actionShortcuts:xe,registerActionHandlers:Te=>{Ce.current=Te},onActiveTabChange:O,requestedActiveTabKey:ue,onRequestedActiveTabConsumed:ae,onRequestScrollToBottom:se,scrollToBottomRequest:ye,onOpenNewSession:te,liveSessionInboxState:de,layoutProfile:me}),it&&s.jsx(WS,{machines:ke,ides:h,onClose:ie,onBrowseDirectory:U,onSaveWorkspace:W,onLaunchIde:Q,onLaunchProvider:V,onListMeshes:fe,onLaunchMeshCoordinator:ce,onListSavedSessions:F}),Ae&&s.jsx(Vh,{activeConv:Ae,sendDaemonCommand:v,onClose:()=>De(null)}),pe&&s.jsx(Yh,{daemonId:pe.daemonId,workspace:pe.workspace,onClose:()=>ge(null)}),dt&&s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:qe,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:Te=>Te.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:qe,"aria-label":"Close dashboard guide",children:s.jsx(Mt,{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(Te=>s.jsx("button",{type:"button",className:`btn btn-sm ${Ee===Te.id?"btn-primary":"btn-secondary"}`,onClick:()=>ve(Te.id),children:Te.label},Te.id))}),Ee==="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 ",et?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),Ee==="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."]})]})]})]}),Ee==="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(Te=>s.jsx("button",{type:"button",className:`btn btn-sm ${Fe===Te.id?"btn-primary":"btn-secondary"}`,onClick:()=>Oe(Te.id),children:Te.label},Te.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ot,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:ss,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:At.map(Te=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${we===Te.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:Te.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Te.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:Te.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:we===Te.id?Ge.length>0?`${Ge.join(" ")} ...`:"Listening...":xe[Te.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{He(Te.id),tt([])},children:we===Te.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Je={...xe};Je[Te.id]="",ze(Je)},children:"Disable"})]})]})},Te.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",et?"⌘⇧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 UC=[{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:"🕸️"}],KC={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"},GC={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 zC({onClose:e,standalone:t=!1}){const[n,r]=l.useState(0),a=[...UC,t?GC:KC],o=a[n],i=n===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:u=>{u.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(Mt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:a.map((u,c)=>s.jsx("div",{style:{width:c===n?24:8,height:8,borderRadius:4,background:c===n?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},c))}),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():r(u=>u+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 VC({hasExtensions:e,ideName:t,activeChatTab:n,extensionTabs:r,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)] ${n==="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}),r.map(o=>{const i=n===o.tabKey,u=o.status==="waiting_approval",c=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:u?"var(--status-warning)":c?"var(--accent-primary)":"var(--text-muted)",boxShadow:c?"0 0 6px var(--accent-primary)":"none"}}),o.title,u&&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 qC({ideData:e,allIdes:t,connectionStates:n,ideName:r,preferredTabKey:a}){const[o,i]=l.useState(()=>a||"native"),u=l.useMemo(()=>yp(t),[t]),c=l.useMemo(()=>e?Vi(e,{machineNames:u,connectionStates:n,defaultConnectionState:"new"}):[],[e,u,n]),p=l.useMemo(()=>c.find(f=>f.streamSource==="native"),[c]),d=l.useMemo(()=>c.filter(f=>f.streamSource==="agent-stream"),[c]),m=l.useMemo(()=>e?cs(c,e.id):null,[c,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"&&(d.some(y=>y.tabKey===o)||i(((f=d[0])==null?void 0:f.tabKey)||"native"))},[o,d]),l.useEffect(()=>{o==="native"&&(p||d[0]&&i(d[0].tabKey))},[o,p,d]);const h=l.useMemo(()=>o==="native"&&p?p:d.find(f=>f.tabKey===o)||m||p||d[0],[o,p,m,d]),g=l.useMemo(()=>d.map(f=>({tabKey:f.tabKey,title:lp(f)||r,status:f.status})),[d,r]),v=l.useCallback(f=>{if(f)return c.find(y=>Jo(y,{sessionId:f,routeId:f,tabKey:f,providerSessionId:f}))},[c]);return{activeChatTab:o,setActiveChatTab:i,activeConv:h,conversations:c,extensionTabs:g,hasExtensions:g.length>0,resolveConversationByTarget:v}}function YC({activeConv:e,ideEntry:t,ides:n,connectionStates:r,actionLogs:a,sendDaemonCommand:o,setActionLogs:i,isStandalone:u,userName:c,onOpenHistory:p,onConversationChange:d,onClose:m}){const[h,g]=l.useState("split"),[v,f]=l.useState(()=>Ts(e)?"native":e.tabKey),y=l.useRef(null),j=l.useMemo(()=>t||n.find(_=>_.id===e.routeId),[e.routeId,t,n]),x=l.useMemo(()=>$t((j==null?void 0:j.type)||""),[j==null?void 0:j.type]),{conversations:w,extensionTabs:N,hasExtensions:k}=qC({ideData:j,allIdes:n,connectionStates:r,ideName:x||"IDE",preferredTabKey:Ts(e)?void 0:e.tabKey}),b=l.useMemo(()=>j?cs(w,j.id):null,[j,w]);l.useEffect(()=>{const _=y.current,K={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(y.current=K,!(_&&_.routeId===K.routeId&&_.tabKey===K.tabKey&&_.streamSource===K.streamSource)){if(Ts(e)){f("native");return}f(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),l.useEffect(()=>{if(v==="native"){if(w.some(_=>_.streamSource==="native"))return;(b==null?void 0:b.streamSource)==="agent-stream"&&f(b.tabKey);return}if(!w.some(_=>_.tabKey===v)){if((b==null?void 0:b.streamSource)==="agent-stream"){f(b.tabKey);return}f("native")}},[w,v,b]);const C=l.useMemo(()=>v==="native"?w.find(_=>_.streamSource==="native")||e:w.find(_=>_.tabKey===v)||e,[e,w,v]),S=Dp(C),M=l.useMemo(()=>S.status||S.modalMessage||S.modalButtons?{...C,...S.status?{status:S.status}:{},...S.modalMessage!==void 0?{modalMessage:S.modalMessage}:{},...S.modalButtons!==void 0?{modalButtons:S.modalButtons}:{}}:C,[C,S]),A=en(M),T=Pa({sendDaemonCommand:o,activeConv:M,setActionLogs:i,isStandalone:u}),{connScreenshot:L,screenshotUsage:P,handleRemoteAction:B}=dh({doId:A,targetSessionId:Bu(M),connState:M.connectionState||"new",viewMode:h}),z=l.useMemo(()=>a.filter(_=>_.routeId===M.tabKey),[a,M.tabKey]);l.useEffect(()=>{d==null||d(M)},[M,d]),l.useEffect(()=>{const _=K=>{K.key==="Escape"&&m()};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[m]);const R=l.useCallback(_=>{_.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:R,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(us,{size:16})}),s.jsx("span",{className:"truncate",children:Oi(C)||"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(_=>{const K=h===_;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${K?"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(_),title:_==="split"?"Split view":"Remote only",children:_==="split"?s.jsx(Ef,{size:15}):s.jsx(us,{size:15})},_)})}),s.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),s.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>p(C),title:"Chat History",children:[s.jsx(Mi,{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(VC,{hasExtensions:k,ideName:x||"IDE",activeChatTab:v,extensionTabs:N,onSelectTab:f}),s.jsx(pu,{activeConv:M,onModalButton:T.handleModalButton}),s.jsx(ri,{activeConv:M,ideEntry:j,showMetaChips:!1,handleSendChat:T.handleSendChat,handleForceSendChat:T.handleForceSendChat,isSendingChat:T.isSendingChat,sendFeedbackMessage:T.sendFeedbackMessage,handleFocusAgent:T.handleFocusAgent,isFocusingAgent:T.isFocusingAgent,actionLogs:z,userName:c})]}),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:M.connectionState||"new",connScreenshot:L,screenshotUsage:P,transportType:M.transport,onAction:B})})]})]})})}function JC({activeConv:e,canSaveAndStop:t=!1,onCancel:n,onStopNow:r,onSaveAndStop:a}){const{t:o}=Xe(),i=L0(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:n,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:r,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:n,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:o("common.cancel")})]})]})]})}function XC({historyModal:e,remoteDialog:t,cliStopDialog:n,connectionBanner:r,toastOverlay:a,onboarding:o,interactivePrompt:i}){var u;return s.jsxs(s.Fragment,{children:[s.jsx(q0,{wsStatus:r.wsStatus,showReconnected:r.showReconnected,loginUrl:r.loginUrl,onReconnect:r.onReconnect}),e.open&&e.targetConv&&s.jsx(xp,{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(YC,{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}),n.open&&n.targetConv&&(ct(n.targetConv)||lt(n.targetConv))&&s.jsx(JC,{activeConv:n.targetConv,canSaveAndStop:ct(n.targetConv)&&!lt(n.targetConv)&&!!((u=n.targetConv.resume)!=null&&u.supported),onCancel:n.onCancel,onStopNow:n.onStopNow,onSaveAndStop:n.onSaveAndStop}),s.jsx(bp,{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(zC,{onClose:o.onClose,standalone:o.standalone})]})}function QC({daemons:e,targetVersion:t,required:n=!1,upgradingDaemons:r,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:n?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:n?"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:n?"var(--status-danger)":"var(--status-warning)"},children:s.jsx(ja,{size:14})}),s.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[s.jsxs("span",{children:[n?"Daemon update required":"Update available",t?s.jsxs(s.Fragment,{children:[": ",s.jsxs("strong",{children:["v",t]})]}):null]}),e.map(i=>{const u=ts(i,{fallbackId:i.id}),c=r[i.id],p=i.version||i.daemonVersion||"unknown",d=i.versionUpdateRequired===!0,h=Wp(i)==="preview"?"Update to preview":d?"Update now":"Upgrade";return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${d?"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:u}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",p]}),d&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),c==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:d?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):c==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):c==="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:d?"var(--status-danger)":"var(--status-warning)",background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${d?"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)})]}),!n&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:o,title:"Dismiss",children:s.jsx(Mt,{size:16})})]})}function ZC(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function e2(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 t2(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>e2(t)).map(t=>t.id)}}function s2(){var yl,vl,wl,kl;const{sendCommand:e}=yt(),t=In(),n=Pp(),r=ki(),a=hr(),[o,i]=Hm(),u=o.get("activeTab"),c=((yl=r.state)==null?void 0:yl.openRemoteForTabKey)||null,p=((vl=r.state)==null?void 0:vl.openMachineId)||null,d=((wl=r.state)==null?void 0:wl.mobileSection)||null,m=np(),h=m.ides||[],g=m.initialLoaded??!0,{updateRouteChats:v,setToasts:f}=m,[y,j]=l.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),x=m.toasts||[],w=m.wsStatus||"connected",N=m.isConnected??!0,k=m.connectionStates||{},b=m.showReconnected||!1,{layoutProfile:C,groupAssignments:S,updateGroupAssignments:M,focusedGroup:A,updateFocusedGroup:T,focusGroup:L,groupActiveTabIds:P,updateGroupActiveTabIds:B,setGroupActiveTab:z,groupTabOrders:R,updateGroupTabOrders:_,setGroupTabOrder:K,groupSizes:E,updateGroupSizes:D,isMobile:$,hasHydratedStoredLayout:I,hydrateStoredLayout:G,focusConversationTab:Y}=tj(),[Z,q]=l.useState(()=>Xi());l.useEffect(()=>ck(q),[]);const ne=l.useMemo(()=>ZC({isMobile:$,mobileViewMode:Z}),[$,Z]),[ue,ae]=l.useState([]),[O,se]=l.useState({}),[X,oe]=l.useState({});mr("Dashboard",{ideCount:h.length,toastCount:x.length,focusedGroup:A,groupCount:Object.keys(S).length,actionLogCount:ue.length});const Se=l.useMemo(()=>h.filter(at=>at.type==="adhdev-daemon").sort(_i),[h]),ke=!!Se[0];l.useEffect(()=>{const{metadataDaemonIds:at,runtimeDaemonIds:Ut}=t2(Se);for(const Pn of at)t(Pn,{minFreshMs:3e4}).catch(()=>{});for(const Pn of Ut)n(Pn,{minFreshMs:3e4}).catch(()=>{})},[t,n,Se]);const me=l.useMemo(()=>Mk(h,O),[h,O]),{conversations:U,visibleConversations:W,visibleTabKeys:Q,resolveConversationBySessionId:V,resolveConversationByTarget:fe}=Hk({ides:me,connectionStates:k,clearedTabs:X}),ce=l.useMemo(()=>new Map(U.map(at=>[at.tabKey,at])),[U]);a0(W,ne);const F=l.useMemo(()=>uu(h),[h]),le=th(F,e,l.useCallback(at=>on(f,`⚠️ ${at}`),[f])),{notifications:je,unreadCount:de}=bj({conversations:U,liveSessionInboxState:F}),{handleMarkDashboardNotificationRead:H,handleMarkDashboardNotificationUnread:be,handleDeleteDashboardNotification:Ne}=gj({notifications:je,sendDaemonCommand:e}),{containerRef:Ce,normalizedGroupAssignments:$e,numGroups:Qe,isSplitMode:dt,groupedConvs:it,moveTabToGroup:he,closeGroup:Ee,handleResizeStart:Fe,splitTabRelative:Ie}=lj({groupAssignments:S,updateGroupAssignments:M,updateFocusedGroup:T,updateGroupActiveTabIds:B,updateGroupTabOrders:_,groupSizes:E,updateGroupSizes:D,isMobile:$,visibleConversations:W,visibleTabKeys:Q}),{activeConv:ve,openDesktopConversation:Oe,requestScrollToBottom:ut,scrollToBottomRequest:ot,setDesktopActiveTab:pt}=Tj({isMobile:$,conversations:U,visibleConversations:W,groupActiveTabIds:P,focusedGroup:A,groupedConvs:it,setSearchParams:i});Lj({activeConv:ve,isMobile:$,liveSessionInboxState:F,sendDaemonCommand:e});const{requestedDesktopTabKey:J,requestedMobileTabKey:te,consumeRequestedActiveTab:ie}=Ok({isMobile:$,urlActiveTab:u,resolveConversationBySessionId:V,setSearchParams:i}),{remoteDialogConv:pe,remoteDialogIdeEntry:ge,remoteDialogActiveConv:Ae,setRemoteDialogActiveConv:De,openRemoteDialog:Me,closeRemoteDialog:Be,cliStopDialogOpen:We,cliStopTargetConv:Ze,requestCliStop:_e,cancelCliStop:Ue,confirmCliStop:et}=Ej({isMobile:$,location:r,navigate:a,requestedRemoteTabTarget:c,requestedDesktopTabKey:J,conversations:U,ides:h,resolveConversationByTarget:fe,activeConv:ve,sendDaemonCommand:e}),{historyModalOpen:ee,openHistoryModal:xe,closeHistoryModal:we,historyTargetConv:Ge,isSavedSessionHistoryTarget:He,isHistoryCreatingChat:tt,isHistoryRefreshingHistory:ze,handleHistorySwitchSession:qe,handleHistoryNewChat:At,handleHistoryRefresh:Ot,savedHistorySessions:ss,savedHistoryFilters:Te,setSavedHistoryFilters:Je,missingWorkspaceResumePath:Pt,isSavedHistoryLoading:It,resumingSavedHistorySessionId:Vt,handleRefreshSavedHistory:qt,handleResumeSavedHistorySession:Yt}=Rj({activeConv:ve,remoteDialogConv:pe,remoteDialogActiveConv:Ae,ides:h,sendDaemonCommand:e,updateRouteChats:v,setToasts:f,setClearedTabs:oe,setSearchParams:i}),gs=l.useMemo(()=>W,[W]),Le=$&&Z==="chat",rt=l.useMemo(()=>U.filter(at=>Ps(at,F).surfaceHidden),[U,F]),Nt=l.useCallback(at=>{const Ut=new URLSearchParams(o);Ut.set("activeTab",at),i(Ut,{replace:!0})},[o,i]),{trackPendingLaunch:Wt}=Cj({ides:h,conversations:U,onOpenSession:Nt}),{handleBrowseMachineDirectory:re,handleSaveMachineWorkspace:Ke,handleLaunchMachineIde:Re,handleLaunchMachineProvider:vt,handleListMachineMeshes:Jt,handleLaunchMeshCoordinator:Tn,handleListMachineSavedSessions:Oa,setActiveCliViewMode:ys}=Mj({sendDaemonCommand:e,trackPendingLaunch:Wt,onOpenSession:Nt,activeConv:ve,ides:h,setCliViewModeOverrides:se});Ik({visibleConversations:W,clearedTabs:X,setClearedTabs:oe,setActionLogs:ae,isConversationMuted:le.isMuted}),Wk({ides:h,sendDaemonCommand:e,setToasts:f,resolveConversationByTarget:fe});const rm=Lp(),{isRefreshingHistory:am,handleRefreshHistory:om}=Op({sendDaemonCommand:e,activeConv:ve,chats:(kl=h.find(at=>at.id===(ve==null?void 0:ve.routeId)))==null?void 0:kl.chats,updateRouteChats:v,setToasts:f,setClearedTabs:oe});nj({urlActiveTab:$&&!Le?u:null,conversations:U,resolveConversationBySessionId:V,normalizedGroupAssignments:$e,hasHydratedStoredLayout:$&&!Le?I:!0,hydrateStoredLayout:$&&!Le?G:()=>{},focusConversationTab:Y,setSearchParams:i,historyModalOpen:ee,activeConv:ve,isRefreshingHistory:am,ides:h,handleRefreshHistory:om});const im=l.useMemo(()=>!ve||!ct(ve)||lt(ve)?null:An(ve),[ve]),{versionMismatchDaemons:lm,hasRequiredVersionDaemons:bl,targetVersion:cm,versionBannerDismissed:dm,setVersionBannerDismissed:um,upgradingDaemons:pm,handleBannerUpgrade:hm}=dj({ides:h,sendDaemonCommand:e}),gl=l.useCallback(at=>{le.setHidden(at,!1),Oe(at)},[Oe,le]),mm=l.useCallback(()=>{for(const at of rt)le.setHidden(at,!1)},[rt,le]),fm=l.useCallback(at=>{le.setHidden(at,!0)},[le]),xm=l.useCallback(at=>{le.toggleHidden(at)},[le]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[(!dm||bl)&&s.jsx(QC,{daemons:lm,targetVersion:cm,required:bl,upgradingDaemons:pm,onUpgrade:hm,onDismiss:()=>um(!0)}),s.jsx(WC,{showMobileChatMode:Le,isMobile:$,activeConv:ve,wsStatus:w,isConnected:N,onOpenHistory:at=>{at&&De(at),xe()},onOpenRemote:Me,onStopCli:_e,activeCliViewMode:im,onSetActiveCliViewMode:ys,mobileChatConversations:gs,ides:h,actionLogs:ue,sendDaemonCommand:e,setActionLogs:ae,setCliViewModeOverrides:se,isStandalone:ke,initialDataLoaded:g,userName:m.userName,requestedMobileTabKey:te,onRequestedMobileTabConsumed:ie,requestedMachineId:p,onRequestedMachineConsumed:()=>{a(r.pathname+r.search,{replace:!0,state:null})},requestedMobileSection:d,onRequestedMobileSectionConsumed:()=>{a(r.pathname+r.search,{replace:!0,state:null})},containerRef:Ce,isSplitMode:dt,numGroups:Qe,groupSizes:E,groupedConvs:it,clearedTabs:X,focusedGroup:A,focusGroup:L,moveTabToGroup:he,splitTabRelative:Ie,closeGroup:Ee,handleResizeStart:Fe,groupActiveTabIds:P,setGroupActiveTab:z,groupTabOrders:R,setGroupTabOrder:K,toggleHiddenTab:at=>{const Ut=ce.get(at);Ut&&xm(Ut)},visibleConversations:W,hiddenConversations:rt,requestedDesktopTabKey:J,onRequestedDesktopTabConsumed:ie,onDesktopActiveTabChange:pt,onRequestScrollToBottom:ut,onHideConversation:fm,onShowHiddenConversation:gl,onShowAllHiddenConversations:mm,scrollToBottomRequest:ot,machineEntries:Se,layoutProfile:C,onBrowseMachineDirectory:re,onSaveMachineWorkspace:Ke,onLaunchMachineIde:Re,onLaunchMachineProvider:vt,onListMachineMeshes:Jt,onLaunchMeshCoordinator:Tn,onListMachineSavedSessions:Oa,notifications:je,notificationUnreadCount:de,liveSessionInboxState:F,onMarkNotificationRead:H,onMarkNotificationUnread:be,onDeleteNotification:Ne}),s.jsx("style",{children:`
90
- body { overflow: hidden; overscroll-behavior: none; }
91
- `}),s.jsx(XC,{historyModal:{open:ee,targetConv:Ge,ides:h,isCreatingChat:tt,isRefreshingHistory:He?!1:ze,savedSessions:ss,savedHistoryFilters:Te,missingWorkspaceResumePath:Pt||null,onSavedHistoryFiltersChange:Je,isSavedSessionsLoading:It,isResumingSavedSessionId:Vt,onClose:we,onNewChat:At,onSwitchSession:qe,onRefreshHistory:He?qt:Ot,onResumeSavedSession:Yt},remoteDialog:{conversation:pe,ideEntry:ge,ides:h,connectionStates:k,actionLogs:ue,sendDaemonCommand:e,setActionLogs:ae,isStandalone:ke,userName:m.userName,onOpenHistory:at=>{at&&De(at),xe()},onConversationChange:De,onClose:Be},cliStopDialog:{open:We,targetConv:Ze,onCancel:Ue,onStopNow:async()=>{await et("hard")},onSaveAndStop:async()=>{await et("save")}},connectionBanner:{wsStatus:w,showReconnected:b,loginUrl:m.connectionLoginUrl,onReconnect:m.retryServerConnection},toastOverlay:{toasts:x,onDismiss:at=>f(Ut=>Ut.filter(Pn=>Pn.id!==at)),onClick:at=>{if(at.targetKey){const Ut=fe(at.targetKey);Ut&&(Y(Ut.tabKey,$e),gl(Ut),ut(Ut.tabKey,"toast-open"))}}},onboarding:{open:y,standalone:ke,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}j(!1)}},interactivePrompt:rm})]})}function n2({machineId:e,registeredMachineId:t,sendDaemonCommand:n,onNicknameSynced:r,logsEndRef:a}){const{launchCli:o}=wa(),[i,u]=l.useState([]),[c,p]=l.useState(null),[d,m]=l.useState(null),[h,g]=l.useState(!1),[v,f]=l.useState(null),[y,j]=l.useState(!1),[x,w]=l.useState(""),N=l.useRef(null),k=l.useCallback(D=>{N.current=D},[]),b=l.useCallback((D,$,I=!1)=>{u(G=>[...G.slice(-100),{timestamp:Date.now(),level:D,message:$}]),setTimeout(()=>{var G;return(G=a.current)==null?void 0:G.scrollIntoView({behavior:"smooth"})},100),I&&ht.showToast($,D==="error"||D==="warn"?"warning":"success")},[a]),C=l.useCallback(D=>{const $=D instanceof Error?D.message:String(D||"");return $.includes("P2P command timeout")||$.includes("P2P not connected")||$.includes("P2P not available")},[]),S=l.useCallback(async(D,$)=>{var I;if(!e||c)return!1;p(D),b("info",`Launching ${$t(D)}${$!=null&&$.workspace?` in ${$.workspace}`:""}...`);try{const G={ideType:D,enableCdp:!0};(I=$==null?void 0:$.workspace)!=null&&I.trim()?G.workspace=$.workspace.trim():$!=null&&$.useDefaultWorkspace&&(G.useDefaultWorkspace=!0);const Y=await n(e,"launch_ide",G);return b(Y!=null&&Y.success?"info":"error",Y!=null&&Y.success?`${$t(D)} launched`:`Failed: ${Y==null?void 0:Y.error}`,!0),!!(Y!=null&&Y.success)}catch(G){return b("error",`Launch error: ${G.message}`,!0),!1}finally{p(null)}},[e,c,b,n]),M=l.useCallback(async D=>{if(!e)return{success:!1};const{cliType:$,dir:I,workspaceId:G,useDefaultWorkspace:Y,useHome:Z,argsStr:q,model:ne,resumeSessionId:ue}=D;if(!$)return b("warn","Select a CLI or ACP provider first",!0),{success:!1};const ae=q?q.split(/\s+/).filter(Boolean):void 0,O=(I==null?void 0:I.trim())||(G?"(saved id)":Y?"(default workspace)":Z?"(home)":"");b("info",`Launching ${$}${O?` in ${O}`:""}${ne?` (model: ${ne})`:""}...`),m($);try{const se={cliType:$,cliArgs:ae,initialModel:ne||void 0};I!=null&&I.trim()?se.dir=I.trim():G?se.workspaceId=G:Y?se.useDefaultWorkspace=!0:Z&&(se.useHome=!0),ue&&(se.resumeSessionId=ue);const X=await o(e,se),oe=(X==null?void 0:X.result)||X;return X!=null&&X.success?(b("info",`${$} 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: ${(X==null?void 0:X.error)||(oe==null?void 0:oe.error)}`,!0),(X==null?void 0:X.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&f({cliType:$,argsStr:q,model:ne}),{success:!1,sessionId:oe==null?void 0:oe.sessionId})}catch(se){return C(se)?(b("warn",`${$} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(b("error",`Launch error: ${se.message}`,!0),{success:!1})}finally{m(null)}},[e,b,C,n]),A=l.useCallback(async(D,$,I,G)=>e?D?$.trim()?M({cliType:D,dir:$,argsStr:I,model:G}):(f({cliType:D,argsStr:I,model:G}),{success:!1}):(b("warn","Select a provider",!0),{success:!1}):{success:!1},[e,b,M]),T=l.useCallback(async(D,$,I)=>{if(e&&window.confirm(`Stop ${D}?
92
- This will terminate the process.`))try{const G=await n(e,"stop_cli",{cliType:D,dir:$,targetSessionId:I});G!=null&&G.success?b("info",`${D} stopped`,!0):b("error",`Stop failed: ${(G==null?void 0:G.error)||"Unknown error"}`,!0)}catch(G){b("error",`Stop failed: ${G.message}`,!0)}},[e,b,n]),L=l.useCallback(async D=>{try{await n(D.daemonId,"restart_ide",{ideType:D.type}),b("info",`${$t(D.type)} restart initiated`,!0)}catch($){b("error",`Restart failed: ${$.message}`,!0)}},[b,n]),P=l.useCallback(async D=>{if(window.confirm(`Stop ${$t(D.type)}?
93
- This will disconnect CDP and optionally kill the process.`))try{const $=await n(D.daemonId,"stop_ide",{ideType:D.type,killProcess:!0});$!=null&&$.success?b("info",`${$t(D.type)} stopped`,!0):b("error",`Stop failed: ${($==null?void 0:$.error)||"Unknown error"}`,!0)}catch($){b("error",`Stop failed: ${$.message}`,!0)}},[b,n]),B=l.useCallback(async()=>{if(e)try{const D=await n(e,"detect_ides",{});b("info",`Found ${((D==null?void 0:D.result)||[]).length} IDE(s)`,!0)}catch(D){b("error",`Detection failed: ${D.message}`,!0)}},[e,b,n]),z=l.useCallback(async D=>{if(!e||!D.trim())return!1;g(!0);try{const $=await n(e,"workspace_add",{path:D.trim()});return $!=null&&$.success?(b("info",`Workspace added: ${D.trim()}`),!0):(b("error",($==null?void 0:$.error)||"workspace_add failed"),!1)}catch($){return b("error",$.message),!1}finally{g(!1)}},[e,b,n]),R=l.useCallback(async D=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){g(!0);try{const $=await n(e,"workspace_remove",{id:D});$!=null&&$.success?b("info","Workspace removed",!0):b("error",($==null?void 0:$.error)||"workspace_remove failed",!0)}catch($){b("error",$.message,!0)}finally{g(!1)}}},[e,b,n]),_=l.useCallback(async D=>{var $;if(e){g(!0);try{const I=await n(e,"workspace_set_default",D===null?{clear:!0}:{id:D});if(I!=null&&I.success){b("info",D?"Default workspace updated":"Default workspace cleared",!0);const G=typeof I.defaultWorkspacePath=="string"?I.defaultWorkspacePath:"";G&&(($=N.current)==null||$.call(N,G))}else b("error",(I==null?void 0:I.error)||"workspace_set_default failed",!0)}catch(I){b("error",I.message,!0)}finally{g(!1)}}},[e,b,n]),K=l.useCallback(async D=>{var I;if(!e||!D.trim())return;const $=D.trim();g(!0);try{const G=await n(e,"workspace_set_default",{path:$});G!=null&&G.success?(b("info","Default workspace set from history"),(I=N.current)==null||I.call(N,$)):b("error",(G==null?void 0:G.error)||"Could not set default (path missing on disk?)")}catch(G){b("error",G.message)}finally{g(!1)}},[e,b,n]),E=l.useCallback(async()=>{if(e)try{if(await n(e,"set_machine_nickname",{nickname:x}),r)try{await r({machineRuntimeId:e,registeredMachineId:t,nickname:x})}catch(D){b("warn",`Live nickname updated, but account sync failed: ${D.message}`)}b("info",`Nickname set to "${x||"(cleared)"}"`),j(!1)}catch(D){b("error",`Failed: ${D.message}`)}},[e,x,t,b,r,n]);return{logs:i,launchingIde:c,launchingAgentType:d,workspaceBusy:h,launchPick:v,setLaunchPick:f,editingNickname:y,setEditingNickname:j,nicknameInput:x,setNicknameInput:w,addLog:b,handleLaunchIde:S,runLaunchCliCore:M,handleLaunchCli:A,handleStopCli:T,handleRestartIde:L,handleStopIde:P,handleDetectIdes:B,handleWorkspaceAdd:z,handleWorkspaceRemove:R,handleWorkspaceSetDefault:_,handleWorkspaceResumePath:K,handleSaveNickname:E,setOnDefaultWorkspaceChanged:k}}function r2({machine:e,ideSessions:t,cliSessions:n,acpSessions:r}){var c;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,u=((c=e.loadavg)==null?void 0:c[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(kr,{icon:s.jsx(Jd,{size:16}),label:"Uptime",value:typeof e.uptime=="number"?Eg(e.uptime):"Waiting…"}),s.jsx(kr,{icon:s.jsx(us,{size:16}),label:"IDEs",value:`${t.length}`}),s.jsx(kr,{icon:s.jsx(Ii,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(kr,{icon:s.jsx(Ff,{size:16}),label:"ACPs",value:`${r.length}`})]}),s.jsxs(js,{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($l,{value:a?Math.min(Math.round(u/e.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:a?`${u.toFixed(2)} avg / ${e.cpus} cores`:"Polled from machine page"}),s.jsx($l,{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 a2(e){if(!e||typeof e!="object")return null;const t=e,n=t.result&&typeof t.result=="object"?t.result:t;return!n.settings||typeof n.settings!="object"?null:{settings:n.settings,values:n.values&&typeof n.values=="object"?n.values:{}}}function o2(e,t,n){const r=[];for(const[a,o]of Object.entries(e.settings)){const i=n!=null&&n.filterSchema?n.filterSchema(o):o;if(i.length===0)continue;const u=t.find(c=>c.type===a);r.push({type:a,displayName:(u==null?void 0:u.displayName)||a,icon:(u==null?void 0:u.icon)||"",category:(u==null?void 0:u.category)||"unknown",schema:i,values:e.values[a]||{}})}return r}function Io(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 md(e){if(!e||typeof e!="object")return null;if(Io(e))return e;const t=e,n=t.result;return Io(n)?n:Io(t.sourceConfig)?t.sourceConfig:null}function i2(e){const t=e.trim();return t||null}function l2({machineId:e,providers:t,sendDaemonCommand:n,onClose:r,onCreated:a}){var k;const o=t.filter(b=>b.category==="ide"),[i,u]=l.useState(((k=o[0])==null?void 0:k.type)||""),[c,p]=l.useState(""),[d,m]=l.useState(""),[h,g]=l.useState(!1),[v,f]=l.useState(""),[y,j]=l.useState(!1),x=b=>{const C=b.toLowerCase().replace(/[^a-z0-9-]/g,"");p(C),(!d||d===w(c))&&m(w(C))},w=b=>b.split("-").map(C=>C.charAt(0).toUpperCase()+C.slice(1)).join(" "),N=async()=>{if(!(!c||!d||!i)){g(!0),f("");try{const b=await n(e,"provider_clone",{type:c,name:d,category:"ide",location:"user",cloneFrom:i});b!=null&&b.success||b!=null&&b.created?(j(!0),a==null||a(c)):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:r,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:y?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:c})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",c,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",c]})," 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:()=>u(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:c,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/",c||"...","/"]})]})]}),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:d,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"})]}),v&&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:v})]})}),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:y?s.jsx("button",{onClick:r,className:"machine-btn",children:"Close"}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:r,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:N,disabled:!c||!d||h,className:"machine-btn",style:{background:c&&d?"rgba(34,197,94,0.12)":void 0,borderColor:c&&d?"rgba(34,197,94,0.3)":void 0,color:c&&d?"#86efac":void 0,opacity:!c||!d||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"},c2={"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 d2({trust:e,sourceName:t,description:n}){const r=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 ${c2[e]}`,title:n,children:r})}function u2(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 p2={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"},h2={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",n=e.message||e.path||e.command||"";return n?`${t} — ${n}`:t}function m2(e){return e==="cli"||e==="acp"}function f2({prov:e,providerInfo:t,savingKey:n,onSetSetting:r,onEnableToggle:a,onDetect:o,onResetCommand:i}){const[u,c]=l.useState(!1),p=(t==null?void 0:t.enabled)===!0||e.values.enabled===!0,d=t==null?void 0:t.machineStatus,m=p&&d==="disabled"?"enabled_unchecked":d||(p?"enabled_unchecked":"disabled"),h=m2(e.category);return s.jsxs(js,{padding:"none",children:[s.jsxs("button",{onClick:()=>c(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 ${h2[e.category]??"border-border-subtle text-text-muted"}`,children:e.category.toUpperCase()}),(t==null?void 0:t.trust)&&s.jsx(d2,{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:p2[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:n===`${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:u?"▾":"▸"})]})]}),u&&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 v=Object.entries(g).map(([f,y])=>({k:f,href:u2(y)})).filter(f=>f.href!==null);return v.length===0?null:s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Links:"})," ",v.map(({k:f,href:y})=>s.jsx("a",{href:y,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,n===`${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 r(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:v=>{const f=parseInt(v.target.value)||0;g.min!==void 0&&f<g.min||g.max!==void 0&&f>g.max||r(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:v=>void r(e.type,g.key,v.target.value),className:"machine-input text-[11px]",children:g.options.map(v=>s.jsx("option",{value:v,children:v},v))}):s.jsx("input",{type:"text",defaultValue:String(e.values[g.key]??g.default??""),onBlur:v=>void r(e.type,g.key,v.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||n===`${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 Br(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function x2({machineId:e,sendDaemonCommand:t,onChange:n}){const[r,a]=l.useState([]),[o,i]=l.useState([]),[u,c]=l.useState(!1),[p,d]=l.useState(null),[m,h]=l.useState(!1),[g,v]=l.useState(""),[f,y]=l.useState("main"),[j,x]=l.useState(""),[w,N]=l.useState(!1),[k,b]=l.useState(null),[C,S]=l.useState(null),M=l.useCallback(async()=>{if(e){c(!0),d(null);try{const P=Br(await t(e,"list_provider_sources",{}));if(!(P!=null&&P.success)){d((P==null?void 0:P.error)||"Failed to load sources");return}a(P.sources||[]),i(P.conflicts||[])}catch(P){d((P==null?void 0:P.message)||String(P))}finally{c(!1)}}},[e,t]);l.useEffect(()=>{M()},[M]);const A=async()=>{if(g.trim()){N(!0),d(null);try{const P=Br(await t(e,"add_provider_source",{url:g.trim(),ref:f.trim()||"main",...j.trim()?{name:j.trim()}:{}}));P!=null&&P.success?(h(!1),v(""),y("main"),x(""),await M(),n==null||n()):d((P==null?void 0:P.error)||"Failed to add source")}catch(P){d((P==null?void 0:P.message)||String(P))}finally{N(!1)}}},T=async P=>{if(confirm(`Remove provider source ${P}? This deletes the cloned manifests and clears any active-source entries that pointed here.`)){b(P),d(null);try{const B=Br(await t(e,"remove_provider_source",{name:P}));B!=null&&B.success?(await M(),n==null||n()):d((B==null?void 0:B.error)||"Failed to remove source")}catch(B){d((B==null?void 0:B.message)||String(B))}finally{b(null)}}},L=async(P,B)=>{S(`${P}:${B}`),d(null);try{const z=Br(await t(e,"set_active_provider_source",{type:P,sourceName:B}));z!=null&&z.success?(await M(),n==null||n()):d((z==null?void 0:z.error)||"Failed to set active source")}catch(z){d((z==null?void 0:z.message)||String(z))}finally{S(null)}};return s.jsxs(js,{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 M(),disabled:u,className:"machine-btn text-[10px]",children:[u?"⏳":"↻"," 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}),r.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:r.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 T(P.name),disabled:k===P.name,className:"machine-btn text-[10px] text-red-400 hover:bg-red-500/[0.10]",children:k===P.name?"…":"Remove"})]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:Object.entries(P.providers).map(([B,z])=>s.jsxs("span",{className:"mr-3",children:[s.jsxs("span",{className:"text-text-secondary",children:[B,":"]})," ",z.length]},B))})]},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(B=>s.jsxs("button",{type:"button",onClick:()=>void L(P.type,B),disabled:C===`${P.type}:${B}`,className:`text-[10px] px-2 py-0.5 rounded border ${P.active===B?"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===B?"Active":`Switch active to ${B}`,children:[P.active===B?"● ":"",B]},B))})]},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=>v(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=>y(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:j,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 A(),disabled:w||!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:w?"Cloning…":"Clone + register"})]})]})]})}function b2({machineId:e,providers:t,sendDaemonCommand:n}){var _;const[r,a]=l.useState([]),[o,i]=l.useState(!1),[u,c]=l.useState(null),[p,d]=l.useState("all"),[m,h]=l.useState(!1),[g,v]=l.useState(!1),[f,y]=l.useState(!1),[j,x]=l.useState(null),[w,N]=l.useState("normal"),[k,b]=l.useState(""),[C,S]=l.useState(!1),M=l.useCallback(async()=>{if(e)try{const K=await n(e,"get_provider_source_config",{}),E=md(K);E&&(x(E),N(E.sourceMode),b(E.explicitProviderDir||""))}catch{}},[e,n]),A=l.useCallback(async()=>{if(e){i(!0);try{const K=await n(e,"get_provider_settings",{}),E=a2(K);if(E){const D=o2(E,t,{filterSchema:$=>$.filter(I=>I.key!=="enabled")});D.sort(($,I)=>$.category.localeCompare(I.category)||$.displayName.localeCompare(I.displayName)),a(D)}}catch{}i(!1)}},[e,t,n]);l.useEffect(()=>{r.length===0&&A(),j||M()},[]);const T=async(K,E,D)=>{c(`${K}.${E}`),a($=>$.map(I=>I.type===K?{...I,values:{...I.values,[E]:D}}:I));try{const $=await n(e,"set_provider_setting",{providerType:K,key:E,value:D});$!=null&&$.success||A()}catch{A()}c(null)},L=async(K,E)=>{await T(K,"enabled",E),await A()},P=async K=>{c(`${K}.detect`);try{await n(e,"detect_provider",{providerType:K})}finally{await A(),c(null)}},B=async K=>{await T(K,"executablePath",""),await T(K,"executableArgs",""),await A()},z=async()=>{S(!0);try{const K=await n(e,"set_provider_source_config",{providerSourceMode:w,providerDir:i2(k)}),E=md(K);E?(x(E),N(E.sourceMode),b(E.explicitProviderDir||"")):await M(),await A()}catch{await M()}S(!1)},R=r.filter(K=>p==="all"||K.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(K=>s.jsx("button",{onClick:()=>d(K),className:`machine-btn text-[10px] px-2 py-0.5 ${p===K?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:K.toUpperCase()},K))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>v(K=>!K),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:A,disabled:o,className:"machine-btn text-[10px]",children:[o?"⏳":"↻"," Refresh"]}),s.jsx("button",{onClick:()=>y(K=>!K),className:"machine-btn text-[10px]",title:"Show source configuration (advanced)",children:"⚙ Advanced"})]})]}),g&&s.jsx(x2,{machineId:e,sendDaemonCommand:n,onChange:()=>{A()}}),f&&s.jsxs(js,{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:M,className:"machine-btn text-[10px]",children:"↻ Refresh"})]}),s.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),s.jsxs("select",{value:w,onChange:K=>N(K.target.value),className:"machine-input text-[11px]",children:[s.jsx("option",{value:"normal",children:"normal"}),s.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),s.jsx("input",{type:"text",value:k,onChange:K=>b(K.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void z(),disabled:C,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:C?"Applying…":"Apply + Reload"})]}),s.jsxs("div",{className:"mt-3 grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"User root:"})," ",(j==null?void 0:j.userDir)||"—"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Upstream root:"})," ",(j==null?void 0:j.upstreamDir)||"—"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Provider roots:"})," ",((_=j==null?void 0:j.providerRoots)==null?void 0:_.join(" → "))||"—"]})]})]}),o&&r.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings…"}):R.length===0?s.jsx(js,{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:R.map(K=>s.jsx(f2,{prov:K,providerInfo:t.find(E=>E.type===K.type),savingKey:u,onSetSetting:T,onEnableToggle:L,onDetect:P,onResetCommand:B},K.type))}),m&&s.jsx(l2,{machineId:e,providers:t,sendDaemonCommand:n,onClose:()=>h(!1),onCreated:()=>{h(!1),A()}})]})}const g2=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function y2({count:e,since:t,category:n}){return{count:e,since:t,...n==="all"?{}:{category:n}}}function v2(e,t){return t==="all"?e:e.filter(n=>n.category===t)}function w2(e){return e.trim().toLowerCase()}function Ba(e,t){const n=w2(t);return n?e.some(r=>String(r??"").toLowerCase().includes(n)):!0}function ml(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Nn(e,t=220){const n=ml(e);return n?n.length>t?`${n.slice(0,t)}…`:n:""}function k2(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(n=>{const r=n;return{timestamp:Number(r.ts)||0,level:r.level||"info",message:`[${String(r.category||"daemon")}] ${String(r.message||"")}`.trim()}}),rawText:""};if(typeof t=="string"){const n=t.trim();return{kind:n?"text":"empty",entries:[],rawText:n}}return{kind:"empty",entries:[],rawText:""}}function j2(e,t){return e.filter(n=>Ba([n.level,n.message],t))}function gd(e){return`${e.timestamp}:${e.level}:${e.message}`}function S2(e,t,n=300){if(t.entries.length>0){const r=new Map;for(const i of e.entries)r.set(gd(i),i);for(const i of t.entries)r.set(gd(i),i);const a=Array.from(r.values()).sort((i,u)=>i.timestamp-u.timestamp).slice(-n),o=a.reduce((i,u)=>Math.max(i,Number(u.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 N2(e,t,n=120){if(t.length===0)return e;const r=new Map;for(const a of e)r.set(a.id,a);for(const a of t)r.set(a.id,a);return Array.from(r.values()).sort((a,o)=>a.ts-o.ts).slice(-n)}function C2(e,t){return e.split(`
94
- `).map(n=>n.trimEnd()).filter(Boolean).filter(n=>Ba([n],t))}function M2(e,t){return e.filter(n=>Ba([n.level,n.category,n.stage,n.interactionId,ml(n.payload)],t))}function A2(e,t){return e.filter(n=>Ba([n.kind,n.topic,n.interactionId,ml(n.payload)],t))}function yd(e){return e==="warn"||e==="error"}function I2({daemonLogs:e,daemonRawLines:t,trace:n,webEvents:r}){return{all:e.length+t.length+n.length+r.length,info:e.filter(a=>a.level!=="debug").length+n.filter(a=>a.level!=="debug").length+r.length,issues:e.filter(a=>yd(a.level)).length+n.filter(a=>yd(a.level)).length}}function T2({daemonLogs:e,daemonRawLines:t,trace:n,webEvents:r}){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
- `)),n.length>0&&a.push(["[trace]",...n.map(o=>`${new Date(o.ts).toISOString()} ${o.level.toUpperCase()} ${o.category}.${o.stage} ${Nn(o.payload,500)}`.trim())].join(`
97
- `)),r.length>0&&a.push(["[browser events]",...r.map(o=>`${new Date(o.ts).toISOString()} ${o.kind}${o.topic?` topic=${o.topic}`:""} ${Nn(o.payload,500)}`.trim())].join(`
98
- `)),a.join(`
99
-
100
- `)}function P2({machineId:e,sendDaemonCommand:t}){const[n,r]=l.useState([]),[a,o]=l.useState("empty"),[i,u]=l.useState(""),[c,p]=l.useState([]),[d,m]=l.useState([]),[h,g]=l.useState(null),[v,f]=l.useState(!0),[y,j]=l.useState("info"),[x,w]=l.useState("all"),[N,k]=l.useState(!0),[b,C]=l.useState(!0),[S,M]=l.useState(""),[A,T]=l.useState(""),[L,P]=l.useState(0),B=l.useRef(0),z=l.useRef(0),R=l.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),_=l.useRef([]),K=l.useCallback(()=>{const Z={entries:[],kind:"empty",rawText:"",lastTs:0};R.current=Z,B.current=0,r([]),u(""),o("empty"),k(!0)},[]),E=l.useCallback(()=>{_.current=[],z.current=0,p([]),C(!0)},[]),D=l.useCallback(Z=>{Z!==y&&(K(),j(Z))},[y,K]),$=l.useCallback(Z=>{w(q=>q===Z?q:Z)},[]),I=l.useCallback(()=>{K(),E(),m([]),g(null),M(""),T(""),xn.clear()},[K,E]),G=l.useCallback(()=>{P(Z=>Z+1)},[]),Y=l.useCallback(async()=>{if(!e)return;const Z=B.current,q=z.current,[ne,ue]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:y,since:Z}),t(e,"get_debug_trace",y2({count:120,since:q,category:x}))]);if(ne.status==="fulfilled"){const ae=ne.value,O=(ae==null?void 0:ae.result)||ae,se=k2(O),X=S2(R.current,se,300);R.current=X,B.current=X.lastTs,k(!1),M((ae==null?void 0:ae.success)===!1?String((ae==null?void 0:ae.error)||"Could not load daemon logs"):""),o(X.kind),u(X.rawText),r(X.entries)}else k(!1),M(ne.reason instanceof Error?ne.reason.message:"Could not load daemon logs");if(ue.status==="fulfilled"){const ae=ue.value,O=(ae==null?void 0:ae.result)||ae;if((ae==null?void 0:ae.success)===!1)T(String((ae==null?void 0:ae.error)||"Could not load daemon trace"));else if(Array.isArray(O==null?void 0:O.trace)){const se=O.trace,X=N2(_.current,se,120),oe=se.reduce((Se,ye)=>Math.max(Se,Number(ye.ts||0)),q);_.current=X,oe>q&&(z.current=oe),T(""),p(X)}else T("");C(!1)}else C(!1),T(ue.reason instanceof Error?ue.reason.message:"Could not load daemon trace");m(xn.list({limit:120})),g(Date.now())},[y,e,t,x]);return l.useEffect(()=>{E()},[E,x]),l.useEffect(()=>{if(!e||(Y(),!v))return;const Z=setInterval(()=>{Y()},3e3);return()=>clearInterval(Z)},[v,Y,e,L]),{daemonLogs:n,daemonLogKind:a,daemonRawText:i,debugTrace:c,webEvents:d,lastUpdatedAt:h,autoRefresh:v,logLevel:y,traceCategory:x,daemonLoading:N,traceLoading:b,daemonFetchError:S,traceFetchError:A,setAutoRefresh:f,setLogLevel:D,setTraceCategory:$,refresh:G,clear:I}}function D2({daemonLoading:e,traceLoading:t,daemonFetchError:n,traceFetchError:r,daemonLogKind:a,daemonLogsCount:o,daemonRawLineCount:i,traceCount:u,webEventCount:c}){return[{id:"daemon_logs",label:"Daemon logs",status:n?"error":e?"loading":o>0||i>0?"ok":"empty",detail:n||(a==="text"?`${i} raw file-fallback line(s)`:`${o} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:r?"error":t?"loading":u>0?"ok":"empty",detail:r||`${u} trace event(s)`},{id:"browser_events",label:"Browser debug events",status:c>0?"ok":"empty",detail:c>0?`${c} local browser event(s)`:"No browser events captured"}]}function vd(e){return e==="warn"||e==="error"}function L2(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 R2(e,t){const n=e.match(/\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z\b/);if(n){const r=Date.parse(n[0]);if(Number.isFinite(r))return r}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 _2(e){const t=Nn(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function E2(e){const t=Nn(e.payload,320),n=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${n} ${t}`:`${e.kind}${n}`}function $2({daemonLogs:e,daemonRawLines:t,trace:n,webEvents:r}){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})}),r.forEach(o=>{a.push({id:`browser-event-${o.id}`,source:"browser_event",ts:Number(o.ts||0),severity:"info",message:E2(o),topic:o.topic,interactionId:o.interactionId,payload:o.payload})}),n.forEach(o=>{a.push({id:`daemon-trace-${o.id}`,source:"daemon_trace",ts:Number(o.ts||0),severity:o.level,message:_2(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:R2(o,i),severity:L2(o),message:o,raw:o})}),a.sort((o,i)=>o.ts!==i.ts?o.ts-i.ts:wd(o.source)-wd(i.source))}function F2(e){return`${e.source}:${e.severity}:${e.message}`}function B2(e){const t=e.filter(r=>vd(r.severity)).sort((r,a)=>a.ts-r.ts),n=new Map;for(const r of e){if(!vd(r.severity))continue;const a=F2(r),o=n.get(a);o?(o.count+=1,o.firstTs=Math.min(o.firstTs,r.ts),o.lastTs=Math.max(o.lastTs,r.ts)):n.set(a,{key:a,source:r.source,severity:r.severity,message:r.message,count:1,firstTs:r.ts,lastTs:r.ts})}return{totalCount:e.length,issueCount:t.length,latestIssue:t[0]||null,repeatedPatterns:Array.from(n.values()).filter(r=>r.count>1).sort((r,a)=>a.count!==r.count?a.count-r.count:a.lastTs-r.lastTs).slice(0,5)}}function H2(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function kd(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",n=e.interactionId?` ix=${e.interactionId}`:"";return`${H2(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${n} ${e.message}`.trim()}function O2({events:e,summary:t,sources:n,maxTimelineEvents:r=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
101
- `)),a.push(["[source status]",...n.map(i=>`${i.label}: ${i.status} - ${i.detail}`)].join(`
102
- `)),t.latestIssue&&a.push(["[latest issue]",kd(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(-r);return a.push(["[timeline]",...o.length>0?o.map(kd):["No diagnostic events captured."]].join(`
105
- `)),a.join(`
106
-
107
- `)}function W2(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function U2(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function K2({daemonLogs:e,daemonRawText:t,daemonLogKind:n,debugTrace:r,webEvents:a,traceCategory:o,quickFilter:i,searchQuery:u,daemonLoading:c,traceLoading:p,daemonFetchError:d,traceFetchError:m}){const h=v2(r,o),g=j2(e,u),v=C2(t,u),f=M2(h,u),y=A2(a,u),j=W2(g,i),x=i==="all"?v:[],w=U2(f,i),N=i==="issues"?[]:y,k=I2({daemonLogs:g,daemonRawLines:v,trace:f,webEvents:y}),b=$2({daemonLogs:j,daemonRawLines:x,trace:w,webEvents:N}),C=B2(b),S=D2({daemonLoading:c,traceLoading:p,daemonFetchError:d,traceFetchError:m,daemonLogKind:n,daemonLogsCount:g.length,daemonRawLineCount:v.length,traceCount:f.length,webEventCount:y.length});return{filteredDaemonLogs:g,filteredDaemonRawLines:v,filteredTraceEntries:f,filteredWebEvents:y,visibleDaemonLogs:j,visibleDaemonRawLines:x,visibleTraceEntries:w,visibleWebEvents:N,quickFilterCounts:k,diagnosticEvents:b,diagnosticsSummary:C,sourceStates:S}}function G2(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Jh(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 z2({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:Jh(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 V2({quickFilter:e,quickFilterCounts:t,searchQuery:n,autoRefresh:r,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:i,onCopyVisible:u,onToggleAutoRefresh:c,onRefresh:p,onClear:d}){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:n,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:u,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:c,className:`machine-btn ${r?"text-green-500 border-green-500/30":""}`,children:r?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:p,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:d,className:"machine-btn",children:"Clear"})]})]})}function q2({logLevel:e,traceCategory:t,onLogLevelChange:n,onTraceCategoryChange:r}){return s.jsx(js,{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:()=>n(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:g2.map(a=>s.jsx("button",{onClick:()=>r(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 Y2({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:n,searchQuery:r,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:i,traceFetchError:u}){var d,m;const c=((d=e.latestIssue)==null?void 0:d.severity)==="error"?"danger":((m=e.latestIssue)==null?void 0:m.severity)==="warn"?"warning":"good",p=i||u?"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:r.trim()?`Filtered by “${r.trim()}”`:"Daemon, trace, and browser signals merged by time"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${To(c)}`,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:Jh(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||u?"Needs attention":o?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",G2(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:n.map(h=>s.jsxs("div",{children:[h.label,": ",h.status]},h.id))})]})]})}function J2({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 X2({streams:e,sectionsOpen:t,setSectionsOpen:n,diagnosticEvents:r,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:i,visibleWebEvents:u,quickFilter:c,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:()=>n(d=>({...d,timeline:!d.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:[r.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)&&r.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&r.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&&r.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),r.map(d=>s.jsx(z2,{event:d},d.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:()=>n(d=>({...d,daemon:!d.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:c==="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((d,m)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:d},`raw-${m}`)),e.daemonLogKind!=="text"&&a.map((d,m)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${bi(d.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(d.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:d.level==="error"?"ERR":d.level==="warn"?"WRN":d.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:d.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:()=>n(d=>({...d,trace:!d.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(d=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${bi(d.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.level.toUpperCase()}),s.jsxs("span",{children:[d.category,".",d.stage]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Nn(d.payload,360)||"No payload"})]},d.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:()=>n(d=>({...d,web:!d.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:[u.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:[u.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."}),u.map(d=>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(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.kind}),d.topic&&s.jsxs("span",{children:["topic=",d.topic]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Nn(d.payload,360)||"No payload"})]},d.id))]})]})]})}function Q2({machineId:e,sendDaemonCommand:t}){const n=P2({machineId:e,sendDaemonCommand:t}),[r,a]=l.useState("info"),[o,i]=l.useState(""),[u,c]=l.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),p=l.useRef(null),d=l.useRef(!1),m=l.useMemo(()=>K2({daemonLogs:n.daemonLogs,daemonRawText:n.daemonRawText,daemonLogKind:n.daemonLogKind,debugTrace:n.debugTrace,webEvents:n.webEvents,traceCategory:n.traceCategory,quickFilter:r,searchQuery:o,daemonLoading:n.daemonLoading,traceLoading:n.traceLoading,daemonFetchError:n.daemonFetchError,traceFetchError:n.traceFetchError}),[r,o,n.daemonFetchError,n.daemonLoading,n.daemonLogKind,n.daemonLogs,n.daemonRawText,n.debugTrace,n.traceCategory,n.traceFetchError,n.traceLoading,n.webEvents]);l.useEffect(()=>{if(n.autoRefresh&&m.diagnosticEvents.length>0){const v=d.current?"smooth":"instant";setTimeout(()=>{var f;(f=p.current)==null||f.scrollIntoView({behavior:v}),d.current=!0},50)}},[m.diagnosticEvents.length,n.autoRefresh]);const h=l.useCallback(async()=>{var f;const v=T2({daemonLogs:m.visibleDaemonLogs,daemonRawLines:m.visibleDaemonRawLines,trace:m.visibleTraceEntries,webEvents:m.visibleWebEvents});if(!v.trim()){ht.showToast("No visible logs to copy.","info");return}try{await((f=navigator.clipboard)==null?void 0:f.writeText(v)),ht.showToast("Copied visible logs to clipboard.","success")}catch(y){ht.showToast(y instanceof Error?y.message:"Could not copy visible logs","warning")}},[m.visibleDaemonLogs,m.visibleDaemonRawLines,m.visibleTraceEntries,m.visibleWebEvents]),g=l.useCallback(async()=>{var f;const v=O2({events:m.diagnosticEvents,summary:m.diagnosticsSummary,sources:m.sourceStates});try{await((f=navigator.clipboard)==null?void 0:f.writeText(v)),ht.showToast("Copied diagnostic bundle to clipboard.","success")}catch(y){ht.showToast(y instanceof Error?y.message:"Could not copy diagnostic bundle","warning")}},[m.diagnosticEvents,m.diagnosticsSummary,m.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(V2,{quickFilter:r,quickFilterCounts:m.quickFilterCounts,searchQuery:o,autoRefresh:n.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:i,onCopyDiagnostics:()=>{g()},onCopyVisible:()=>{h()},onToggleAutoRefresh:()=>n.setAutoRefresh(v=>!v),onRefresh:n.refresh,onClear:n.clear}),s.jsx(q2,{logLevel:n.logLevel,traceCategory:n.traceCategory,onLogLevelChange:n.setLogLevel,onTraceCategoryChange:n.setTraceCategory}),s.jsx(Y2,{diagnosticsSummary:m.diagnosticsSummary,diagnosticEventsCount:m.diagnosticEvents.length,sourceStates:m.sourceStates,searchQuery:o,lastUpdatedAt:n.lastUpdatedAt,autoRefresh:n.autoRefresh,daemonFetchError:n.daemonFetchError,traceFetchError:n.traceFetchError}),s.jsx(J2,{patterns:m.diagnosticsSummary.repeatedPatterns}),s.jsx(X2,{streams:n,sectionsOpen:u,setSectionsOpen:c,diagnosticEvents:m.diagnosticEvents,visibleDaemonLogs:m.visibleDaemonLogs,visibleDaemonRawLines:m.visibleDaemonRawLines,visibleTraceEntries:m.visibleTraceEntries,visibleWebEvents:m.visibleWebEvents,quickFilter:r,searchQuery:o}),s.jsx("div",{ref:p})]})}function Z2(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 Xh(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 eM(e){var a;const t=[],n=[],r=[];for(const o of e||[]){const i=String((o==null?void 0:o.lifecycle)||"").trim(),u=Xh((o==null?void 0:o.meta)||void 0),c=((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")&&(c||u)?n.push(o):r.push(o)}return{liveRuntimes:t,recoverySnapshots:n,inactiveRecords:r}}function tM(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Po(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 Do(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Lo(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function jd(e){if(!e)return"unknown";const t=Date.now()-e,n=Math.max(0,Math.round(t/1e3));if(n<60)return`${n}s ago`;const r=Math.round(n/60);if(r<60)return`${r}m ago`;const a=Math.round(r/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function sM(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function nM(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 rM(e){var n;const t=new Map;for(const r of e){if(!["starting","running","stopping","interrupted"].includes(r.lifecycle))continue;const a=typeof((n=r.meta)==null?void 0:n.providerSessionId)=="string"?String(r.meta.providerSessionId).trim():"";if(!a)continue;const o=`${r.providerType}::${r.workspace}::${a}`;t.set(o,(t.get(o)||0)+1)}return Array.from(t.values()).filter(r=>r>1).length}function aM({machineId:e,cliSessions:t,sendDaemonCommand:n}){const[r,a]=l.useState(""),[o,i]=l.useState(null),[u,c]=l.useState(!1),p=yk(e,{enabled:!!e,includeSessions:!0,limit:oc,intervalMs:Dv}),d=p.diagnostics,m=p.loading,h=p.applyDiagnostics,g=l.useMemo(()=>Z2({diagnostics:d,loading:m,refreshing:u,error:r}),[d,m,u,r]),v=l.useMemo(()=>new Map(t.map(T=>[T.sessionId||T.id,T])),[t]),f=l.useCallback(async()=>{if(e){c(!0);try{const T=await n(e,"session_host_get_diagnostics",{includeSessions:!0,limit:oc}),L=Do(T);if(!(L!=null&&L.success))throw new Error((L==null?void 0:L.error)||"Could not load hosted runtime diagnostics");h(L.diagnostics||L.result||null),a("")}catch(T){const L=T instanceof Error?T.message:"Could not load hosted runtime diagnostics";a(L)}finally{c(!1)}}},[h,e,n]);l.useEffect(()=>{!e||d||m||u||f()},[d,m,e,f,u]);const y=l.useCallback(async(T,L)=>{const P=`${T}:${L.sessionId}`;if(!(T==="session_host_stop_session"&&!window.confirm(`Stop ${L.displayName}?
108
- This will terminate the hosted runtime.`))){i(P);try{const B=await n(e,T,{sessionId:L.sessionId}),z=Do(B);if(!(z!=null&&z.success))throw new Error((z==null?void 0:z.error)||"Session host action failed");const R=T==="session_host_resume_session"?"resumed":T==="session_host_restart_session"?"restarted":"stopped";ht.showToast(`Session host ${R}: ${L.displayName}`,"success"),await f()}catch(B){const z=B instanceof Error?B.message:"Session host action failed";ht.showToast(z,"warning"),a(z)}finally{i(B=>B===P?null:B)}}},[e,f,n]),j=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 L=await n(e,"session_host_prune_duplicate_sessions",{}),P=Do(L);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Duplicate prune failed");const B=P.result||{},z=Array.isArray(B.prunedSessionIds)?B.prunedSessionIds.length:0,R=typeof B.duplicateGroupCount=="number"?B.duplicateGroupCount:0;ht.showToast(`Pruned ${z} duplicate runtime(s) across ${R} group(s)`,"success"),await f()}catch(L){const P=L instanceof Error?L.message:"Duplicate prune failed";ht.showToast(P,"warning"),a(P)}finally{i(L=>L==="session_host_prune_duplicate_sessions"?null:L)}}},[e,f,n]),x=l.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((T,L)=>(L.lastActivityAt||0)-(T.lastActivityAt||0)),[d==null?void 0:d.sessions]),w=l.useMemo(()=>d!=null&&d.liveRuntimes||d!=null&&d.recoverySnapshots||d!=null&&d.inactiveRecords?{liveRuntimes:(d==null?void 0:d.liveRuntimes)||[],recoverySnapshots:(d==null?void 0:d.recoverySnapshots)||[],inactiveRecords:(d==null?void 0:d.inactiveRecords)||[]}:eM(x),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,x]),N=w.liveRuntimes,k=w.recoverySnapshots,b=w.inactiveRecords,C=l.useMemo(()=>rM(N),[N]),S=l.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),M=l.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(T=>T.level==="warn"||T.level==="error")||null,[d==null?void 0:d.recentLogs]),A=(T,L)=>{var $;const P=o===`session_host_resume_session:${T.sessionId}`,B=o===`session_host_restart_session:${T.sessionId}`,z=o===`session_host_stop_session:${T.sessionId}`,R=Xh(T.meta),_=v.get(T.sessionId),K=T.attachedClients.length===1?"1 client":`${T.attachedClients.length} clients`,E=L==="recovery"?"Recover":"Resume",D=tM(L);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:T.displayName||(_==null?void 0:_.cliName)||T.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${nM(T.lifecycle)}`,children:T.lifecycle}),R&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:R})]}),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:T.workspaceLabel||(_==null?void 0:_.runtimeWorkspaceLabel)||T.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:T.runtimeKey}),T.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",T.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:(($=T.writeOwner)==null?void 0:$.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:sM(T.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})," ",K]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",jd(T.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",D]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[L==="recovery"&&(T.lifecycle==="interrupted"||T.lifecycle==="failed"||T.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{y("session_host_resume_session",T)},children:P?`${E}ing…`:E}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{y("session_host_restart_session",T)},children:B?"Restarting…":"Restart"}),L==="live"&&(T.lifecycle==="running"||T.lifecycle==="starting"||T.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:()=>{y("session_host_stop_session",T)},children:z?"Stopping…":"Stop"})]})]})},T.sessionId)};return s.jsxs(js,{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(Is,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:aw()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[C>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{j()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${C})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${g.toneClass}`,children:g.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{f()},disabled:m||u,children:[s.jsx(ja,{size:13}),m||u?"Refreshing…":"Refresh"]})]})]}),r&&!d&&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:r})]})]})}),d&&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:d.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:k.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.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:jd(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Lo(d.hostStartedAt)})]})]}),M&&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:M.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Lo(M.timestamp),M.sessionId?` · ${M.sessionId}`:""]})]}),s.jsxs("div",{className:"mb-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Ii,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Po("live")}),N.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:N.map(T=>A(T,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Is,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Po("recovery")}),k.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:k.map(T=>A(T,"recovery"))})]}),b.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Po("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:b.map(T=>A(T,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),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(T=>{var P;const L=x.find(B=>B.sessionId===T.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(L==null?void 0:L.displayName)||((P=v.get(T.sessionId))==null?void 0:P.cliName)||T.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[T.action,T.lifecycle?` · ${T.lifecycle}`:"",T.detail?` · ${T.detail}`:"",T.error?` · ${T.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${T.success===!1?"text-red-300":"text-text-secondary"}`,children:Lo(T.timestamp)})]},`${T.sessionId}:${T.timestamp}:${T.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),r?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",r]}):null]})]})]})}function oM({machine:e,launchPick:t,actions:n}){const{runLaunchCliCore:r,setLaunchPick:a}=n;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),r({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),r({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),r({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 iM(e,t){const n=Wp(e),r=dn(e,t),a=qi(e,r),o=tr(e,r),i=n==="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.":n==="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:r,channel:n,required:o,tone:"warn"}:n==="preview"?{visible:!0,showButton:!1,title:r?"Preview daemon is up to date":"Preview update status unknown",description:r?"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:r,channel:n,required:!1,tone:r?"good":"info"}:{visible:!1,showButton:!1,title:"",description:"",buttonLabel:i,targetVersion:r,channel:n,required:!1,tone:"info"}}function Ro({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 _o({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 lM({machineEntry:e,providers:t,recentLaunches:n,currentConversations:r,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:i}){const u=r.slice(0,6),c=n.slice(0,4),d=iM(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:[u.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ro,{icon:s.jsx(Zs,{size:13}),children:"Current Chats"}),s.jsx(_o,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.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:gt(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:vn(m)})]},m.tabKey)})})})]}),c.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ro,{icon:s.jsx(Jd,{size:13}),children:"Recent Launches"}),s.jsx(_o,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(m=>{const{metaText:h,updatedLabel:g}=eh(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)})})})]}),d.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ro,{icon:s.jsx(Ys,{size:13}),children:"Daemon Update"}),s.jsx(_o,{className:d.tone==="good"?"border-emerald-500/20 bg-emerald-500/5":d.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:d.title}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[d.description,d.targetVersion&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",d.targetVersion,d.channel?` (${d.channel})`:""]})]}),d.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(ja,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:d.buttonLabel})]}):s.jsx("div",{className:d.tone==="good"?"text-xs font-medium text-emerald-300":"text-xs font-medium text-sky-300",children:"No preview update action is needed."})]})})]})]})}function cM({machineId:e,machine:t,ideSessions:n,cliSessions:r,acpSessions:a,actions:o,sendDaemonCommand:i}){const{workspaceBusy:u,handleWorkspaceAdd:c,handleWorkspaceRemove:p,handleWorkspaceSetDefault:d}=o,[m,h]=l.useState(!1),[g,v]=l.useState(""),[f,y]=l.useState([]),[j,x]=l.useState(!1),[w,N]=l.useState(""),k=l.useCallback(async C=>{x(!0),N("");try{const S=await sl(i,e,C);v(S.path),y(S.directories)}catch(S){N(S instanceof Error?S.message:"Could not load folder")}finally{x(!1)}},[e,i]),b=l.useCallback(()=>{h(!0);const C=[...n.map(M=>M.workspace),...r.map(M=>M.workspace),...a.map(M=>M.workspace)],S=tl(t.platform,el(C,t.defaultWorkspacePath,(t.workspaces||[]).map(M=>M.path)));k(S)},[a,r,n,k,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs(js,{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(gn,{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:u,onClick:b,children:"+ Add workspace"})]}),(t.workspaces||[]).length===0?s.jsxs("div",{className:"text-[11px] text-text-muted py-4 text-center",children:["No saved workspaces yet. Click ",s.jsx("span",{className:"text-text-secondary",children:"+ Add workspace"})," to pick a folder."]}):s.jsx("ul",{className:"space-y-1.5 max-h-72 overflow-y-auto",children:(t.workspaces||[]).map(C=>{const S=C.id===t.defaultWorkspaceId;return s.jsxs("li",{className:`flex items-start gap-2 text-[11px] rounded-lg border px-2.5 py-2 transition-colors ${S?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:S?"Default workspace — click to unset":"Set as default workspace",disabled:u,onClick:()=>void d(S?null:C.id),className:`text-base leading-none shrink-0 transition-colors ${S?"text-yellow-400 hover:text-yellow-300":"text-text-muted/40 hover:text-yellow-400"}`,children:"★"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"font-medium text-text-primary truncate",children:gu(C.path,C.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:C.path,children:C.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:u,onClick:()=>void p(C.id),children:"Remove"})]},C.id)})})]}),m&&s.jsx(rl,{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:j,error:w,confirmLabel:"Add workspace",onClose:()=>h(!1),onNavigate:C=>{k(C)},onConfirm:C=>{(async()=>{if(!C)return;await c(C)&&h(!1)})()}})]})}function dM({machine:e,machineId:t,ideSessions:n,cliSessions:r,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(cM,{machineId:t,machine:e,ideSessions:n,cliSessions:r,acpSessions:a,actions:o,sendDaemonCommand:i})]})}function uM({onNicknameSynced:e}={}){var Se,ye,ke,me,U,W,Q,V,fe,ce;const{id:t}=Om(),n=hr(),r=ki(),{sendCommand:a}=yt(),o=In(),i=Pp(),u=np(),c=u.ides||[],p=u.initialLoaded??!0,d=c.find(F=>F.id===t&&F.type==="adhdev-daemon"),m=c.some(F=>F.type==="adhdev-daemon"),h=t?(Se=u.connectionRetryStatuses)==null?void 0:Se[t]:void 0,g=!!(h!=null&&h.blocked),[v,f]=l.useState("workspace"),[y,j]=l.useState(null);l.useCallback((F,le)=>{j({daemonId:F,workspace:le})},[]);const[,x]=l.useState("ide"),w=l.useRef(null),[N,k]=l.useState(null),b=l.useRef("__home__"),[C,S]=l.useState("__home__"),[M,A]=l.useState(!1),T=l.useRef(null);l.useEffect(()=>{!t||!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||o(t,{minFreshMs:3e4}).catch(()=>{})},[o,d,t]),l.useEffect(()=>{if(!t||!d||v!=="overview")return;const F=d.machine;(typeof(F==null?void 0:F.cpus)!="number"||typeof(F==null?void 0:F.totalMem)!="number"||typeof(F==null?void 0:F.arch)!="string"||typeof(F==null?void 0:F.release)!="string")&&i(t,{minFreshMs:3e4}).catch(()=>{})},[v,i,d,t]),gk(t&&v==="overview"?[t]:[],{enabled:v==="overview",intervalMs:Iv});const L=()=>{if(m){n("/dashboard",{state:{mobileSection:"machines"}});return}n("/machines")},P=n2({machineId:t,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:T});l.useEffect(()=>ht.onToast(le=>{u.setToasts(de=>{if(de.some(Ne=>Ne.message===le.message&&le.timestamp-Ne.timestamp<3e3))return de;const be={id:le.id,message:le.message,type:le.type,timestamp:le.timestamp,targetKey:le.targetKey,actions:le.actions};return[...de.slice(-4),be]});const je=le.duration||5e3;setTimeout(()=>u.setToasts(de=>de.filter(H=>H.id!==le.id)),je)}),[u]);const B=(d==null?void 0:d.availableProviders)||[],z={};for(const F of B)z[F.type]=F.icon;const R=d?{id:d.id,hostname:yu(d,{fallbackId:d.id}),platform:((ye=d.machine)==null?void 0:ye.platform)||"unknown",arch:((ke=d.machine)==null?void 0:ke.arch)||"",cpus:((me=d.machine)==null?void 0:me.cpus)||0,totalMem:((U=d.machine)==null?void 0:U.totalMem)||0,freeMem:(W=d.machine)==null?void 0:W.freeMem,availableMem:(Q=d.machine)==null?void 0:Q.availableMem,loadavg:(V=d.machine)==null?void 0:V.loadavg,uptime:(fe=d.machine)==null?void 0:fe.uptime,release:((ce=d.machine)==null?void 0:ce.release)||"",cdpConnected:!!d.cdpConnected,machineNickname:d.machineNickname||null,p2p:d.p2p?{screenshotActive:!1,...d.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:d.detectedIdes||[],workspaces:d.workspaces||[],defaultWorkspaceId:d.defaultWorkspaceId??d.activeWorkspaceId??null,defaultWorkspacePath:d.defaultWorkspacePath??d.activeWorkspacePath??null}:null,_=c.filter(F=>F.daemonId===t&&F.type!=="adhdev-daemon").filter(F=>!ir(F)&&!hn(F)).map(F=>({id:F.id,sessionId:F.sessionId,type:F.type,version:F.version||"",instanceId:F.instanceId||"",status:F.status,workspace:F.workspace||null,terminals:F.terminals||0,aiAgents:Kg(F.aiAgents||(F.agents||[]).map(le=>({id:le.name,name:le.name,status:le.status,version:le.version}))),activeChat:F.activeChat||null,chats:F.chats||[],childSessions:F.childSessions||[],cdpConnected:F.cdpConnected||!1,daemonId:t,lastMessageAt:F.lastMessageAt})),K=c.filter(F=>F.daemonId===t&&ir(F)).map(F=>({id:F.id,sessionId:F.sessionId,type:F.type,cliName:F.cliName||F.type,status:F.status,workspace:F.workspace||"",activeChat:F.activeChat||null,providerSessionId:F.providerSessionId,mode:F.mode,runtimeKey:F.runtimeKey,runtimeDisplayName:F.runtimeDisplayName,runtimeWorkspaceLabel:F.runtimeWorkspaceLabel,runtimeWriteOwner:F.runtimeWriteOwner||null,runtimeAttachedClients:F.runtimeAttachedClients||[],daemonId:t,lastMessageAt:F.lastMessageAt})),E=c.filter(F=>F.daemonId===t&&hn(F)).map(F=>({id:F.id,sessionId:F.sessionId,type:F.type,acpName:F.cliName||F.type,status:F.status,workspace:F.workspace||"",activeChat:F.activeChat||null,providerSessionId:F.providerSessionId,daemonId:t,lastMessageAt:F.lastMessageAt})),D=d?ts(d,{fallbackId:t}):"",$="workspace",I=r.state,G=I==null?void 0:I.initialMachineTab,Y=I==null?void 0:I.initialWorkspaceCategory;I==null||I.initialWorkspaceId,I==null||I.initialWorkspacePath;const Z=G==="ides"||G==="clis"||G==="acps"?"workspace":G||$,q=G==="ides"?"ide":G==="clis"?"cli":G==="acps"?"acp":Y,ne=[..._.map(F=>{var le;return{id:`ide:${F.type}:${F.workspace||""}`,label:((le=F.activeChat)==null?void 0:le.title)||F.type,kind:"ide",providerType:F.type,subtitle:F.workspace||void 0,workspace:F.workspace||void 0,lastLaunchedAt:F.lastMessageAt||0}}),...K.map(F=>{var le;return{id:`cli:${F.type}:${F.workspace||""}`,label:((le=F.activeChat)==null?void 0:le.title)||F.cliName,kind:"cli",providerType:F.type,providerSessionId:F.providerSessionId,subtitle:F.workspace||void 0,workspace:F.workspace||void 0,lastLaunchedAt:F.lastMessageAt||0}}),...E.map(F=>{var le;return{id:`acp:${F.type}:${F.workspace||""}`,label:((le=F.activeChat)==null?void 0:le.title)||F.acpName,kind:"acp",providerType:F.type,providerSessionId:F.providerSessionId,subtitle:Js(F.summaryMetadata)||F.workspace||void 0,workspace:F.workspace||void 0,lastLaunchedAt:F.lastMessageAt||0}})].sort((F,le)=>(le.lastLaunchedAt||0)-(F.lastLaunchedAt||0)),ue=((d==null?void 0:d.recentLaunches)||[]).length>0?((d==null?void 0:d.recentLaunches)||[]).map(F=>({id:F.id,label:F.title||F.providerName||F.providerType,kind:F.kind,providerType:F.providerType,providerSessionId:F.providerSessionId,subtitle:Js(F.summaryMetadata)||F.workspace||void 0,workspace:F.workspace,summaryMetadata:F.summaryMetadata,lastLaunchedAt:F.lastLaunchedAt})):ne,ae=l.useMemo(()=>{var le;const F=((le=u.connectionStates)==null?void 0:le[t||""])||void 0;return c.filter(je=>je.daemonId===t&&je.type!=="adhdev-daemon").flatMap(je=>Vi(je,{connectionStates:t&&F?{[t]:F}:void 0,defaultConnectionState:F})).filter(je=>!(je.transport==="pty"&&je.mode==="terminal")).sort((je,de)=>pi(de)-pi(je))},[c,u.connectionStates,t]),O=l.useCallback(F=>{const le=zp(F);le&&n(dr(le))},[n]),se=l.useCallback(()=>{w.current&&(A(!0),w.current().finally(()=>{w.current=null,A(!1),k(null)}))},[]),X=l.useCallback(F=>{if(!R)return;const{options:le,selectedKey:je}=Zp({machine:R,currentWorkspacePath:F.workspace}),de=async()=>{x(F.kind),f("workspace")};w.current=async()=>{const H=le.find(Ce=>Ce.key===b.current),be=(H==null?void 0:H.workspacePath)??null,Ne=(H==null?void 0:H.workspaceId)??null;if(F.kind==="ide"&&F.providerType){await P.handleLaunchIde(F.providerType,be?{workspace:be}:void 0);return}if((F.kind==="cli"||F.kind==="acp")&&F.providerType){await P.runLaunchCliCore({cliType:F.providerType,dir:Ne?void 0:be||"",workspaceId:Ne||void 0,model:F.kind==="acp"&&wu(F.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:F.providerSessionId});return}await de()},b.current=je,S(je),k({title:F.kind==="ide"?da("restart-ide",F.label):F.providerSessionId?mp(F.label):da("start-fresh",F.label),description:F.kind==="ide"?ua("restart-ide"):F.providerSessionId?fp():ua("start-fresh"),confirmLabel:F.kind==="ide"?pa("restart-ide"):F.providerSessionId?ai(!0):pa("start-fresh"),busyLabel:F.kind==="ide"?ha("restart-ide"):F.providerSessionId?hp(!0):ha("start-fresh"),workspaceOptions:le,details:[{label:"Mode",value:F.kind.toUpperCase()},...F.providerType?[{label:"Provider",value:F.providerType}]:[]]})},[P,R]);if(l.useEffect(()=>{f(Z)},[$,Z,t]),l.useEffect(()=>{q&&x(q)},[q,t]),!R)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:L,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const oe=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:14})," Workspace"]}),count:_.length+K.length+E.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Is,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ka,{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:L,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[P.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:P.nicknameInput,onChange:F=>P.setNicknameInput(F.target.value),onKeyDown:F=>{F.key==="Enter"&&P.handleSaveNickname(),F.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(R.machineNickname||"")},title:"Click to set nickname",children:D}),g?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),u.retryConnection&&t&&s.jsx("button",{onClick:()=>u.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:[R.platform," · ",R.arch]}),s.jsxs("span",{children:[R.cpus," cores"]}),(d==null?void 0:d.version)&&s.jsxs("span",{children:["v",d.version]}),R.p2p.available&&s.jsxs("span",{children:["P2P ",R.p2p.state==="connected"?"connected":R.p2p.state]}),R.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:R.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(F=>s.jsxs("button",{onClick:()=>f(F.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${v===F.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[F.label,F.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${v===F.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:F.count})]},F.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:[v==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(lM,{machineEntry:d,providers:B,recentLaunches:ue,currentConversations:ae,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",Up(d))}catch{}},onOpenRecent:X,onOpenConversation:O}),s.jsx(dM,{machine:R,machineId:t,ideSessions:_,cliSessions:K,acpSessions:E,actions:P,sendDaemonCommand:a})]}),v==="providers"&&s.jsx(b2,{machineId:t,providers:B,sendDaemonCommand:a}),v==="overview"&&s.jsx(r2,{machine:R,ideSessions:_,cliSessions:K,acpSessions:E}),v==="session-host"&&s.jsx(aM,{machineId:t,cliSessions:K,sendDaemonCommand:a}),v==="logs"&&s.jsx(Q2,{machineId:t,sendDaemonCommand:a})]})})}),P.launchPick&&R&&s.jsx(oM,{machine:R,launchPick:P.launchPick,actions:P}),N&&s.jsx(Qp,{title:N.title,description:N.description,details:N.details,workspaceOptions:N.workspaceOptions,selectedWorkspaceKey:C,onWorkspaceChange:F=>{b.current=F,S(F)},confirmLabel:N.confirmLabel,busyLabel:N.busyLabel,busy:M,onConfirm:se,onCancel:()=>{w.current=null,k(null)}}),y&&s.jsx(Yh,{daemonId:y.daemonId,workspace:y.workspace,onClose:()=>j(null)}),s.jsx(bp,{toasts:u.toasts||[],onDismiss:F=>u.setToasts(le=>le.filter(je=>je.id!==F)),onClickToast:F=>{F.targetKey&&n(dr(F.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 pM({daemonIds:e,meshId:t,sendData:n,onRevisionAdvance:r}){const a=l.useRef(new Map),o=l.useRef(r);o.current=r;const i=[...new Set(e.filter(Boolean))].sort().join(",");l.useEffect(()=>{a.current=new Map},[i,t]),l.useEffect(()=>{if(!t||!n)return;const u=[...new Set(e.filter(Boolean))];if(u.length===0)return;const c=u.map(p=>ls.subscribe({sendData:n},p,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${p}`,params:{includeSessions:!0}},d=>{if(d.topic!=="daemon.metadata")return;const m=d.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 c)p()}},[i,t,n])}const hM={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},Qh=l.createContext(null);function mM(){const e=l.useContext(Qh);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function fM({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 xM({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 bM({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 gM({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 yM({status:e}){const n={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:n.color+"15",color:n.color,border:`1px solid ${n.color}25`},title:n.title,children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:n.color}}),n.label]})}function vM(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function wM({meshes:e,loading:t,error:n,onDismissError:r,daemons:a,features:o,showCreate:i,onToggleCreate:u,createName:c,onCreateNameChange:p,createRepoIdentity:d,onCreateRepoIdentityChange:m,createRepoRemoteUrl:h,onCreateRepoRemoteUrlChange:g,newMeshDaemonId:v,onNewMeshDaemonIdChange:f,newMeshWorkspace:y,onNewMeshWorkspaceChange:j,createPickerWorkspaces:x,onSelectMesh:w,onCreate:N,onCancelCreate:k}){const{t:b}=Xe("common");return s.jsxs(br,{icon:s.jsx(es,{}),title:b("repoMesh.list.title"),subtitle:b("repoMesh.list.count",{count:e.length}),widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:u,children:b("repoMesh.list.createMesh")}),children:[n&&s.jsx(Kt,{variant:"error",onDismiss:r,className:"mb-4",children:n}),i&&s.jsxs(xt,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:[s.jsx("h3",{className:"text-base font-bold mb-4",children:b("repoMesh.list.createTitle")}),o.createDaemonPicker&&s.jsx(St,{label:b("repoMesh.list.createOnMachine"),hint:b("repoMesh.list.createOnMachineHint"),children:s.jsx("select",{className:"input w-full",value:v,onChange:C=>f(C.target.value),disabled:!a.length,children:a.length===0?s.jsx("option",{value:"",children:b("repoMesh.list.noConnectedDaemon")}):a.map(C=>s.jsx("option",{value:C.id,children:vM(C)},C.id))})}),o.createDaemonPicker&&s.jsx(St,{label:b("repoMesh.list.workspace"),hint:b("repoMesh.list.workspaceHint"),children:s.jsx("select",{className:"input w-full",value:y,onChange:C=>j(C.target.value),disabled:!v||!x.length,children:v?x.length===0?s.jsx("option",{value:"",children:b("repoMesh.list.noRegisteredWorkspaces")}):x.map(C=>s.jsx("option",{value:C.path,children:C.label?`${C.label} · ${C.path}`:C.path},C.id||C.path)):s.jsx("option",{value:"",children:b("repoMesh.list.selectMachineFirst")})})}),s.jsx(St,{label:b("repoMesh.list.name"),children:s.jsx(is,{value:c,onChange:C=>p(C.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(St,{label:b("repoMesh.list.remoteUrl"),hint:b("repoMesh.list.remoteUrlHint"),children:s.jsx(is,{value:h,onChange:C=>g(C.target.value),placeholder:"https://github.com/user/repo"})}),s.jsx(St,{label:b("repoMesh.list.repoIdentity"),hint:b("repoMesh.list.remoteUrlHint"),children:s.jsx(is,{value:d,onChange:C=>m(C.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:N,disabled:!c.trim()||!h.trim()&&!d.trim()||o.createDaemonPicker&&(!v||!y),children:b("repoMesh.list.create")}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:k,children:b("repoMesh.list.cancel")})]})]}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:b("repoMesh.list.loading")}):e.length===0?s.jsx(La,{icon:s.jsx(es,{}),title:b("repoMesh.list.emptyTitle"),description:a.length>0?b("repoMesh.list.emptyWithDaemons"):b("repoMesh.list.emptyNoDaemons"),action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!a.length,onClick:u,children:b("repoMesh.list.createFirst")})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(C=>{var S;return s.jsx("button",{type:"button",onClick:()=>w(C.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(es,{size:16}),s.jsx("span",{className:"font-bold text-sm",children:C.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:C.repoIdentity||C.repo_identity||b("repoMesh.list.noRepoIdentity")}),(C.defaultBranch||C.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(xM,{size:11}),C.defaultBranch||C.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(C.createdAt||C.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((S=C.nodes)==null?void 0:S.length)??C.nodeCount??0," ",b("repoMesh.list.nodesSuffix")]})]})]})},C.id)})})]})}const kM=["claude-cli","codex-cli","gemini-cli","hermes-cli","antigravity-cli"],jM=[{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 SM(){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 NM(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function CM(e){const t=[];for(let n=0;n<e.length;n++){const r=e[n],a=r.provider.trim();if(!a)return{error:{code:"provider_required",slot:n+1}};const o=r.nodeId.trim(),i=r.model.trim(),u=r.n.trim();let c;if(u){const p=Number(u);if(!Number.isFinite(p)||p<1)return{error:{code:"replica_min",slot:n+1}};c=Math.floor(p)}t.push({provider:a,...o?{nodeId:o}:{},...i?{model:i}:{},...c!==void 0?{n:c}:{}})}return t.length===0?{error:{code:"no_slot"}}:{slots:t}}function MM({status:e,daemonId:t,sendDaemonCommand:n,availableProviders:r}){const{t:a}=Xe(),{theme:o}=Ls(),i=l.useMemo(()=>Rs(o),[o]),u=l.useMemo(()=>kp(r),[r]),[c,p]=l.useState({}),[d,m]=l.useState(!1),[h,g]=l.useState(null),[v,f]=l.useState({}),[y,j]=l.useState(null),x=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(D=>({nodeId:D.nodeId,machineLabel:D.machineLabel,providers:D.providers,providerPriority:D.providerPriority})),[e==null?void 0:e.nodes]),w=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(D=>D.nodeId),[e==null?void 0:e.nodes]),N=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map(D=>[D.nodeId,D.machineLabel||D.nodeId])),[e==null?void 0:e.nodes]),k=l.useMemo(()=>{const D={};for(const $ of x)D[$.nodeId]=Sd($);return D},[x]),b=l.useMemo(()=>{const D=[...new Set(x.flatMap(Sd).filter(Boolean))];return[...new Set([...D,...kM])].sort()},[x]),C=!!t&&!!n,S=D=>D&&typeof D=="object"&&"result"in D?D.result:D,M=l.useCallback(async()=>{if(!(!t||!n)){m(!0),g(null);try{const D=await n(t,"magi_kind_panel_list",{}),$=S(D);if(($==null?void 0:$.success)===!1)throw new Error($.error||a("meshGraph.magiKind.errorLoad"));p($!=null&&$.kindPanels&&typeof $.kindPanels=="object"?$.kindPanels:{}),f({})}catch(D){g((D==null?void 0:D.message)||a("meshGraph.magiKind.errorLoad"))}finally{m(!1)}}},[t,n,a]);l.useEffect(()=>{M()},[M]);const A=l.useCallback(D=>{if(v[D])return v[D];const $=c[D];return $?$.map(NM):[]},[v,c]),T=(D,$)=>{f(I=>({...I,[D]:$}))},L=(D,$,I)=>{const G=A(D);T(D,G.map((Y,Z)=>Z===$?{...Y,...I}:Y))},P=D=>{T(D,[...A(D),SM()])},B=(D,$)=>{T(D,A(D).filter((I,G)=>G!==$))},z=l.useCallback(async D=>{if(!t||!n)return;const $=CM(A(D));if("error"in $){const I=$.error,G=I.code==="provider_required"?a("meshGraph.magiKind.errorSlotProvider",{slot:I.slot}):I.code==="replica_min"?a("meshGraph.magiKind.errorSlotReplica",{slot:I.slot}):a("meshGraph.magiKind.errorNoSlot");g(`${D}: ${G}`);return}j(D),g(null);try{const I=await n(t,"magi_kind_panel_set",{kind:D,slots:$.slots}),G=S(I);if((G==null?void 0:G.success)===!1)throw new Error(G.error||a("meshGraph.magiKind.errorSave"));await M()}catch(I){g((I==null?void 0:I.message)||a("meshGraph.magiKind.errorSave"))}finally{j(null)}},[t,n,A,M,a]),R=l.useCallback(async D=>{if(!(!t||!n)&&confirm(a("meshGraph.magiKind.removeConfirm",{kind:D}))){j(D),g(null);try{const $=await n(t,"magi_kind_panel_remove",{kind:D}),I=S($);if((I==null?void 0:I.success)===!1)throw new Error(I.error||a("meshGraph.magiKind.errorRemove"));await M()}catch($){g(($==null?void 0:$.message)||a("meshGraph.magiKind.errorRemove"))}finally{j(null)}}},[t,n,M,a]),_=`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"}`,K="btn btn-primary btn-sm",E="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:E,onClick:()=>void M(),disabled:d||!C,children:a(d?"meshGraph.magiKind.loading":"meshGraph.magiKind.refresh")})})]}),!C&&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:jM.map(({kind:D,labelKey:$,hint:I})=>{const G=A(D),Y=!!c[D],Z=y===D;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($)}),s.jsx("span",{className:`font-mono text-[10px] ${i.textMuted}`,children:I}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${Y?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:Y?a("meshGraph.magiKind.agentCount",{count:c[D].length}):a("meshGraph.magiKind.off")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[G.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")}),G.map((q,ne)=>{const ue=q.nodeId?k[q.nodeId]??[]:[],ae=q.nodeId&&ue.length?ue: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:_,value:q.nodeId,onChange:O=>L(D,ne,{nodeId:O.target.value}),title:a("meshGraph.magiKind.machineTitle"),children:[s.jsx("option",{value:"",children:a("meshGraph.magiKind.anyMachine")}),w.map(O=>s.jsx("option",{value:O,children:N[O]??O},O)),q.nodeId&&!w.includes(q.nodeId)&&s.jsx("option",{value:q.nodeId,children:a("meshGraph.magiKind.offlineSuffix",{label:N[q.nodeId]??q.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:_,value:q.provider,onChange:O=>L(D,ne,{provider:O.target.value}),title:a("meshGraph.magiKind.providerTitle"),children:[s.jsx("option",{value:"",children:a("meshGraph.magiKind.selectProvider")}),ae.map(O=>s.jsx("option",{value:O,children:O},O)),q.provider&&!ae.includes(q.provider)&&s.jsx("option",{value:q.provider,children:q.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 X;const O=(q.provider?(X=u.get(q.provider))==null?void 0:X.models:void 0)??[],se=!!q.model&&O.length>0&&!O.includes(q.model);return O.length>0&&!se?s.jsxs("select",{className:_,value:O.includes(q.model)?q.model:"",title:a("meshGraph.magiKind.modelTitle"),onChange:oe=>L(D,ne,{model:oe.target.value==="__custom__"?" ":oe.target.value}),children:[s.jsx("option",{value:"",children:a("meshGraph.magiKind.modelDefault")}),O.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:_,value:q.model.trim(),placeholder:a("meshGraph.magiKind.modelDefault"),title:a("meshGraph.magiKind.modelTitle"),onChange:oe=>L(D,ne,{model:oe.target.value})}),O.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:()=>L(D,ne,{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:`${_} sm:w-16`,value:q.n,placeholder:"1",inputMode:"numeric",title:a("meshGraph.magiKind.copiesTitle"),onChange:O=>L(D,ne,{n:O.target.value})})]}),s.jsx("button",{type:"button",className:`${E} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>B(D,ne),"aria-label":a("meshGraph.magiKind.removeAgent"),title:a("meshGraph.magiKind.removeAgent"),children:"✕"})]},ne)}),s.jsx("div",{children:s.jsx("button",{type:"button",className:E,onClick:()=>P(D),disabled:!C,children:a("meshGraph.magiKind.addAgent")})})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:K,onClick:()=>void z(D),disabled:Z||!C,children:a(Z?"meshGraph.magiKind.saving":"meshGraph.magiKind.save")}),s.jsx("button",{type:"button",className:E,onClick:()=>void R(D),disabled:Z||!C||!Y,title:a(Y?"meshGraph.magiKind.removeBindingTitle":"meshGraph.magiKind.removeBindingDisabledTitle"),children:a("meshGraph.magiKind.removeBinding")})]})]},D)})})]})}function AM({daemonId:e,meshId:t,cliType:n,sendCommand:r}){const{t:a}=Xe(),[o,i]=l.useState(!1),[u,c]=l.useState(!1),[p,d]=l.useState(null),[m,h]=l.useState(null),[g,v]=l.useState(null),f=l.useCallback(async()=>{if(!e||!t){d(a("repoMesh.promptPreview.connectPrompt"));return}c(!0),d(null);try{const j=await r(e,"coordinator_prompt_preview",{meshId:t,cliType:n}),x=j!=null&&j.result&&typeof j.result=="object"?j.result:j;if(!(x!=null&&x.success)){d((x==null?void 0:x.error)||a("repoMesh.promptPreview.errorRender"));return}h(typeof x.prompt=="string"?x.prompt:""),v(typeof x.bytes=="number"?x.bytes:null)}catch(j){d((j==null?void 0:j.message)||String(j))}finally{c(!1)}},[e,t,n,r,a]),y=l.useCallback(()=>{const j=!o;i(j),j&&m===null&&!u&&f()},[o,m,u,f]);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:y,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:["(",n,")"]})]}),o&&s.jsxs("div",{className:"mt-2",children:[u&&s.jsx("div",{className:"text-[12px] text-text-muted",children:a("repoMesh.promptPreview.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:a("repoMesh.promptPreview.retry")})]}),!u&&!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:a("repoMesh.promptPreview.info")}),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:j=>j.currentTarget.select()})]})]})]})}const IM=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function TM(e){const t=IM(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function PM(e){const t=e==null?void 0:e.missions;return Array.isArray(t)?t:[]}function DM(e){return typeof e.goal=="string"&&e.goal?{text:e.goal,truncated:!1}:{text:e.goalPreview??"",truncated:e.goalTruncated===!0}}const LM=["active","paused","completed","abandoned"];function Nd(e){return(e.status||"active").toLowerCase()}const RM=8;function _M({status:e,daemonId:t,meshId:n,sendCommand:r}){const{t:a}=Xe("common"),o=l.useMemo(()=>PM(e),[e]),[i,u]=l.useState({}),[c,p]=l.useState({}),[d,m]=l.useState(!1),[h,g]=l.useState(null),[v,f]=l.useState("active"),[y,j]=l.useState(!1),x=l.useMemo(()=>{const M={};for(const A of o){const T=Nd(A);M[T]=(M[T]||0)+1}return M},[o]),w=l.useMemo(()=>v==="all"?o:o.filter(M=>Nd(M)===v),[o,v]),N=y?w:w.slice(0,RM),k=w.length-N.length,b=!!t&&o.length>0,C=l.useCallback(async()=>{if(t){m(!0),g(null);try{const M=await r(t,"mesh_status",{meshId:n,verbose:!0}),A=TM(M),T=Array.isArray(A==null?void 0:A.missions)?A.missions:[],L={};for(const P of T)P.id&&typeof P.goal=="string"&&P.goal&&(L[P.id]=P.goal);u(P=>({...P,...L}))}catch(M){g(M instanceof Error?M.message:a("repoMesh.missions.errorFetch"))}finally{m(!1)}}},[t,n,r,a]),S=l.useCallback(M=>{p(A=>({...A,[M]:!A[M]})),!c[M]&&!i[M]&&C()},[c,i,C]);return o.length===0?null:s.jsxs(xt,{title:a("repoMesh.missions.title"),description:a("repoMesh.missions.description"),children:[h&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400",children:h}),s.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[LM.filter(M=>(x[M]||0)>0).map(M=>s.jsxs("button",{type:"button",onClick:()=>{f(M),j(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] capitalize transition-colors ${v===M?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:[M," ",x[M]]},M)),s.jsxs("button",{type:"button",onClick:()=>{f("all"),j(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] transition-colors ${v==="all"?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:["All ",o.length]})]}),w.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:a("repoMesh.missions.empty",{status:v})}),s.jsx("div",{className:"flex flex-col gap-2",children:N.map(M=>{var R;const A=c[M.id]===!0,T=i[M.id],L=DM(M),P=A&&T?T:L.text,B=A&&!T&&L.truncated,z=((R=M.tasks)==null?void 0:R.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:M.title,children:M.title||M.id}),M.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:M.status}),z>0&&s.jsx("span",{className:"shrink-0 text-[11px] text-text-muted",children:a("repoMesh.missions.taskCount",{count:z})})]}),P&&s.jsxs("div",{className:`mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-text-secondary ${A?"max-h-72 overflow-y-auto":"line-clamp-2"}`,children:[P,B&&s.jsx("span",{className:"text-text-muted",children:a("repoMesh.missions.goalUnavailable")})]}),(L.truncated||T)&&b&&s.jsx("button",{type:"button",className:"mt-1.5 text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:()=>S(M.id),disabled:d,children:a(A?"repoMesh.missions.showLess":d&&!T?"repoMesh.missions.loading":"repoMesh.missions.showFullGoal")})]},M.id)})}),k>0&&s.jsx("button",{type:"button",className:"mt-2 text-[12px] text-accent-primary hover:underline",onClick:()=>j(!0),children:a("repoMesh.missions.showMore",{count:k})})]})}const EM=["","low","medium","high"],$M={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 Md(e){const t=e.provider.trim();if(!t)return null;const n=e.model.trim(),r=e.thinkingLevel.trim()||void 0,a=Number(e.maxParallel),o=Number.isFinite(a)&&a>0?Math.floor(a):void 0;return{provider:t,...n?{model:n}:{},...r?{thinkingLevel:r}:{},...e.difficulty.length?{difficulty:e.difficulty}:{},...e.capability.length?{capability:e.capability}:{},...o!==void 0?{maxParallel:o}:{}}}function FM(){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 BM({slots:e,availableProviders:t,saving:n,onSave:r}){const{t:a}=Xe("common"),[o,i]=l.useState(()=>e.map(Cd)),u=l.useMemo(()=>JSON.stringify(e),[e]);l.useEffect(()=>{i(e.map(Cd))},[u]);const c=l.useMemo(()=>[...new Set(t.map(x=>x.type).filter(Boolean))],[t]),p=l.useMemo(()=>kp(t),[t]),d=l.useMemo(()=>{const x=o.map(Md).filter(Boolean);return JSON.stringify(x)!==JSON.stringify(e)},[o,e]),m=(x,w)=>i(N=>N.map((k,b)=>b===x?{...k,...w}:k)),h=(x,w)=>i(N=>N.map((k,b)=>{var M;if(b!==x)return k;const C=((M=p.get(w))==null?void 0:M.models)??[],S=!k.model||C.length===0||C.includes(k.model);return{...k,provider:w,...S?{}:{model:""}}})),g=x=>i(w=>w.filter((N,k)=>k!==x)),v=()=>i(x=>[...x,FM()]),f=(x,w)=>i(N=>{const k=x+w;if(k<0||k>=N.length)return N;const b=[...N];return[b[x],b[k]]=[b[k],b[x]],b}),y=(x,w)=>i(N=>N.map((k,b)=>{if(b!==x)return k;const C=k.difficulty.includes(w);return{...k,difficulty:C?k.difficulty.filter(S=>S!==w):[...k.difficulty,w]}})),j=()=>r(o.map(Md).filter(Boolean));return s.jsxs("div",{className:"flex flex-col gap-2",onClick:x=>x.stopPropagation(),children:[o.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:a("repoMesh.slotEditor.empty")}),o.map((x,w)=>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:["#",w+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:w===0,onClick:()=>f(w,-1),title:a("repoMesh.slotEditor.moveUp"),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:w===o.length-1,onClick:()=>f(w,1),title:a("repoMesh.slotEditor.moveDown"),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:()=>g(w),"aria-label":a("repoMesh.slotEditor.removeSlot"),children:s.jsx(Mt,{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:a("repoMesh.slotEditor.provider")}),c.length>0?s.jsxs("select",{className:Es,value:x.provider,onChange:N=>h(w,N.target.value),children:[s.jsx("option",{value:"",children:a("repoMesh.slotEditor.select")}),c.map(N=>s.jsx("option",{value:N,children:N},N)),x.provider&&!c.includes(x.provider)&&s.jsx("option",{value:x.provider,children:x.provider})]}):s.jsx("input",{className:Es,value:x.provider,placeholder:"claude-cli",onChange:N=>m(w,{provider:N.target.value})})]}),(()=>{var S;const N=p.get(x.provider),k=(N==null?void 0:N.models)??[],b=(S=N==null?void 0:N.thinking)!=null&&S.length?["",...N.thinking]:EM,C=!!x.model&&k.length>0&&!k.includes(x.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:a("repoMesh.slotEditor.model")}),k.length>0&&!C?s.jsxs("select",{className:Es,value:k.includes(x.model)?x.model:"",onChange:M=>m(w,{model:M.target.value==="__custom__"?" ":M.target.value}),children:[s.jsx("option",{value:"",children:a("repoMesh.slotEditor.providerDefault")}),k.map(M=>s.jsx("option",{value:M,children:M},M)),s.jsx("option",{value:"__custom__",children:a("repoMesh.slotEditor.custom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:Es,value:x.model.trim(),placeholder:x.provider?`${x.provider} model`:a("repoMesh.slotEditor.modelPlaceholder"),onChange:M=>m(w,{model:M.target.value})}),k.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:()=>m(w,{model:""}),children:a("repoMesh.slotEditor.backToModelList")})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.thinking")}),s.jsx("select",{className:Es,value:x.thinkingLevel,onChange:M=>m(w,{thinkingLevel:M.target.value}),children:b.map(M=>s.jsx("option",{value:M,children:M||a("repoMesh.slotEditor.thinkingDefault")},M||"_default"))})]})]})})()]}),s.jsxs("div",{className:"mt-2",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.difficulty")}),s.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:Pg.map(N=>{const k=x.difficulty.includes(N);return s.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${k?"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:()=>y(w,N),children:$M[N]},N)})})]}),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:a("repoMesh.slotEditor.capabilityTags")}),s.jsx("input",{className:Es,value:x.capability.join(", "),placeholder:"worktree, os=darwin",onChange:N=>m(w,{capability:N.target.value.split(",").map(k=>k.trim()).filter(Boolean)})})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.maxParallel")}),s.jsx("input",{type:"number",inputMode:"numeric",min:1,className:Es,value:x.maxParallel,placeholder:a("repoMesh.slotEditor.maxParallelPlaceholder"),onChange:N=>m(w,{maxParallel:N.target.value})})]})]})]},w)),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:v,children:[s.jsx(Ti,{size:13})," ",a("repoMesh.slotEditor.addSlot")]}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:j,disabled:!!n||!d,children:a(n?"repoMesh.slotEditor.saving":"repoMesh.slotEditor.saveSlots")})]})]})}function HM(e){const t=new Map;for(const n of e)n!=null&&n.id&&t.set(n.id,wn(n.availableProviders||[]));return t}function OM(e,t){const n=String(e.daemon_id||e.daemonId||"");return n&&t.has(n)?t.get(n):!n&&t.size===1?[...t.values()][0]:[]}function WM(e){var c,p,d;const t=e,n=[],r=Array.isArray(t.capabilities)?t.capabilities:[];for(const m of r){const h=typeof m=="string"?m.trim():"";h&&n.push({tag:h,custom:!0})}const a=(((c=t.userOverrides)==null?void 0:c.platform)||t.reportedPlatform||"").toString().trim(),o=(((p=t.userOverrides)==null?void 0:p.arch)||t.reportedArch||"").toString().trim();a&&n.push({tag:`os=${a}`,custom:!1}),o&&n.push({tag:`arch=${o}`,custom:!1});const i=Array.isArray((d=t.policy)==null?void 0:d.providerPriority)?String(t.policy.providerPriority[0]||"").trim():"";i&&n.push({tag:`provider=${i}`,custom:!1});const u=typeof t.worktreeBranch=="string"?t.worktreeBranch.trim():"";return t.isLocalWorktree===!0&&u&&n.push({tag:`worktree=${u}`,custom:!1}),n}function UM(e){const t=e.capabilities;return Array.isArray(t)?t.map(n=>typeof n=="string"?n.trim():"").filter(Boolean):[]}const KM=["os=","arch=","provider=","worktree=","converge="];function GM({node:e,saving:t,onSave:n}){const{t:r}=Xe("common"),a=l.useMemo(()=>WM(e).filter(f=>!f.custom),[e]),o=l.useMemo(()=>UM(e),[e]),[i,u]=l.useState(o),[c,p]=l.useState(""),d=JSON.stringify(i)!==JSON.stringify(o),h=(f=>{const y=f.trim();return y?/\s/.test(y)?r("repoMesh.tagEditor.noSpaces"):KM.some(j=>y.toLowerCase().startsWith(j))?r("repoMesh.tagEditor.reservedPrefix"):i.includes(y)?r("repoMesh.tagEditor.alreadyAdded"):null:null})(c);function g(){const f=c.trim();!f||h||(u(y=>[...y,f]),p(""))}function v(f){u(y=>y.filter(j=>j!==f))}return s.jsxs("div",{className:"mt-2",onClick:f=>f.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:r("repoMesh.tagEditor.routingTags")}),a.map(f=>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:r("repoMesh.tagEditor.autoDerivedTitle"),children:f.tag},f.tag)),i.map(f=>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:r("repoMesh.tagEditor.customTagTitle"),children:[f,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:()=>v(f),disabled:t,"aria-label":r("repoMesh.tagEditor.remove",{tag:f}),children:"×"})]},f))]}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"text",value:c,onChange:f=>p(f.target.value),onKeyDown:f=>{f.key==="Enter"&&(f.preventDefault(),g())},placeholder:r("repoMesh.tagEditor.addPlaceholder"),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:g,disabled:t||!c.trim()||!!h,children:r("repoMesh.tagEditor.add")}),d&&s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>n(i),disabled:t,children:r(t?"repoMesh.tagEditor.saving":"repoMesh.tagEditor.saveTags")})]}),h&&s.jsx("div",{className:"mt-1 text-[11px] text-amber-400",children:h}),i.length===0&&a.length===0&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:r("repoMesh.tagEditor.empty")})]})}function zM(e,t){return t.filter(n=>n.status!=="assigned"?!1:(n.assignedNodeId||n.nodeId)===e.id)}function VM(e){const t=e.assignedSessionId||e.sessionId||"unassigned session",n=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${t}: ${n}`}function qM(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>n.has(a)?!1:(n.add(a),!0))}function YM(e){const t=qM(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 JM(e){return e.isLocalWorktree===!0}function XM(e,t){const n=t;return[...Array.isArray(n==null?void 0:n.cliSessions)?n.cliSessions:[],...Array.isArray(n==null?void 0:n.acpSessions)?n.acpSessions:[],...Array.isArray(n==null?void 0:n.sessions)?n.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 QM(e,t){var n;return(e==null?void 0:e.ownerName)||(e==null?void 0:e.userName)||((n=e==null?void 0:e.user)==null?void 0:n.name)||t||"You"}function ZM({nodes:e,meshQueue:t,activeDaemon:n,daemons:r,selectedMeshId:a,userName:o,features:i,coordinatorDaemonId:u,availableCliProviders:c,savingNodeSlotsId:p,onUpdateNodeSlots:d,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:h,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:v,savingNodeSystemPromptId:f,onSaveNodeSystemPrompt:y,selectedNodeId:j,onSelectNode:x,showAddNode:w,onShowAddNode:N,onCancelAddNode:k,nodeWorkspace:b,onNodeWorkspaceChange:C,nodeProviderPriority:S,onNodeProviderPriorityChange:M,nodeDaemonId:A,onNodeDaemonIdChange:T,nodeCustomPath:L,onNodeCustomPathChange:P,nodePickerWorkspaces:B,nodePickerProviders:z,attachableDaemons:R,onAddNode:_,onRemoveNode:K}){const{t:E}=Xe("common"),D=l.useMemo(()=>HM(r),[r]),$=l.useMemo(()=>e.filter(I=>!JM(I)),[e]);return s.jsxs(xt,{title:i.addNodeDaemonPicker?E("repoMesh.nodeList.title",{count:$.length}):E("repoMesh.nodeList.titleNoCount"),description:i.addNodeDaemonPicker?E("repoMesh.nodeList.descriptionCloud"):E("repoMesh.nodeList.descriptionStandalone"),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:E("repoMesh.nodeList.daemonCandidates")}),s.jsx("div",{className:"text-[12px] text-text-muted",children:E("repoMesh.nodeList.daemonCandidatesHint")})]}),s.jsx("span",{className:"text-[11px] text-text-muted",children:E("repoMesh.nodeList.available",{count:R.length})})]}),r.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:E("repoMesh.nodeList.noDaemonsAvailable")}):R.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:E("repoMesh.nodeList.allDaemonsAttached")}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:R.map(I=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors ${I.id===u?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{T(I.id),C(""),P(!1),M(cr(wn(I.availableProviders||[]))),N()},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-medium truncate",children:Ad(I)}),I.id===u&&s.jsx("span",{className:"text-[10px] text-accent-primary",children:E("repoMesh.nodeList.selectedHost")})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:I.id}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:E("repoMesh.nodeList.workspacesDetected",{count:(I.workspaces||[]).length})})]},I.id))})]}),!w&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:N,children:[s.jsx(gM,{size:13})," ",i.addNodeDaemonPicker?E("repoMesh.nodeList.attachMachine"):E("repoMesh.nodeList.addNode")]}),w&&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?E("repoMesh.nodeList.attachMachineTitle"):E("repoMesh.nodeList.addNodeTitle")}),s.jsx("button",{onClick:()=>{k(),T(""),P(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(Mt,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(St,{label:E("repoMesh.nodeList.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:A,onChange:I=>{var G;T(I.target.value),C(""),P(!1),M(cr(wn(((G=r.find(Y=>Y.id===I.target.value))==null?void 0:G.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:E("repoMesh.nodeList.selectMachine")}),r.map(I=>s.jsx("option",{value:I.id,children:Ad(I)},I.id))]})}),(i.addNodeDaemonPicker?A:!0)&&s.jsx(St,{label:E("repoMesh.nodeList.workspacePath"),children:i.addNodeDaemonPicker&&!L&&B.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:B.map(I=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${b===I.path?"border-accent-primary bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-primary hover:bg-violet-500/10 text-text-primary"}`,onClick:()=>C(I.path),children:[s.jsx("span",{className:"font-medium block truncate",children:I.label||I.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:I.path})]},I.id||I.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{P(!0),C("")},children:E("repoMesh.nodeList.enterCustomPath")})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(is,{value:b,onChange:I=>C(I.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:I=>{I.key==="Enter"&&_()}}),B.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),C("")},children:E("repoMesh.nodeList.pickFromSaved")})]}):(()=>{var Y;const I=Array.isArray(n==null?void 0:n.workspaces)?n.workspaces:[],G=`mesh-add-node-workspaces-${a||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(is,{value:b,onChange:Z=>C(Z.target.value),placeholder:((Y=I[0])==null?void 0:Y.path)||"/Users/dev/projects/myapp",list:I.length>0?G:void 0,autoFocus:!0}),I.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:G,children:I.map(Z=>s.jsx("option",{value:Z.path,children:Z.label||Z.path},Z.id||Z.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:I.slice(0,6).map(Z=>s.jsx("button",{type:"button",onClick:()=>C(Z.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:Z.path,children:Z.label||Z.path.split("/").filter(Boolean).pop()||Z.path},Z.id||Z.path))})]})]})})()})}),s.jsx(St,{label:E("repoMesh.nodeList.preferredTools"),hint:E("repoMesh.nodeList.preferredToolsHint"),children:s.jsx(jw,{value:S,availableProviders:i.addNodeDaemonPicker?z:c,onChange:M})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:_,disabled:!b.trim()||i.addNodeDaemonPicker&&!A,className:"btn btn-primary btn-sm",children:E("repoMesh.nodeList.add")}),s.jsx("button",{onClick:()=>{k(),T(""),P(!1)},className:"btn btn-secondary btn-sm",children:E("repoMesh.nodeList.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:E("repoMesh.nodeList.setupInventoryWarning")}),$.length===0?s.jsx(La,{icon:s.jsx(gn,{}),title:E("repoMesh.nodeList.emptyTitle"),description:E("repoMesh.nodeList.emptyDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:$.map(I=>{var ue;const G=YM(I),Y=zM(I,t),Z=XM(I,n),q=j===I.id,ne=I.status||I.machine_status||(Y.length>0||Z.length>0?"active":"enabled");return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary transition-colors ${i.addNodeDaemonPicker?"bg-bg-glass border-border-subtle rounded-xl px-5 py-4":`cursor-pointer ${q?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:i.addNodeDaemonPicker?void 0:"button",tabIndex:i.addNodeDaemonPicker?void 0:0,onClick:i.addNodeDaemonPicker?void 0:()=>x(q?null:I.id),onKeyDown:i.addNodeDaemonPicker?void 0:ae=>{(ae.key==="Enter"||ae.key===" ")&&(ae.preventDefault(),x(q?null:I.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:I.machine_label||I.machine_nickname||I.hostname||I.workspace}):s.jsx("span",{className:"text-sm font-medium",children:I.workspace.split("/").pop()}),i.addNodeDaemonPicker&&s.jsx(yM,{status:ne}),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:E("repoMesh.nodeList.setupInventory")})]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"text-[11px] text-text-muted",children:E("repoMesh.nodeList.ownerMachine",{owner:QM(r.find(ae=>ae.id===String(I.daemon_id||"")),o),machine:I.machine_label||I.daemon_id||I.workspace})}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:I.workspace}),s.jsx(GM,{node:I,saving:m===I.id,onSave:ae=>h(I,ae)}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mt-2 text-[11px] text-amber-300",children:E("repoMesh.nodeList.liveDetailGraphOwned")}),s.jsxs("div",{className:"mt-3 max-w-2xl",onClick:ae=>ae.stopPropagation(),children:[s.jsx(St,{label:E("repoMesh.nodeList.slotsLabel"),hint:E("repoMesh.nodeList.slotsHint"),children:s.jsx(BM,{slots:Array.isArray((ue=I.policy)==null?void 0:ue.slots)?I.policy.slots:[],availableProviders:OM(I,D),saving:p===I.id,onSave:ae=>d(I,ae)})}),i.nodeInstruction&&s.jsxs(St,{label:E("repoMesh.nodeList.nodeInstruction"),hint:E("repoMesh.nodeList.nodeInstructionHint"),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[I.id]??"",onChange:ae=>{const O=ae.target.value;v(I.id,O)},onClick:ae=>ae.stopPropagation(),disabled:f===I.id,placeholder:E("repoMesh.nodeList.nodeInstructionPlaceholder")}),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:ae=>{ae.stopPropagation(),y(I)},disabled:f===I.id,children:f===I.id?E("repoMesh.nodeList.saving"):E("repoMesh.nodeList.saveInstruction")})})]})]})]}),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:ae=>{ae.stopPropagation(),K(I.id)},title:E("repoMesh.nodeList.removeNode"),children:s.jsx(bM,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:ae=>ae.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:"▸"})," ",E("repoMesh.nodeList.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:E("repoMesh.nodeList.nodeId")})," ",s.jsx("span",{className:"font-mono break-all",children:I.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.launchReady")})," ",s.jsx("span",{className:G.configured?"text-green-400":"text-amber-400",children:G.configured?E("repoMesh.nodeList.launchReadyYes"):E("repoMesh.nodeList.launchReadyNo")})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.repoRoot")})," ",s.jsx("span",{className:"font-mono break-all",children:I.repoRoot||I.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.activeSessionsLabel")})," ",Z.length]}),i.addNodeDaemonPicker&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.added")})," ",new Date(I.created_at||I.createdAt||Date.now()).toLocaleDateString()]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:E("repoMesh.nodeList.activeQueueAssignments")}),Y.length===0?s.jsx("div",{children:E("repoMesh.nodeList.noActiveAssignment")}):s.jsx("ul",{className:"m-0 pl-4",children:Y.map(ae=>s.jsx("li",{className:"font-mono",children:VM(ae)},ae.id))})]}),Z.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:E("repoMesh.nodeList.activeSessions")}),s.jsx("ul",{className:"m-0 pl-4",children:Z.map(ae=>s.jsxs("li",{className:"font-mono",children:[ae.provider," / ",ae.status," / ",ae.id]},ae.id))})]})]})]})]},I.id)})})]})}function Hr(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function eA({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:n,coordinatorCliType:r,onCoordinatorCliTypeChange:a,launchingCoordinator:o,launchResult:i,isHostNodeAttached:u,selectedHostNode:c,hostPinned:p,hostLabel:d,hostOnline:m,hostRebindDaemonId:h,onHostRebindDaemonIdChange:g,onLaunchCoordinator:v}){const{t:f}=Xe("common"),y=s.jsx(St,{label:f("repoMesh.host.coordinatorProvider"),hint:f("repoMesh.host.coordinatorProviderHint"),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:w=>a(w.target.value),children:[s.jsx("option",{value:"",children:f("repoMesh.host.useNodePriority")}),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"})]})}),j=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(xt,{title:f("repoMesh.host.title"),description:f("repoMesh.host.descriptionSet"),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:f("repoMesh.host.hostLabel")}),s.jsx("span",{className:"font-medium",children:d||f("repoMesh.host.unknown")}),s.jsxs("span",{className:m?"text-text-muted":"text-amber-400",children:["· ",f(m?"repoMesh.host.online":"repoMesh.host.offline")]})]}),(c==null?void 0:c.workspace)&&s.jsxs("span",{className:"text-[12px] text-text-muted",children:[f("repoMesh.host.hostNode")," ",s.jsx("span",{className:"font-mono text-text-secondary",children:c.workspace})]})]}),!m&&s.jsxs("div",{className:"mt-4",children:[s.jsxs(Kt,{variant:"warning",className:"mb-3",children:[s.jsx("strong",{children:f("repoMesh.host.hostOffline")})," ",f("repoMesh.host.hostOfflineText")]}),e.length>0?s.jsx(St,{label:f("repoMesh.host.reconnectToCommand"),hint:f("repoMesh.host.reconnectToCommandHint"),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:w=>g(w.target.value),children:[s.jsx("option",{value:"",children:f("repoMesh.host.waitForHost")}),e.map(w=>s.jsx("option",{value:w.id,children:Hr(w)},w.id))]})}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:f("repoMesh.host.noDaemonsToRoute")})]}),s.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-[180px_auto] items-end",children:[y,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:v,disabled:o||!t,title:t?void 0:f("repoMesh.host.noCommandTarget"),children:f(o?"repoMesh.host.launching":"repoMesh.host.launchHost")})]}),j]});const x=e.find(w=>w.id===t);return s.jsxs(xt,{title:f("repoMesh.host.title"),description:f("repoMesh.host.descriptionUnset"),children:[s.jsxs(Kt,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:f("repoMesh.host.setHostBanner")})," ",f("repoMesh.host.setHostBannerText")]}),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:u?s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:Hr(x)}),c!=null&&c.workspace?s.jsxs(s.Fragment,{children:[" · setup node ",s.jsx("span",{className:"font-mono text-text-secondary",children:c.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:Hr(x)}),". Attach one of its workspaces as a node first, then launch to set the host."]})}):s.jsx(St,{label:f("repoMesh.host.hostDaemon"),hint:f("repoMesh.host.hostDaemonHint"),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:w=>n(w.target.value),children:[s.jsx("option",{value:"",children:f("repoMesh.host.resolvingHost")}),e.map(w=>s.jsx("option",{value:w.id,children:Hr(w)},w.id))]})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-[180px_auto] items-end mt-3",children:[y,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:v,disabled:!t||!u||o,title:t?u?void 0:f("repoMesh.host.attachNodeFirst"):f("repoMesh.host.pickHostFirst"),children:f(o?"repoMesh.host.launching":"repoMesh.host.launchHostSetsHost")})]})]}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:f("repoMesh.host.noDaemonsToHost")}),j]})}function tA({meshId:e,availableCliAgents:t}){const{t:n}=Xe(),r=t.find(o=>{const i=o.id.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||o.name.toLowerCase().includes("hermes")}),a=Gp(r==null?void 0:r.meshCoordinator,{meshId:e});return a?s.jsx(xt,{title:n("repoMesh.hermesMcp.title"),description:n("repoMesh.hermesMcp.description"),children:s.jsx(fh,{setup:a,providerName:(r==null?void 0:r.name)||n("repoMesh.hermesMcp.fallbackProvider")})}):null}const Eo=[{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."}],sA=[{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 nA(e){return e==="smart"?"fitness":e==="spread"?"least_loaded":"first_eligible"}function rA(e,t){const n=e||"first_eligible";return n==="fitness"?"smart":n==="first_eligible"?"in_order":n==="priority_only"?t!=null&&t.priorityConfigured?"spread":"in_order":n==="least_loaded"||n==="round_robin"?"spread":"in_order"}const aA={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function gi(e){return{...aA,...(e==null?void 0:e.policy)||{}}}function oA(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 iA({selectedMesh:e,error:t,onDismissError:n,onBack:r,onDelete:a,displayedMeshStatus:o,graphLoading:i,graphError:u,onRefreshGraph:c,savingPolicy:p,onUpdatePolicy:d,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:h,savingCoordinatorPrompt:g,onSaveCoordinatorPrompt:v,daemons:f,coordinatorDaemonId:y,onCoordinatorDaemonIdChange:j,coordinatorCliType:x,onCoordinatorCliTypeChange:w,launchingCoordinator:N,launchResult:k,isHostNodeAttached:b,selectedHostNode:C,hostPinned:S,hostLabel:M,hostOnline:A,hostRebindDaemonId:T,onHostRebindDaemonIdChange:L,onLaunchCoordinator:P,activeDaemon:B,activeDaemonId:z,meshQueue:R,userName:_,availableCliProviders:K,savingNodeSlotsId:E,onUpdateNodeSlots:D,savingNodeCapabilitiesId:$,onUpdateNodeCapabilities:I,nodeSystemPromptDrafts:G,onNodeSystemPromptDraftChange:Y,savingNodeSystemPromptId:Z,onSaveNodeSystemPrompt:q,selectedNodeId:ne,onSelectNode:ue,showAddNode:ae,onShowAddNode:O,onCancelAddNode:se,nodeWorkspace:X,onNodeWorkspaceChange:oe,nodeProviderPriority:Se,onNodeProviderPriorityChange:ye,nodeDaemonId:ke,onNodeDaemonIdChange:me,nodeCustomPath:U,onNodeCustomPathChange:W,nodePickerWorkspaces:Q,nodePickerProviders:V,attachableDaemons:fe,onAddNode:ce,onRemoveNode:F,availableCliAgents:le,features:je,sendCommand:de}){var Fe;const{t:H}=Xe("common"),be=gi(e),Ne=e.nodes||[],Ce=Ne.some(Ie=>{var Oe;const ve=Number((Oe=Ie.policy)==null?void 0:Oe.schedulingPriority);return Number.isFinite(ve)&&ve!==0}),$e=!be.schedulingStrategy,Qe=l.useMemo(()=>Ne.some(Ie=>{var ve;return Array.isArray((ve=Ie.policy)==null?void 0:ve.slots)&&Ie.policy.slots.length>0}),[Ne]),dt=$e?Qe?"smart":Ne.length>=2?"spread":null:null,[it,he]=l.useState(!1),Ee=!!z&&!!e.id;return s.jsxs(br,{icon:s.jsx(es,{}),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:r,children:H("repoMesh.detail.back")}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>c(!0),disabled:i,children:[s.jsx(fM,{size:13}),H(i?"repoMesh.detail.probing":"repoMesh.detail.refresh")]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>a(e.id),children:H("repoMesh.detail.delete")})]}),children:[t&&s.jsx(Kt,{variant:"error",onDismiss:n,className:"mb-4",children:t}),je.meshHostDaemonSection&&s.jsx(eA,{daemons:f,coordinatorDaemonId:y,onCoordinatorDaemonIdChange:j,coordinatorCliType:x,onCoordinatorCliTypeChange:w,launchingCoordinator:N,launchResult:k,isHostNodeAttached:b,selectedHostNode:C,hostPinned:S,hostLabel:M,hostOnline:A,hostRebindDaemonId:T,onHostRebindDaemonIdChange:Ie=>{L(Ie),c()},onLaunchCoordinator:P}),s.jsxs(xt,{title:H("repoMesh.detail.observabilityTitle"),description:H("repoMesh.detail.observabilityDescription"),children:[u&&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:u}),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:()=>he(!0),disabled:!Ee,title:H(Ee?"repoMesh.detail.observabilityOpenTitle":"repoMesh.detail.observabilityDisabledTitle"),children:[s.jsx(es,{size:14}),H("repoMesh.detail.observabilityOpen")]}),s.jsx("span",{className:"text-[12px] text-text-muted",children:H("repoMesh.detail.observabilityHint")})]})]}),s.jsx(ZM,{nodes:Ne,meshQueue:R,activeDaemon:B,daemons:f,selectedMeshId:e.id,userName:_,features:{addNodeDaemonPicker:je.addNodeDaemonPicker,nodeInstruction:je.nodeInstruction},coordinatorDaemonId:y,availableCliProviders:K,savingNodeSlotsId:E,onUpdateNodeSlots:D,savingNodeCapabilitiesId:$,onUpdateNodeCapabilities:I,nodeSystemPromptDrafts:G,onNodeSystemPromptDraftChange:Y,savingNodeSystemPromptId:Z,onSaveNodeSystemPrompt:q,selectedNodeId:ne,onSelectNode:ue,showAddNode:ae,onShowAddNode:O,onCancelAddNode:se,nodeWorkspace:X,onNodeWorkspaceChange:oe,nodeProviderPriority:Se,onNodeProviderPriorityChange:ye,nodeDaemonId:ke,onNodeDaemonIdChange:me,nodeCustomPath:U,onNodeCustomPathChange:W,nodePickerWorkspaces:Q,nodePickerProviders:V,attachableDaemons:fe,onAddNode:ce,onRemoveNode:F}),s.jsxs(xt,{title:H("repoMesh.detail.schedulingTitle"),description:H("repoMesh.detail.schedulingDescription"),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:H("repoMesh.detail.distribution")}),s.jsx("div",{className:"flex flex-col gap-2",children:sA.map(Ie=>{const Oe=rA(be.schedulingStrategy,{priorityConfigured:Ce})===Ie.value;return s.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${Oe?"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:Ie.value,checked:Oe,disabled:p,onChange:()=>d({schedulingStrategy:nA(Ie.value)})}),s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-primary",children:[Ie.label,dt===Ie.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:H("repoMesh.detail.recommended")})]}),s.jsx("span",{className:"block text-[12px] text-text-muted",children:Ie.description})]})]},Ie.value)})})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:H("repoMesh.detail.saving")})]}),s.jsx(xt,{title:H("repoMesh.detail.visibilityTitle"),description:H("repoMesh.detail.visibilityDescription"),children:s.jsx(St,{label:H("repoMesh.detail.visibilityLabel"),hint:H("repoMesh.detail.visibilityHint"),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:be.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:Ie=>d({spawnedSessionVisibility:Ie.target.value==="visible"?"visible":"hidden"}),disabled:p,children:[s.jsx("option",{value:"hidden",children:H("repoMesh.detail.visibilityHidden")}),s.jsx("option",{value:"visible",children:H("repoMesh.detail.visibilityVisible")})]})})}),o&&s.jsx(xt,{title:H("repoMesh.detail.magiTitle"),description:H("repoMesh.detail.magiDescription"),children:s.jsx(MM,{status:o,daemonId:z,sendDaemonCommand:de,availableProviders:K})}),s.jsx(_M,{status:o,daemonId:z,meshId:e.id,sendCommand:de}),je.coordinatorPrompt&&s.jsxs(xt,{title:H("repoMesh.detail.coordinatorPromptTitle"),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:H("repoMesh.detail.advanced")}),description:H("repoMesh.detail.coordinatorPromptDescription"),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:H("repoMesh.detail.thisMesh")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:H("repoMesh.detail.thisMeshHint",{name:e.name})}),s.jsxs(St,{label:H("repoMesh.detail.overrideLabel"),hint:H("repoMesh.detail.overrideHint"),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:Ie=>h({...m,override:Ie.target.value}),disabled:g,placeholder:H("repoMesh.detail.overridePlaceholder")}),s.jsx(AM,{daemonId:z,meshId:e.id,cliType:x,sendCommand:de})]}),s.jsx(St,{label:H("repoMesh.detail.appendLabel"),hint:H("repoMesh.detail.appendHint"),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:Ie=>h({...m,append:Ie.target.value}),disabled:g,placeholder:H("repoMesh.detail.appendPlaceholder")})}),s.jsxs("details",{className:"mt-2 text-[12px] text-text-muted",children:[s.jsx("summary",{className:"cursor-pointer select-none",children:H("repoMesh.detail.availablePlaceholders")}),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:v,disabled:g,children:H(g?"repoMesh.detail.saving":"repoMesh.detail.saveCoordinatorPrompt")}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>h({override:"",append:""}),disabled:g,title:H("repoMesh.detail.clearTitle"),children:H("repoMesh.detail.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:H("repoMesh.detail.userLevel")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:H("repoMesh.detail.userLevelDescription")}),s.jsx(Qw,{daemonId:z||void 0})]})]}),s.jsxs(xt,{title:H("repoMesh.detail.safetyTitle"),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:H("repoMesh.detail.advanced")}),description:H("repoMesh.detail.safetyDescription"),children:[s.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:H("repoMesh.detail.checkpointBefore"),key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:Ie=>Ie?"yes":"no",parse:Ie=>Ie==="yes"},{label:H("repoMesh.detail.checkpointAfter"),key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:Ie=>Ie?"yes":"no",parse:Ie=>Ie==="yes"},{label:H("repoMesh.detail.pushApproval"),key:"requireApprovalForPush",opts:[["required",H("repoMesh.detail.requireApprovalBeforePush")],["not_required",H("repoMesh.detail.doNotRequireApproval")]],val:Ie=>Ie?"required":"not_required",parse:Ie=>Ie==="required"},{label:H("repoMesh.detail.destructiveGitApproval"),key:"requireApprovalForDestructiveGit",opts:[["required",H("repoMesh.detail.requireApproval")],["not_required",H("repoMesh.detail.doNotRequireApproval")]],val:Ie=>Ie?"required":"not_required",parse:Ie=>Ie==="required"},{label:H("repoMesh.detail.uncommittedChanges"),key:"dirtyWorkspaceBehavior",opts:[["warn",H("repoMesh.detail.warnAndContinue")],["block",H("repoMesh.detail.blockTask")],["checkpoint_then_continue",H("repoMesh.detail.checkpointThenContinue")]],val:Ie=>Ie||"warn",parse:Ie=>Ie},{label:H("repoMesh.detail.autoPublishSubmodule"),key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled",H("repoMesh.detail.requireExplicitApproval")],["enabled",H("repoMesh.detail.allowRefineryPublish")]],val:Ie=>Ie?"enabled":"disabled",parse:Ie=>Ie==="enabled"}].map(({label:Ie,key:ve,opts:Oe,val:ut,parse:ot})=>s.jsx(St,{label:Ie,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:ut(be[ve]),onChange:pt=>d({[ve]:ot(pt.target.value)}),disabled:p,children:Oe.map(([pt,J])=>s.jsx("option",{value:pt,children:J},pt))})},ve))}),(()=>{const Ie=be.autoFastForward&&typeof be.autoFastForward=="object"?be.autoFastForward:{},ve=Ie.enabled!==!1,Oe=Ie.remoteNodes===!0,ut=Ie.mode==="continuous"?"continuous":"idle",ot=pt=>d({autoFastForward:{...Ie,...pt}});return s.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[s.jsx(St,{label:H("repoMesh.detail.autoFastForward"),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:ve?"enabled":"disabled",onChange:pt=>ot({enabled:pt.target.value==="enabled"}),disabled:p,children:[s.jsx("option",{value:"enabled",children:H("repoMesh.detail.ffEnabled")}),s.jsx("option",{value:"disabled",children:H("repoMesh.detail.ffDisabled")})]})}),s.jsx(St,{label:H("repoMesh.detail.includeRemoteNodes"),hint:H("repoMesh.detail.includeRemoteNodesHint"),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:Oe?"yes":"no",onChange:pt=>ot({remoteNodes:pt.target.value==="yes"}),disabled:p||!ve,children:[s.jsx("option",{value:"no",children:H("repoMesh.detail.remoteNo")}),s.jsx("option",{value:"yes",children:H("repoMesh.detail.remoteYes")})]})}),s.jsx(St,{label:H("repoMesh.detail.detectionMode"),hint:H("repoMesh.detail.detectionModeHint"),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:ut,onChange:pt=>ot({mode:pt.target.value==="continuous"?"continuous":"idle"}),disabled:p||!ve||!Oe,children:[s.jsx("option",{value:"idle",children:H("repoMesh.detail.idleEdgeOnly")}),s.jsx("option",{value:"continuous",children:H("repoMesh.detail.continuousScan")})]})})]})})(),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(St,{label:H("repoMesh.detail.sessionCleanupLabel"),hint:H("repoMesh.detail.sessionCleanupHint"),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:be.sessionCleanupOnNodeRemove||"preserve",onChange:Ie=>d({sessionCleanupOnNodeRemove:Ie.target.value}),disabled:p,children:Eo.map(Ie=>s.jsx("option",{value:Ie.value,children:Ie.label},Ie.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((Fe=Eo.find(Ie=>Ie.value===be.sessionCleanupOnNodeRemove))==null?void 0:Fe.description)||Eo[0].description})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:H("repoMesh.detail.saving")})]}),je.hermesMcpConfig&&s.jsx(tA,{meshId:e.id,availableCliAgents:le}),je.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."]}),it&&Ee&&s.jsx(Vh,{activeConv:oA({meshId:e.id,daemonId:z,meshName:e.name}),sendDaemonCommand:de,onClose:()=>he(!1)})]})}const Un=new Map;function lA({daemons:e,primaryDaemonId:t,sendCommand:n,unwrapResult:r,normalizeMesh:a,features:o,loadDaemonMetadata:i}){const u=e.map(D=>D.id).filter(Boolean).sort().join(","),[c,p]=l.useState(()=>Un.get(u)??[]),[d,m]=l.useState(null),[h,g]=l.useState(()=>!Un.has(u)),[v,f]=l.useState(null),[y,j]=l.useState(!1),[x,w]=l.useState(""),[N,k]=l.useState(""),[b,C]=l.useState(""),[S,M]=l.useState(""),[A,T]=l.useState(""),L=l.useMemo(()=>e.find(D=>D.id===S),[e,S]),P=(L==null?void 0:L.workspaces)||[],B=l.useMemo(()=>wn((L==null?void 0:L.availableProviders)||[]),[L]);l.useEffect(()=>{!o.createDaemonPicker||!i||!S||!L||!(!L.workspaces||!L.availableProviders)||Promise.resolve(i(S,{minFreshMs:3e4})).catch(()=>{})},[o.createDaemonPicker,i,S,L]);const z=l.useMemo(()=>e.map(D=>D.id).filter(Boolean).sort().join(","),[e]),R=l.useCallback(async(D=!1)=>{const $=D||Un.has(z);g(I=>$?I:!0);try{if(o.createDaemonPicker){const I=await Promise.allSettled(e.map(async Z=>{if(!Z.id)return[];const q=await n(Z.id,"list_meshes",{}),ne=r(q);if((ne==null?void 0:ne.success)===!1)throw new Error(ne.error||"Failed to load meshes");return(Array.isArray(ne==null?void 0:ne.meshes)?ne.meshes:[]).map(ue=>a(ue,Z.id)).filter(ue=>ue.id)})),G=new Map;for(const Z of I)if(Z.status==="fulfilled")for(const q of Z.value)G.has(q.id)||G.set(q.id,q);const Y=Array.from(G.values());p(Y),Un.set(z,Y),f(null)}else{if(!t)return;const I=await n(t,"list_meshes");if(I!=null&&I.success){const G=(I.meshes||[]).map(Y=>a(Y,t));p(G),Un.set(z,G),f(null)}else f((I==null?void 0:I.error)||"Failed to load meshes")}}catch(I){f((I==null?void 0:I.message)||"Failed to load meshes")}finally{g(!1)}},[z,t,n,r,a,o.createDaemonPicker]);async function _(){var G,Y;const D=o.createDaemonPicker?S:t;if(!D||!x.trim())return;const $=b.trim(),I=N.trim();if(!(!$&&!I))try{const Z={name:x.trim()};$&&(Z.repoRemoteUrl=$),I&&(Z.repoIdentity=I);const q=await n(D,"create_mesh",Z),ne=r(q);if((ne==null?void 0:ne.success)===!1)throw new Error(ne.error||"Create failed");const ue=typeof((G=ne==null?void 0:ne.mesh)==null?void 0:G.id)=="string"?ne.mesh.id:"";if(ue&&o.createDaemonPicker&&A){const ae=await n(D,"add_mesh_node",{meshId:ue,daemonId:D,machineId:L==null?void 0:L.machineId,workspace:A,role:"host",providerPriority:cr(B)}),O=r(ae);if((O==null?void 0:O.success)===!1)throw new Error(O.error||"Mesh created but failed to attach workspace")}j(!1),w(""),k(""),C(""),T(""),await R(),(Y=ne==null?void 0:ne.mesh)!=null&&Y.id&&m(ne.mesh.id)}catch(Z){f((Z==null?void 0:Z.message)||"Create failed")}}async function K(D){var I;if(!confirm("Delete this mesh? This cannot be undone."))return;const $=((I=c.find(G=>G.id===D))==null?void 0:I.__sourceDaemonId)||t;try{const G=await n($,"delete_mesh",{meshId:D}),Y=r(G);if((Y==null?void 0:Y.success)===!1)throw new Error(Y.error||"Failed to delete");d===D&&m(null),await R()}catch(G){f((G==null?void 0:G.message)||"Delete failed")}}function E(){j(!1),w(""),k(""),C("")}return{meshes:c,setMeshes:p,selectedMeshId:d,setSelectedMeshId:m,loading:h,error:v,setError:f,showCreate:y,setShowCreate:j,createName:x,setCreateName:w,createRepoIdentity:N,setCreateRepoIdentity:k,createRepoRemoteUrl:b,setCreateRepoRemoteUrl:C,newMeshDaemonId:S,setNewMeshDaemonId:M,newMeshWorkspace:A,setNewMeshWorkspace:T,createPickerWorkspaces:P,createPickerProviders:B,loadMeshes:R,handleCreate:_,handleDelete:K,cancelCreate:E}}function cA({selectedMesh:e,selectedMeshId:t,primaryDaemonId:n,activeDaemonId:r,daemons:a,sendCommand:o,unwrapResult:i,loadLiveMesh:u,resolveCommandTarget:c,launchCoordinator:p,features:d,loadMeshes:m,loadQueue:h,queueSection:g,setError:v}){const[f,y]=l.useState({}),[j,x]=l.useState(null),[w,N]=l.useState(null),[k,b]=l.useState(!1),[C,S]=l.useState(""),[M,A]=l.useState([]),[T,L]=l.useState(""),[P,B]=l.useState(!1),[z,R]=l.useState(""),[_,K]=l.useState(!1),[E,D]=l.useState(null),[$,I]=l.useState(!1),[G,Y]=l.useState({override:"",append:""}),[Z,q]=l.useState(!1),[ne,ue]=l.useState({}),[ae,O]=l.useState(null),se=l.useMemo(()=>a.find(de=>de.id===T),[a,T]),X=(se==null?void 0:se.workspaces)||[],oe=l.useMemo(()=>wn((se==null?void 0:se.availableProviders)||[]),[se]);async function Se(){const de=(e==null?void 0:e.__sourceDaemonId)||n;if(!t||!de)return;const H=C.trim();if(H)try{const be={meshId:t,workspace:H};d.addNodeDaemonPicker&&T&&(be.daemonId=T,be.machineId=se==null?void 0:se.machineId),be.providerPriority=kn(M);const Ne=await o(de,"add_mesh_node",be),Ce=i(Ne);if((Ce==null?void 0:Ce.success)===!1)throw new Error(Ce.error||"Add node failed");b(!1),S(""),A([]),L(""),B(!1),await m(),g||await h(t)}catch(be){v((be==null?void 0:be.message)||"Add node failed")}}async function ye(de){var Ce;if(!e)return;const H=gi(e),be=((Ce=[{value:"preserve",label:"Preserve history and runtimes"},{value:"stop",label:"Stop live runtimes only"},{value:"delete_stopped",label:"Delete stopped sessions only"},{value:"stop_and_delete",label:"Stop and delete sessions"}].find($e=>$e.value===H.sessionCleanupOnNodeRemove))==null?void 0:Ce.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
115
-
116
- Node removal cleanup policy: ${be}`))return;const Ne=e.__sourceDaemonId||n;try{const $e=await o(Ne,"remove_mesh_node",{meshId:e.id,nodeId:de}),Qe=i($e);if((Qe==null?void 0:Qe.success)===!1)throw new Error(Qe.error||"Remove failed");w===de&&N(null),await m(),g||await h(t)}catch($e){v(($e==null?void 0:$e.message)||"Remove node failed")}}async function ke(de){if(!e)return;const H={...gi(e),...de},be=e.__sourceDaemonId||n;try{I(!0),v(null);const Ne=await o(be,"update_mesh",{meshId:e.id,policy:H}),Ce=i(Ne);if((Ce==null?void 0:Ce.success)===!1)throw new Error(Ce.error||"Policy update failed");await m()}catch(Ne){v((Ne==null?void 0:Ne.message)||"Policy update failed")}finally{I(!1)}}async function me(de){if(!t)return;const H=(e==null?void 0:e.__sourceDaemonId)||n,be=f[de.id]||dA(de),Ne=kn(be),Ce={...de.policy||{}};delete Ce.provider_priority,Ne.length?Ce.providerPriority=Ne:delete Ce.providerPriority;try{x(de.id),v(null);const $e=await o(H,"update_mesh_node",{meshId:t,nodeId:de.id,policy:Ce,providerPriority:Ne}),Qe=i($e);if((Qe==null?void 0:Qe.success)===!1){v(Qe.error||"Node policy update failed");return}await m()}catch($e){v(($e==null?void 0:$e.message)||"Node policy update failed")}finally{x(null)}}const[U,W]=l.useState(null);async function Q(de,H){if(!t)return;const be=(e==null?void 0:e.__sourceDaemonId)||n;try{W(de.id),v(null);const Ne=await o(be,"update_mesh_node",{meshId:t,nodeId:de.id,policy:{slots:H}}),Ce=i(Ne);if((Ce==null?void 0:Ce.success)===!1){v(Ce.error||"Node slots update failed");return}await m()}catch(Ne){v((Ne==null?void 0:Ne.message)||"Node slots update failed")}finally{W(null)}}const[V,fe]=l.useState(null);async function ce(de,H){if(!t)return;const be=(e==null?void 0:e.__sourceDaemonId)||n,Ne=H.map(Ce=>Ce.trim()).filter(Boolean);try{fe(de.id),v(null);const Ce=await o(be,"update_mesh_node",{meshId:t,nodeId:de.id,capabilities:Ne}),$e=i(Ce);if(($e==null?void 0:$e.success)===!1){v($e.error||"Node tag update failed");return}await m()}catch(Ce){v((Ce==null?void 0:Ce.message)||"Node tag update failed")}finally{fe(null)}}async function F(){if(!n||!t)return;const H={...(e==null?void 0:e.coordinator)||{}};G.override.trim()?H.systemPromptOverride=G.override:delete H.systemPromptOverride,G.append.trim()?H.systemPromptAppend=G.append:delete H.systemPromptAppend,delete H.systemPromptSuffix;try{q(!0),v(null);const be=await o(n,"update_mesh",{meshId:t,coordinator:H}),Ne=i(be);if((Ne==null?void 0:Ne.success)===!1){v(Ne.error||"Coordinator prompt save failed");return}await m()}catch(be){v((be==null?void 0:be.message)||"Coordinator prompt save failed")}finally{q(!1)}}async function le(de){if(!n||!t)return;const H=(ne[de.id]||"").trim();try{O(de.id),v(null);const be=await o(n,"update_mesh_node",{meshId:t,nodeId:de.id,systemPrompt:H}),Ne=i(be);if((Ne==null?void 0:Ne.success)===!1){v(Ne.error||"Node instruction save failed");return}await m()}catch(be){v((be==null?void 0:be.message)||"Node instruction save failed")}finally{O(null)}}async function je(){if(e){v(null),D(null);try{K(!0);const de=u?await u(r,e.id,e):null,H=c(r,e.id,e,e.nodes||[],de);if("error"in H)throw new Error(H.error);const be=await p(H.targetDaemonId,{meshId:e.id,inlineMesh:H.inlineMesh,coordinatorNodeId:H.coordinatorNodeId,cliType:z.trim()||void 0});D(be.message)}catch(de){v((de==null?void 0:de.message)||"Coordinator launch failed")}finally{K(!1)}}}return{nodeProviderPriorityDrafts:f,setNodeProviderPriorityDrafts:y,savingNodePolicyId:j,selectedNodeId:w,setSelectedNodeId:N,showAddNode:k,setShowAddNode:b,nodeWorkspace:C,setNodeWorkspace:S,nodeProviderPriority:M,setNodeProviderPriority:A,nodeDaemonId:T,setNodeDaemonId:L,nodeCustomPath:P,setNodeCustomPath:B,nodePickerWorkspaces:X,nodePickerProviders:oe,coordinatorCliType:z,setCoordinatorCliType:R,launchingCoordinator:_,launchResult:E,savingPolicy:$,coordinatorPromptDraft:G,setCoordinatorPromptDraft:Y,savingCoordinatorPrompt:Z,nodeSystemPromptDrafts:ne,setNodeSystemPromptDrafts:ue,savingNodeSystemPromptId:ae,savingNodeSlotsId:U,savingNodeCapabilitiesId:V,handleAddNode:Se,handleRemoveNode:ye,handleUpdatePolicy:ke,handleUpdateNodeProviderPriority:me,handleUpdateNodeSlots:Q,handleUpdateNodeCapabilities:ce,handleSaveCoordinatorPrompt:F,handleSaveNodeSystemPrompt:le,handleLaunchCoordinator:je}}function dA(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>n.has(a)?!1:(n.add(a),!0))}function uA(e){const t=e.filter(r=>r.status==="pending"||r.status==="assigned"),n=e.filter(r=>r.status==="completed"||r.status==="failed"||r.status==="cancelled");return{active:t.length,historical:n.length,activeCounts:{pending:t.filter(r=>r.status==="pending").length,assigned:t.filter(r=>r.status==="assigned").length},historicalCounts:{completed:n.filter(r=>r.status==="completed").length,failed:n.filter(r=>r.status==="failed").length},counts:{pending:e.filter(r=>r.status==="pending").length,assigned:e.filter(r=>r.status==="assigned").length,completed:e.filter(r=>r.status==="completed").length,failed:e.filter(r=>r.status==="failed").length},staleAssignedCount:e.filter(r=>r.staleAssigned).length,recent:e.slice(0,20)}}function pA({primaryDaemonId:e,activeDaemonId:t,sendCommand:n,unwrapResult:r,loadLiveMesh:a,resolveCommandTarget:o}){const[i,u]=l.useState([]),[c,p]=l.useState(null),[d,m]=l.useState(!1),[h,g]=l.useState(null),v=l.useCallback(async y=>{if(!e||!y){u([]);return}try{const j=await n(e,"get_mesh_queue",{meshId:y});u(j!=null&&j.success?Array.isArray(j.queue)?j.queue:[]:[])}catch{u([])}},[e,n]);async function f(y){var j,x;if(y){m(!0),g(null);try{const w=a?await a(t,y.id,y):null,N=o(t,y.id,y,y.nodes||[],w);if("error"in N)throw new Error(N.error);const k=await n(N.targetDaemonId,"get_mesh_queue",{meshId:y.id}),b=r(k);if((b==null?void 0:b.success)===!1)throw new Error(b.error||"Queue load failed");const C=Array.isArray(((j=b==null?void 0:b.result)==null?void 0:j.rows)??(b==null?void 0:b.rows)??(b==null?void 0:b.queue))?((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(uA(C))}catch(w){g((w==null?void 0:w.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:u,queueSummary:c,queueLoading:d,queueError:h,loadQueue:v,handleLoadQueue:f}}function hA(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const Zh=new Map;function em(e){return e?Zh.get(e)??null:null}function mA(e,t){!e||!t||Zh.set(e,t)}function fA({selectedMeshId:e,loadMeshStatus:t,extractStatus:n,normalizeNode:r,gateIncompleteGraph:a}){const[o,i]=l.useState(()=>em(e)),[u,c]=l.useState(!1),[p,d]=l.useState(null),[m,h]=l.useState("idle"),[g,v]=l.useState(!1),f=l.useRef(!1);async function y(j,x=e,w=!1){if(!(!j||!x))try{c(!w&&o===null),h(w?"settling":"first_paint"),d(null);const N=await t(j,x,{refresh:w,retryProfile:w?"settled":"interactive"});v(hA(N));const k=n(N),b=r&&k?{...k,nodes:(k.nodes??[]).map(C=>r(C,k.meshId??x,""))}:k;if(b){if(a&&!w&&o!==null&&!LN(Th(b))){h("settling"),f.current||(f.current=!0,Promise.resolve().then(()=>y(j,x,!0)).finally(()=>{f.current=!1}));return}i(b),mA(x,b),h("settled")}else i(null),d("mesh_status returned an unexpected payload."),h("idle")}catch(N){o||i(null),d((N==null?void 0:N.message)||"Failed to load mesh graph"),h("idle")}finally{c(!1)}}return{meshGraphStatus:o,setMeshGraphStatus:i,graphLoading:u,graphError:p,setGraphError:d,graphProvenance:m,graphBootstrapFallback:g,loadGraph:y}}function xA(e,t,n,r,a){if(!e.length)return"";const o=String(a||"");if(o){const c=e.find(p=>Os(p.id,o));return c?c.id:o}const i=t.find(c=>c.role==="host"),u=String((i==null?void 0:i.daemon_id)||(i==null?void 0:i.daemonId)||"");if(u){const c=e.find(p=>Os(p.id,u));if(c)return c.id}return""}const bA=7e3,gA=45e3;function yA(){const e=mM(),{sendCommand:t,sendData:n,daemons:r,userName:a,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:u,extractStatus:c,unwrapResult:p,normalizeMesh:d,normalizeNode:m,resolveCommandTarget:h,features:g,gateIncompleteGraph:v}=e,f=In(),y=r[0],j=(y==null?void 0:y.id)||"",x=l.useMemo(()=>((y==null?void 0:y.availableProviders)||[]).filter(rt=>rt.category==="cli").map(rt=>({id:rt.type||rt.id,name:rt.displayName||rt.name||rt.type,meshCoordinator:rt.meshCoordinator})),[y]),w=l.useMemo(()=>wn((y==null?void 0:y.availableProviders)||[]),[y]),{meshes:N,selectedMeshId:k,setSelectedMeshId:b,loading:C,error:S,setError:M,showCreate:A,setShowCreate:T,createName:L,setCreateName:P,createRepoIdentity:B,setCreateRepoIdentity:z,createRepoRemoteUrl:R,setCreateRepoRemoteUrl:_,newMeshDaemonId:K,setNewMeshDaemonId:E,newMeshWorkspace:D,setNewMeshWorkspace:$,createPickerWorkspaces:I,loadMeshes:G,handleCreate:Y,handleDelete:Z,cancelCreate:q}=lA({daemons:r,primaryDaemonId:j,sendCommand:t,unwrapResult:p,normalizeMesh:d,features:g,loadDaemonMetadata:f}),ne=N.find(Le=>Le.id===k)||null,{meshGraphStatus:ue,setMeshGraphStatus:ae,graphLoading:O,graphError:se,setGraphError:X,loadGraph:oe}=fA({selectedMeshId:k,loadMeshStatus:o,extractStatus:c,normalizeNode:m,gateIncompleteGraph:v}),[Se,ye]=l.useState(""),[ke,me]=l.useState(""),U=g.meshHostDaemonSection&&Se||j,{meshQueue:W,loadQueue:Q}=pA({primaryDaemonId:j,activeDaemonId:U,sendCommand:t,unwrapResult:p,loadLiveMesh:u,resolveCommandTarget:h}),{setNodeProviderPriorityDrafts:V,selectedNodeId:fe,setSelectedNodeId:ce,showAddNode:F,setShowAddNode:le,nodeWorkspace:je,setNodeWorkspace:de,nodeProviderPriority:H,setNodeProviderPriority:be,nodeDaemonId:Ne,setNodeDaemonId:Ce,nodeCustomPath:$e,setNodeCustomPath:Qe,nodePickerWorkspaces:dt,nodePickerProviders:it,coordinatorCliType:he,setCoordinatorCliType:Ee,launchingCoordinator:Fe,launchResult:Ie,savingPolicy:ve,coordinatorPromptDraft:Oe,setCoordinatorPromptDraft:ut,savingCoordinatorPrompt:ot,nodeSystemPromptDrafts:pt,setNodeSystemPromptDrafts:J,savingNodeSystemPromptId:te,savingNodeSlotsId:ie,savingNodeCapabilitiesId:pe,handleAddNode:ge,handleRemoveNode:Ae,handleUpdatePolicy:De,handleUpdateNodeSlots:Me,handleUpdateNodeCapabilities:Be,handleSaveCoordinatorPrompt:We,handleSaveNodeSystemPrompt:Ze,handleLaunchCoordinator:_e}=cA({selectedMesh:ne,selectedMeshId:k,primaryDaemonId:j,activeDaemonId:U,daemons:r,availableCliProviders:w,sendCommand:t,unwrapResult:p,loadLiveMesh:u,resolveCommandTarget:h,launchCoordinator:i,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:G,loadQueue:Q,queueSection:g.queueSection,setError:M}),Ue=l.useMemo(()=>r.find(Le=>Le.id===U)||y,[r,U,y]),et=l.useMemo(()=>new Set(((ne==null?void 0:ne.nodes)||[]).map(Le=>String(Le.daemon_id||Le.daemonId||""))),[ne]),ee=l.useMemo(()=>r.filter(Le=>Le.id&&!et.has(Le.id)),[r,et]),xe=(ne==null?void 0:ne.nodes)||[],we=l.useMemo(()=>xe.find(Le=>Os(String(Le.daemon_id||Le.daemonId||""),Se)),[xe,Se]),Ge=g.meshHostDaemonSection?!!we:!0,He=l.useMemo(()=>{if(!g.meshHostDaemonSection||!ne)return{pinned:!1,daemonId:"",label:"",online:!1};const Le=ne.meshHost,rt=ue!=null&&ue.meshId&&String(ue.meshId)===String(ne.id??"")?ue.meshHost:void 0,Nt=rt!=null&&rt.hostDaemonId?rt:Le??rt,Wt=String((Nt==null?void 0:Nt.hostDaemonId)||""),re=xe.find(ys=>ys.role==="host"),Ke=String((Nt==null?void 0:Nt.hostNodeId)||(re==null?void 0:re.id)||""),Re=Ke?xe.find(ys=>String(ys.id)===Ke):void 0,vt=String((Re==null?void 0:Re.daemon_id)||(Re==null?void 0:Re.daemonId)||""),Jt=Wt||vt;if(!Jt)return{pinned:!1,daemonId:"",label:"",online:!1};const Tn=r.find(ys=>Wt&&Os(ys.id,Wt))||(vt?r.find(ys=>Os(ys.id,vt)):void 0);if(Tn)return{pinned:!0,daemonId:Tn.id,label:vA(Tn),online:!0};const Oa=String((Re==null?void 0:Re.machineLabel)||"")||String((Re==null?void 0:Re.workspace)||"")||Jt;return{pinned:!0,daemonId:Jt,label:Oa,online:!1}},[ne,xe,r,ue,g.meshHostDaemonSection]),tt=He.daemonId,ze=He.online,qe=l.useMemo(()=>!g.meshHostDaemonSection||!He.pinned?"":!ze&&ke&&r.some(Le=>Le.id===ke)?ke:tt,[g.meshHostDaemonSection,He.pinned,ze,ke,r,tt]),At=l.useMemo(()=>ue?[...new Set((ue.nodes??[]).map(Le=>String(Le.daemonId||Le.daemon_id||"")).filter(Boolean))]:[],[ue]),Ot=zh({status:ue,daemonId:U||null,extraDaemonIds:At,meshId:k,sendData:n});l.useEffect(()=>{V(Object.fromEntries(((ne==null?void 0:ne.nodes)||[]).map(Le=>[Le.id,wA(Le)])))},[ne]),l.useEffect(()=>{const Le=(ne==null?void 0:ne.coordinator)||{};ut({override:typeof Le.systemPromptOverride=="string"?Le.systemPromptOverride:"",append:typeof Le.systemPromptAppend=="string"?Le.systemPromptAppend:typeof Le.systemPromptSuffix=="string"?Le.systemPromptSuffix:""}),J(Object.fromEntries(((ne==null?void 0:ne.nodes)||[]).map(rt=>[rt.id,typeof rt.systemPrompt=="string"?rt.systemPrompt:""])))},[ne]),l.useEffect(()=>{const Le=g.addNodeDaemonPicker?cr(it):cr(w);F&&H.length===0&&Le.length>0&&be(Le)},[F,w,it,H.length,g.addNodeDaemonPicker]),l.useEffect(()=>{const Le=new Set(((ne==null?void 0:ne.nodes)||[]).map(rt=>rt.id));fe&&!Le.has(fe)&&ce(null)},[ne,fe]);const ss=l.useMemo(()=>{var Le;if(!(!(ue!=null&&ue.meshId)||String(ue.meshId)!==String((ne==null?void 0:ne.id)??"")))return(Le=ue.meshHost)==null?void 0:Le.hostDaemonId},[ue,ne]),Te=l.useMemo(()=>xA(r,xe,U,j,ss),[r,xe,U,j,ss]);l.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!r.length&&!He.pinned){ye("");return}const Le=He.pinned?qe:Te;Le&&!Os(Le,Se)&&ye(Le)},[r,Se,He.pinned,qe,Te,g.meshHostDaemonSection]),l.useEffect(()=>{ke&&(ze||!r.some(Le=>Le.id===ke))&&me("")},[ze,ke,r]),l.useEffect(()=>{if(g.createDaemonPicker){if(!r.length){E("");return}(!K||!r.some(Le=>Le.id===K))&&E(r[0].id)}},[r,K,g.createDaemonPicker]),l.useEffect(()=>{var Le;if(!g.createDaemonPicker||!K){$("");return}if(!I.length){$("");return}I.some(rt=>rt.path===D)||$(((Le=I[0])==null?void 0:Le.path)||"")},[K,D,I,g.createDaemonPicker]);const Je=l.useRef(null);l.useEffect(()=>{if(!k)return;const Le=Je.current!==k;if(Je.current=k,Le){const rt=em(k);ae(rt),X(null),oe(U,k,rt!==null)}else X(null),oe(U,k,!0)},[k,U]);const Pt=l.useRef(oe);Pt.current=oe;const It=l.useRef(!1),Vt=l.useRef(()=>{});Vt.current=()=>{It.current||!k||!U||(It.current=!0,Promise.resolve(Pt.current(U,k,!0)).finally(()=>{It.current=!1}))};const qt=g.meshStatePushRefresh?gA:bA;pM({daemonIds:l.useMemo(()=>[U,...At].filter(Boolean),[U,At]),meshId:k,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||Vt.current()}}),l.useEffect(()=>{if(!k||!U||typeof document>"u")return;let Le=null;const rt=()=>{document.visibilityState==="visible"&&Vt.current()},Nt=()=>{Le===null&&(Le=setInterval(rt,qt))},Wt=()=>{Le!==null&&(clearInterval(Le),Le=null)},re=()=>{document.visibilityState==="visible"?Nt():Wt()};return document.visibilityState==="visible"&&Nt(),document.addEventListener("visibilitychange",re),()=>{Wt(),document.removeEventListener("visibilitychange",re)}},[k,U,qt]),l.useEffect(()=>{g.queueSection||Q(k)},[k,g.queueSection]);const Yt=l.useMemo(()=>r.map(Le=>Le.id).filter(Boolean).sort().join(","),[r]),gs=l.useRef(!1);return l.useEffect(()=>{G(gs.current),gs.current=!0},[Yt]),j?ne?s.jsx(iA,{selectedMesh:ne,error:S,onDismissError:()=>M(null),onBack:()=>{b(null),ae(null)},onDelete:Z,displayedMeshStatus:Ot,graphLoading:O,graphError:se,onRefreshGraph:()=>oe(U,k,!0),savingPolicy:ve,onUpdatePolicy:De,coordinatorPromptDraft:Oe,onCoordinatorPromptDraftChange:ut,savingCoordinatorPrompt:ot,onSaveCoordinatorPrompt:We,daemons:r,coordinatorDaemonId:Se,onCoordinatorDaemonIdChange:ye,coordinatorCliType:he,onCoordinatorCliTypeChange:Ee,launchingCoordinator:Fe,launchResult:Ie,isHostNodeAttached:Ge,selectedHostNode:we,hostPinned:He.pinned,hostLabel:He.label,hostOnline:ze,hostRebindDaemonId:ke,onHostRebindDaemonIdChange:Le=>me(Le),onLaunchCoordinator:_e,activeDaemon:Ue,activeDaemonId:U,meshQueue:W,userName:a,availableCliProviders:w,savingNodeSlotsId:ie,onUpdateNodeSlots:Me,savingNodeCapabilitiesId:pe,onUpdateNodeCapabilities:Be,nodeSystemPromptDrafts:pt,onNodeSystemPromptDraftChange:(Le,rt)=>J(Nt=>({...Nt,[Le]:rt})),savingNodeSystemPromptId:te,onSaveNodeSystemPrompt:Ze,selectedNodeId:fe,onSelectNode:ce,showAddNode:F,onShowAddNode:()=>le(!0),onCancelAddNode:()=>le(!1),nodeWorkspace:je,onNodeWorkspaceChange:de,nodeProviderPriority:H,onNodeProviderPriorityChange:be,nodeDaemonId:Ne,onNodeDaemonIdChange:Ce,nodeCustomPath:$e,onNodeCustomPathChange:Qe,nodePickerWorkspaces:dt,nodePickerProviders:it,attachableDaemons:ee,onAddNode:ge,onRemoveNode:Ae,availableCliAgents:x,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:t}):s.jsx(wM,{meshes:N,loading:C,error:S,onDismissError:()=>M(null),daemons:r,features:{createDaemonPicker:g.createDaemonPicker},showCreate:A,onToggleCreate:()=>T(!A),createName:L,onCreateNameChange:P,createRepoIdentity:B,onCreateRepoIdentityChange:z,createRepoRemoteUrl:R,onCreateRepoRemoteUrlChange:_,newMeshDaemonId:K,onNewMeshDaemonIdChange:E,newMeshWorkspace:D,onNewMeshWorkspaceChange:$,createPickerWorkspaces:I,onSelectMesh:b,onCreate:Y,onCancelCreate:q}):s.jsx(br,{icon:s.jsx(es,{}),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 vA(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function wA(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>n.has(a)?!1:(n.add(a),!0))}function kA({children:e}){const{sendCommand:t,sendData:n}=yt(),{ides:r}=bs(),a=l.useMemo(()=>r.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[r]),o=l.useMemo(()=>({sendCommand:t,sendData:n,daemons:a,userName:void 0,loadMeshStatus:async(i,u)=>t(i,"mesh_status",{meshId:u}),launchCoordinator:async(i,u)=>{var h;const c={meshId:u.meshId};u.cliType&&(c.cliType=u.cliType);const p=await t(i,"launch_mesh_coordinator",c),d=(p==null?void 0:p.result)??p;if((d==null?void 0:d.success)===!1)throw new Error(d.error||"Coordinator launch failed");const m=(d==null?void 0:d.sessionId)||((h=d==null?void 0:d.session)==null?void 0:h.id)||(d==null?void 0:d.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:Hi,unwrapResult:i=>i,normalizeMesh:(i,u)=>i,normalizeNode:(i,u,c)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:hM}),[t,n,a]);return s.jsx(Qh.Provider,{value:o,children:e})}function xl(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function jA(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),n=xl();return n&&!t.searchParams.has("token")&&t.searchParams.set("token",n),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function ms(e,t){return await fetch(jA(e),{credentials:"same-origin",...t})}function tm(){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 SA{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 n of this.adapters.keys())if(n.startsWith("standalone"))return n}return null}register(t,n){this.adapters.set(t,n),this.states.set(t,n.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,n){this.states.set(t,n);const r=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(a=>a(r,n))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const n=this.resolveDaemonId(t);return n?this.adapters.get(n):void 0}getState(t){const n=this.resolveDaemonId(t);return n&&this.states.get(n)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,n){return!1}sendPtyInput(t,n,r){return this.ptyInputSender?this.ptyInputSender(t,n,r):!1}onScreenshot(t,n){return this.screenshotCallbacks.set(t,n),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,n){this.screenshotCallbacks.forEach(r=>r(t,n))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,n){this.statusCallbacks.forEach(r=>r(t,n))}emitRuntimeSnapshot(t,n,r=0,a=!1,o,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:r,text:n,truncated:a,cols:o,rows:i})}emitSessionOutput(t,n,r){!t||typeof n!="string"||!n||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof r=="number"?{seq:r}:{},data:n})}onRuntimeEvent(t,n){const r=this.runtimeListeners.get(t)||new Set;return r.add(n),this.runtimeListeners.set(t,r),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(n),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,n,r){if(!n)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(n)}/snapshot`,window.location.origin);typeof(r==null?void 0:r.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(r.sinceSeq));const o=await ms(`${a.pathname}${a.search}`);if(!o.ok){let u=`Runtime snapshot unavailable (${o.status})`;try{const c=await o.json();c!=null&&c.error&&(u=c.error)}catch{}return{success:!1,error:u}}const i=await o.json();return this.emitRuntimeEvent(n,{type:"runtime_snapshot",sessionId:n,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:!!(r!=null&&r.force)}),{success:!0}}emitRuntimeEvent(t,n){var r;(r=this.runtimeListeners.get(t))==null||r.forEach(a=>a(n))}}const hs=new SA;function NA(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=xl();return n?`${t}?token=${encodeURIComponent(n)}`:t}const Or=NA(),Id=3e3,CA=3e4;let as=null,MA=0;const va=new Map;let $s=null,nr=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 Kn(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function AA(e){return e==="connected"?"connected":e}async function rr(e,t,n){const r=jp(e,n||{}),a=as;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++MA}_${Date.now()}`;return new Promise((i,u)=>{const c=setTimeout(()=>{va.delete(o),u(new Error(`WS command timeout: ${t}`))},3e4);va.set(o,{resolve:p=>{clearTimeout(c),i(p)},reject:p=>{clearTimeout(c),u(p)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:r.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function yi(e,t){const n=as;if(!n||n.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return n.send(JSON.stringify(t)),!0}catch{return!1}}function sm(e,t,n){const r=as;if(!r||r.readyState!==WebSocket.OPEN)return!1;const a=jp(e,{sessionId:t,targetSessionId:t,data:n});try{return r.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}hs.registerPtyInputSender(sm);class IA{constructor(t){st(this,"daemonId");st(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(as==null?void 0:as.readyState)===WebSocket.OPEN}get connectionState(){return(as==null?void 0:as.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,n){return rr(this.daemonId,t,n)}async sendInput(t,n){return rr(this.daemonId,"cdp_remote_action",{action:t,params:n,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,$s&&(clearInterval($s),$s=null);const n=async()=>{if(this.hasCommandChannel)try{const r=await rr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(r!=null&&r.success&&(r!=null&&r.base64)){const a=await fetch(`data:image/jpeg;base64,${r.base64}`).then(o=>o.blob());hs.emitScreenshot(this.daemonId,a)}}catch{}};n(),$s=setInterval(n,2e3)}stopScreenshots(t){$s&&(clearInterval($s),$s=null)}}let Qt=null;function TA(e){return(!Qt||Qt.daemonId!==e)&&(Qt=new IA(e)),Qt}function PA({children:e}){const t=l.useRef(ar()),n=ar();t.current=n;const{setUserName:r}=bs(),a=l.useRef(r);a.current=r;const o=l.useRef(null),i=l.useRef(null),[,u]=l.useState("disconnected"),c=l.useCallback((f,y)=>{u(f),nr==null||nr(f,y)},[]),p=l.useRef(null),d=l.useRef(),m=l.useRef(Id),h=l.useRef(!0),g=l.useRef(!1),v=l.useRef("initial_connect");return l.useEffect(()=>{h.current=!0,g.current=!1;function f(){var x,w;if(!h.current||((x=p.current)==null?void 0:x.readyState)===WebSocket.OPEN||((w=p.current)==null?void 0:w.readyState)===WebSocket.CONNECTING)return;c("connecting"),console.log(`[Standalone WS] Connecting to ${Or}...`),Kn("connect_attempt",{url:Or,reason:v.current,delayMs:m.current});let j;try{j=new WebSocket(Or)}catch(N){console.error("[Standalone WS] Failed to create WebSocket:",N),y();return}p.current=j,j.onopen=()=>{if(!h.current){j.close();return}c("connected"),m.current=Id,Kn("open",{url:Or,reason:v.current}),ls.resubscribeAll({sendData:yi}),console.log("[Standalone WS] Connected")},as=j,j.onmessage=N=>{var k,b;try{const C=JSON.parse(N.data);if((C.type==="command_result"||C.type==="error")&&C.requestId){const S=va.get(C.requestId);S&&(va.delete(C.requestId),C.type==="error"?S.reject(new Error(((k=C.data)==null?void 0:k.message)||"Command failed")):S.resolve(C.data));return}if(C.type==="session_output"){const S=C.sessionId||C.cliId||C.cliType;S&&hs.emitSessionOutput(S,typeof C.data=="string"?C.data:"",typeof C.seq=="number"?C.seq:void 0);return}if(C.type==="runtime_snapshot"){hs.emitRuntimeSnapshot(C.sessionId,typeof C.text=="string"?C.text:"",typeof C.seq=="number"?C.seq:0,!!C.truncated,typeof C.cols=="number"?C.cols:void 0,typeof C.rows=="number"?C.rows:void 0);return}if(C.type==="topic_update"){const S=C.update;S&&ls.publish(S);return}if(C.type==="status"||C.type==="initial_state"){const S=C.data;if(!S)return;const{injectEntries:M,markLoaded:A,getIdes:T}=t.current,L=S.instanceId||"standalone",P=T().find(R=>R.id===L),B=TA(L);hs.register(L,B),hs.setState(L,"connected"),c("connected",L),hs.emitStatus(L,S);const z=oa(S,{daemonId:L,existingDaemon:P,existingEntries:T()});Td("ws_status",{type:C.type,daemonId:L,sessions:(S.sessions||[]).map(R=>({id:R.id,parentId:R.parentId,providerType:R.providerType,kind:R.kind,transport:R.transport,unread:R.unread,inboxBucket:R.inboxBucket,lastSeenAt:R.lastSeenAt,lastUpdated:R.lastUpdated,title:R.title})),recentLaunches:(S.recentLaunches||[]).map(R=>({id:R.id,providerType:R.providerType,kind:R.kind,workspace:R.workspace,lastLaunchedAt:R.lastLaunchedAt}))}),Td("entries",{daemonId:L,entries:z.filter(R=>R.type!=="adhdev-daemon").map(R=>({id:R.id,type:R.type,unread:R.unread,inboxBucket:R.inboxBucket,lastSeenAt:R.lastSeenAt,lastUpdated:R.lastUpdated,sessionId:R.sessionId}))}),z.length>0&&M(z,{authoritativeDaemonIds:[L]}),A(),i.current!==L&&((b=o.current)==null||b.call(o),i.current=L,o.current=ls.subscribe({sendData:yi},L,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${L}`,params:{includeSessions:!0}},R=>{if(R.topic!=="daemon.metadata")return;const _=t.current.getIdes(),K=_.find(D=>D.id===L),E=oa(R.status,{daemonId:L,existingDaemon:K,existingEntries:_,timestamp:R.timestamp});E.length>0&&t.current.injectEntries(E,{authoritativeDaemonIds:[L]}),R.userName&&a.current&&a.current(R.userName)}))}}catch(C){console.error("[Standalone WS] Parse error:",C)}},j.onclose=N=>{h.current&&(Qt==null||Qt.stopScreenshots(),Qt&&hs.setState(Qt.daemonId,"disconnected"),c("disconnected"),p.current=null,v.current=`close:${N.code}${N.wasClean?":clean":":unclean"}`,Kn("close",{code:N.code,reason:N.reason||"",wasClean:N.wasClean}),y())},j.onerror=N=>{g.current||!h.current||(v.current="error",Kn("error",{message:N instanceof Event?"event":String(N),readyState:j.readyState}),console.warn("[Standalone WS] Error, will reconnect:",N))}}function y(){if(!h.current)return;clearTimeout(d.current);const j=m.current;console.log(`[Standalone WS] Reconnecting in ${j}ms...`),Kn("schedule_reconnect",{reason:v.current,delayMs:j}),d.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,CA),f()},j)}return f(),()=>{var j;h.current=!1,g.current=!0,(j=o.current)==null||j.call(o),o.current=null,i.current=null,clearTimeout(d.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,as=null),Qt&&(Qt.stopScreenshots(),hs.unregister(Qt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function DA({children:e}){const[t,n]=l.useState("disconnected"),[r,a]=l.useState(null);l.useEffect(()=>(nr=(i,u)=>{n(i),u&&a(u)},()=>{nr=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",u=AA(t),c={};return r&&(c[r]=u),c.standalone=u,{wsStatus:t,isConnected:i,connectionStates:c}},[t,r]);return s.jsx(af,{connectionOverrides:o,children:s.jsx(PA,{children:e})})}const nm="adhdev_standalone_font_preferences",qs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Ha=[{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"}],pr=[{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"}],LA=new Set(Ha.map(e=>e.id)),RA=new Set(pr.map(e=>e.id));function fs(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Zr("chat",t.chat),code:Zr("code",t.code),terminal:Zr("terminal",t.terminal)}}function Zr(e,t){const n=qs[e],r=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof r.preset=="string"?r.preset.trim():"",o=typeof r.customFamily=="string"?r.customFamily.trim():"";return(e==="chat"?LA:RA).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:n:{preset:a}:n}function ea(e,t){var a;const n=Zr(e,t);if(n.preset==="custom"&&n.customFamily)return n.customFamily;const r=e==="chat"?Ha:pr;return((a=r.find(o=>o.id===n.preset))==null?void 0:a.family)||r[0].family}function _A(e){const t=fs(e),n=ea("chat",t.chat),r=ea("code",t.code),a=ea("terminal",t.terminal);return{"--chat-font-family":n,"--chat-code-font-family":r,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Hs(e,t=document.documentElement){const n=fs(e),r=_A(n);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(r))t.style.setProperty(a,o);return n}function vi(e){const t=fs(e);try{localStorage.setItem(nm,JSON.stringify(t))}catch{}return t}function EA(){try{const e=localStorage.getItem(nm);if(e)return fs(JSON.parse(e))}catch{}return qs}function $A(){return Hs(EA())}function Gn(e,t){var r;const n=e==="chat"?Ha:pr;return((r=n.find(a=>a.id===t))==null?void 0:r.label)||n[0].label}function FA({children:e}){const t=hr(),n=ki(),{t:r}=Xe("common"),a=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:s.jsx(Gd,{}),label:r("standalone.nav.dashboard"),active:n.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:s.jsx(Is,{}),label:"Burrow",active:n.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:s.jsx(es,{}),label:"Mesh",active:n.pathname.startsWith("/mesh"),onSelect:()=>t("/mesh")},{id:"settings",path:"/settings",icon:s.jsx(ka,{}),label:r("standalone.nav.settings"),active:n.pathname.startsWith("/settings"),onSelect:()=>t("/settings")}],[n.pathname,t,r]),o=l.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:r("standalone.nav.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:r("standalone.nav.docs")},{id:"about",label:r("standalone.nav.about"),icon:s.jsx(Ci,{}),active:n.pathname==="/about",onSelect:()=>t("/about"),title:r("standalone.nav.about")}],[n.pathname,t,r]);return s.jsx(Ew,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:a,footerItems:o,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.82"]}),footerActions:({collapsed:i,toggleCollapsed:u})=>s.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:u,title:r(i?"standalone.layout.expandSidebar":"standalone.layout.collapseSidebar"),children:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:r("standalone.layout.collapse")})]}),children:e})}const BA=[{icon:s.jsx(Is,{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(us,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(or,{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."}],HA=[{icon:s.jsx($f,{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(Cn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Tf,{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(Lf,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],OA=[{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 WA(){const{t:e}=Xe("common");return s.jsxs(br,{icon:s.jsx(Ci,{className:"text-text-primary"}),title:e("standalone.about.title"),subtitle:e("standalone.about.subtitle"),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(xt,{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:e("standalone.about.selfHostedEdition")}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:e("standalone.about.headline")}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:e("standalone.about.description")})]}),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:e("standalone.about.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:e("standalone.about.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:e("standalone.about.tryCloud")})]})]})}),s.jsx(xt,{title:e("standalone.about.includedSection"),description:e("standalone.about.includedDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:BA.map(t=>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:t.icon}),t.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),s.jsx(xt,{title:e("standalone.about.inventorySection"),description:e("standalone.about.inventoryDescription"),children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Sp.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:Cp.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:Np.map(t=>`${t.icon} ${t.name}`)}].map(t=>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:t.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:t.items.map(n=>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:n},n))})]},t.label))})}),s.jsx(xt,{title:e("standalone.about.cloudExtrasSection"),description:e("standalone.about.cloudExtrasDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:HA.map(t=>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:t.icon}),t.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),s.jsx(xt,{title:e("standalone.about.comparisonSection"),description:e("standalone.about.comparisonDescription"),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:e("standalone.about.featureHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.selfhostHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.cloudHeader")})]})}),s.jsx("tbody",{children:OA.map((t,n)=>s.jsxs("tr",{className:n%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:t.feature}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:t.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:"✓"})})]},t.feature))})]})})}),s.jsx(La,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:e("standalone.about.cloudOptional"),description:e("standalone.about.cloudOptionalDescription"),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:e("standalone.about.compareCloud")}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(zf,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function $o(e,t,n){return{...e,[t]:n}}function Fo({surface:e,title:t,description:n,value:r,options:a,onChange:o}){const{t:i}=Xe("common");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:n})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Hw,{value:r.preset,onChange:u=>{const c=u.target.value;o(c==="custom"?{preset:"custom",customFamily:r.customFamily||""}:{preset:c})},children:a.map(u=>s.jsx("option",{value:u.id,children:u.label},u.id))}),r.preset==="custom"&&s.jsx(is,{type:"text",className:"font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:r.customFamily||"",onChange:u=>o({preset:"custom",customFamily:u.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:i("standalone.fonts.resolvedStack")})," ",s.jsx("span",{className:"font-mono break-all",children:ea(e,r)})]})]})]})}function UA({value:e,savedValue:t,saving:n=!1,error:r,notice:a,onChange:o,onSave:i,onResetToSaved:u,onResetToDefaults:c}){const{t:p}=Xe("common"),d=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:p("standalone.fonts.fontOverridesNotice")}),r&&s.jsx(Kt,{variant:"error",children:r}),a&&s.jsx(Kt,{variant:"success",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Fo,{surface:"chat",title:p("standalone.fonts.chat"),description:p("standalone.fonts.chatDescription"),value:e.chat,options:Ha,onChange:m=>o($o(e,"chat",m))}),s.jsx(Fo,{surface:"code",title:p("standalone.fonts.code"),description:p("standalone.fonts.codeDescription"),value:e.code,options:pr,onChange:m=>o($o(e,"code",m))}),s.jsx(Fo,{surface:"terminal",title:p("standalone.fonts.terminal"),description:p("standalone.fonts.terminalDescription"),value:e.terminal,options:pr,onChange:m=>o($o(e,"terminal",m))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:p("standalone.fonts.livePreview")}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",Gn("chat",e.chat.preset)," · Code: ",Gn("code",e.code.preset)," · Terminal: ",Gn("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[p("standalone.fonts.defaults")," ",Gn("chat",qs.chat.preset)," / ",Gn("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:n||!d,children:p(n?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),s.jsx(ks,{type:"button",variant:"secondary",size:"sm",onClick:u,disabled:n||!d,children:p("standalone.fonts.revertToSaved")}),s.jsx(ks,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:n,children:p("standalone.fonts.resetToDefaults")})]})]})}function KA(){const{t:e}=Xe("common"),{ides:t}=bs(),n=t.find(O=>O.type==="adhdev-daemon"),r=(n==null?void 0:n.detectedIdes)||[],{sendCommand:a}=yt(),{userName:o}=bs(),[i,u]=l.useState(o||""),[c,p]=l.useState(null),[d,m]=l.useState(null),[h,g]=l.useState(qs),[v,f]=l.useState(!1),[y,j]=l.useState(""),[x,w]=l.useState(""),[N,k]=l.useState("127.0.0.1"),[b,C]=l.useState(""),[S,M]=l.useState(""),[A,T]=l.useState(""),[L,P]=l.useState(""),[B,z]=l.useState(""),[R,_]=l.useState(!1),K=async()=>{const se=await(await ms("/auth/session")).json();p(se)},E=async()=>{const se=await(await ms("/api/v1/standalone/preferences")).json();m(se),k(se.standaloneBindHost);const X=fs(se.standaloneFontPreferences);g(X),Hs(X),vi(X)};l.useEffect(()=>{o!==void 0&&u(o)},[o]),l.useEffect(()=>{Promise.all([K(),E()]).catch(O=>{P(O instanceof Error?O.message:String(O))})},[]),l.useEffect(()=>{Hs(h)},[h]);const D=O=>{const se=O.target.value.trim();n!=null&&n.id&&se!==o&&a(n.id,"set_user_name",{userName:se}).catch(console.error)},[$,I]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),G=O=>{I(O);try{localStorage.setItem("adhdev_sound",O?"1":"0")}catch{}},Y=async()=>{j(""),w(""),f(!0);try{const O=fs(h),se=await ms("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:O})}),X=await se.json();if(!se.ok)throw new Error((X==null?void 0:X.error)||"Failed to save standalone font preferences");const oe=fs(X.standaloneFontPreferences);m(X),g(oe),Hs(oe),vi(oe),w(e("standalone.settings.fontsSaved"))}catch(O){j(O instanceof Error?O.message:String(O))}finally{f(!1)}},Z=()=>{const O=fs(d==null?void 0:d.standaloneFontPreferences);j(""),w(""),g(O),Hs(O)},q=()=>{j(""),w(""),g(qs),Hs(qs)},ne=async()=>{P(""),z(""),_(!0);try{const O=await ms("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:N})}),se=await O.json();if(!O.ok)throw new Error((se==null?void 0:se.error)||"Failed to save standalone network preference");m(se),k(se.standaloneBindHost),z(se.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(O){P(O instanceof Error?O.message:String(O))}finally{_(!1)}},ue=async()=>{if(P(""),z(""),S.trim().length<4){P(e("standalone.settings.passwordTooShort"));return}if(S!==A){P(e("standalone.settings.passwordMismatch"));return}_(!0);try{const O=await ms("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:b,newPassword:S})}),se=await O.json();if(!O.ok)throw new Error((se==null?void 0:se.error)||"Failed to save password");p(se),await E(),C(""),M(""),T(""),z(c!=null&&c.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),tm()}catch(O){P(O instanceof Error?O.message:String(O))}finally{_(!1)}},ae=async()=>{P(""),z(""),_(!0);try{const O=await ms("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:b,clear:!0})}),se=await O.json();if(!O.ok)throw new Error((se==null?void 0:se.error)||"Failed to clear password");p(se),await E(),C(""),M(""),T(""),z(e("standalone.settings.passwordDisabled"))}catch(O){P(O instanceof Error?O.message:String(O))}finally{_(!1)}};return s.jsxs(br,{icon:s.jsx(ka,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[s.jsx(Kt,{variant:"info",children:e("standalone.settings.infoNotice")}),(c==null?void 0:c.publicHostWarning)&&s.jsx(Kt,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),s.jsx(xt,{title:e("standalone.settings.daemonSection"),description:e("standalone.settings.daemonDescription"),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:e("standalone.settings.versionLabel")}),s.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.82"]}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.statusLabel")}),s.jsx("span",{className:n?"text-green-400":"text-yellow-400",children:e(n?"standalone.settings.statusRunning":"standalone.settings.statusNotConnected")}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.currentBindLabel")}),s.jsx("span",{className:"font-mono text-xs",children:(d==null?void 0:d.currentBindHost)||(c==null?void 0:c.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.defaultBindLabel")}),s.jsx("span",{className:"font-mono text-xs",children:(d==null?void 0:d.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.authLabel")}),s.jsx("span",{className:"text-xs",children:c!=null&&c.hasPasswordAuth?e("standalone.settings.authPassword"):c!=null&&c.hasTokenAuth?e("standalone.settings.authToken"):e("standalone.settings.authNone")})]})}),s.jsx(xt,{title:e("standalone.settings.networkSection"),description:e("standalone.settings.networkDescription"),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:e("standalone.settings.networkHint")}),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:N==="127.0.0.1",onChange:()=>k("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.localhostLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.localhostHint")})]})]}),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:N==="0.0.0.0",onChange:()=>k("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.allInterfacesLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.allInterfacesHint")})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(ks,{type:"button",variant:"primary",size:"sm",onClick:()=>{ne()},disabled:R,children:e(R?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),s.jsx("span",{className:"text-xs text-text-muted",children:e("standalone.settings.networkRestartHint",{host:(d==null?void 0:d.currentBindHost)||(c==null?void 0:c.boundHost)||"127.0.0.1"})})]})]})}),s.jsx(xt,{title:e("standalone.settings.securitySection"),description:e("standalone.settings.securityDescription"),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?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),L&&s.jsx(Kt,{variant:"error",children:L}),B&&s.jsx(Kt,{variant:"success",children:B}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(is,{type:"password",placeholder:c!=null&&c.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:b,onChange:O=>C(O.target.value)}),s.jsx(is,{type:"password",placeholder:c!=null&&c.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:S,onChange:O=>M(O.target.value)}),s.jsx(is,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:A,onChange:O=>T(O.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(ks,{type:"button",variant:"primary",size:"sm",onClick:()=>{ue()},disabled:R,children:R?e("standalone.settings.saving"):c!=null&&c.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(c==null?void 0:c.hasPasswordAuth)&&s.jsx(ks,{type:"button",variant:"danger",size:"sm",onClick:()=>{ae()},disabled:R,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(xt,{title:e("standalone.settings.detectedIdesSection"),description:e("standalone.settings.detectedIdesDescription"),children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:e("standalone.settings.noIdesDetected")}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(O=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${O.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:O.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:O.type})]},O.type))})}),s.jsx(xt,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(qw,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(xt,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(mk,{themeDescription:e("standalone.settings.themeDescription"),mobileDescription:e("standalone.settings.mobileDescription"),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:e("standalone.settings.fontsLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e("standalone.settings.fontsDescription")}),s.jsx(UA,{value:h,savedValue:fs(d==null?void 0:d.standaloneFontPreferences),saving:v,error:y,notice:x,onChange:g,onSave:()=>{Y()},onResetToSaved:Z,onResetToDefaults:q})]})})}),s.jsx(xt,{title:e("standalone.settings.notificationsSection"),description:e("standalone.settings.notificationsDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Kw,{}),s.jsx(Bs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Gf,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:$,onChange:G})]})}),s.jsx(xt,{title:e("standalone.settings.profileSection"),description:e("standalone.settings.profileDescription"),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(If,{size:16,className:"text-text-secondary"})," ",e("standalone.settings.displayNameLabel")]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:e("standalone.settings.displayNameHint")})]}),s.jsx(is,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:i,onChange:O=>u(O.target.value),onBlur:D,onKeyDown:O=>{O.key==="Enter"&&O.currentTarget.blur()}})]})})})]})}const GA=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],Yn="adhdev_onboarding_done",zA=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],VA={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function qA({onDone:e}){const{t}=Xe("common"),[n,r]=l.useState([]),[a,o]=l.useState(new Set(GA)),[i,u]=l.useState(!0),[c,p]=l.useState(null),[d,m]=l.useState(!1),[h,g]=l.useState(null),[v,f]=l.useState("all");l.useEffect(()=>{let b=!1;const C=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${C}/providers?sort=popular&limit=100`).then(S=>{if(!S.ok)throw new Error(`HTTP ${S.status}`);return S.json()}).then(S=>{b||r(S.providers??[])}).catch(S=>{b||p(S instanceof Error?S.message:String(S))}).finally(()=>{b||u(!1)}),()=>{b=!0}},[]);const y=n.filter(b=>v==="all"||b.category===v),j=["cli","ide","extension","acp"].map(b=>({category:b,items:y.filter(C=>C.category===b)})).filter(b=>b.items.length>0),x=l.useCallback(b=>{o(C=>{const S=new Set(C);return S.has(b)?S.delete(b):S.add(b),S})},[]),w=l.useCallback(async()=>{if(a.size===0){localStorage.setItem(Yn,"1"),e();return}m(!0);const b=[];for(const C of a)try{const M=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:C})})).json().catch(()=>({}));b.push({type:C,ok:!!M.success,error:M.error})}catch(S){b.push({type:C,ok:!1,error:S instanceof Error?S.message:String(S)})}g(b),m(!1),b.every(C=>C.ok)&&localStorage.setItem(Yn,"1")},[a,e]),N=l.useCallback(()=>{localStorage.setItem(Yn,"1"),e()},[e]),k=l.useCallback(()=>{h&&h.every(b=>b.ok)?e():d||N()},[h,d,e,N]);return s.jsx(Pu,{open:!0,onClose:k,size:"lg",contentClassName:"max-w-2xl",title:t("standalone.onboarding.title"),footer:s.jsxs("div",{className:"flex w-full items-center gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t(a.size!==1?"standalone.onboarding.selectedCount_other":"standalone.onboarding.selectedCount_one",{count:a.size})}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx(ks,{variant:"secondary",size:"sm",onClick:N,disabled:d,children:t("standalone.onboarding.skip")}),s.jsx(ks,{variant:"primary",size:"sm",onClick:()=>{h?(localStorage.setItem(Yn,"1"),e()):w()},disabled:d||!h&&a.size===0,children:d?t("standalone.onboarding.installing"):h?t("standalone.onboarding.done"):t("standalone.onboarding.installCount",{count:a.size})})]})]}),children:s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsx("div",{className:"text-[12px] text-text-muted",children:t("standalone.onboarding.intro")}),!i&&!c&&n.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:zA.map(b=>{const C=b.key==="all"?n.length:n.filter(S=>S.category===b.key).length;return C===0&&b.key!=="all"?null:s.jsxs("button",{onClick:()=>f(b.key),className:`machine-btn text-[10px] px-2 py-0.5 ${v===b.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[b.label," ",s.jsxs("span",{className:"opacity-60",children:["(",C,")"]})]},b.key)})}),i&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&c&&s.jsx(Kt,{variant:"error",children:t("standalone.onboarding.loadError",{error:c})}),!i&&!c&&y.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!c&&y.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:j.map(b=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:VA[b.category]??b.category}),s.jsx("div",{className:"grid gap-1.5",children:b.items.map(C=>{var L,P;const S=a.has(C.type),M=h==null?void 0:h.find(B=>B.type===C.type),A=((L=C.manifest)==null?void 0:L.icon)??"📦",T=((P=C.manifest)==null?void 0:P.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${S?"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:S,onChange:()=>x(C.type),disabled:d,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:A}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:C.displayName}),T&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:T})]}),M&&s.jsx("span",{className:`text-[10px] font-semibold ${M.ok?"text-status-online":"text-status-error"}`,children:M.ok?t("standalone.onboarding.installed"):t("standalone.onboarding.installFailed",{error:M.error??"failed"})})]},C.type)})})]},b.category))})]})})}function YA(){try{return localStorage.getItem(Yn)==="1"}catch{return!1}}Tw();ok();yg();$A();const JA=Fd({baseUrl:"",getToken:xl});function XA({children:e}){const{t}=Xe("common"),[n,r]=l.useState(null),[a,o]=l.useState(!0),[i,u]=l.useState(""),[c,p]=l.useState(""),[d,m]=l.useState(!1),h=async()=>{o(!0),p("");try{const f=await(await ms("/auth/session")).json();r(f)}catch(v){p(v instanceof Error?v.message:String(v))}finally{o(!1)}};l.useEffect(()=>{h()},[]),l.useEffect(()=>{if(!n||n.required&&!n.authenticated)return;let v=!1;return(async()=>{try{const f=await ms("/api/v1/standalone/preferences");if(!f.ok)return;const y=await f.json();if(v)return;const j=fs(y.standaloneFontPreferences);Hs(j),vi(j)}catch{}})(),()=>{v=!0}},[n==null?void 0:n.authenticated,n==null?void 0:n.required]);const g=async v=>{v.preventDefault(),m(!0),p("");try{const f=await ms("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),y=await f.json();if(!f.ok)throw new Error((y==null?void 0:y.error)||"Login failed");r(y),u(""),tm()}catch(f){p(f instanceof Error?f.message:String(f))}finally{m(!1)}};return a?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:t("standalone.auth.loading")}):n?!n.required||n.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:t("standalone.auth.signInTitle")}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:n.hasPasswordAuth?t("standalone.auth.passwordProtected"):t("standalone.auth.tokenProtected")})]}),n.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[s.jsx(is,{type:"password",value:i,onChange:v=>u(v.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),s.jsx(ks,{type:"submit",variant:"primary",disabled:d||!i,className:"justify-center",children:t(d?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):s.jsx(Kt,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),c&&s.jsx(Kt,{variant:"error",children:c})]})}):s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:t("standalone.auth.loadError",{error:c||"unknown error"})})}function Pd(){const{t:e}=Xe("common"),{ides:t,initialLoaded:n}=bs();if(!n)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:e("standalone.machine.loading")});const r=t.find(a=>a.daemonMode||a.type==="adhdev-daemon");return r?s.jsx(Oo,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Oo,{to:"/dashboard",replace:!0})}function QA(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!YA())return fetch("/api/v1/providers/installed").then(r=>r.ok?r.json():{providers:[]}).then(r=>{n||(r.providers??[]).length===0&&t(!0)}).catch(()=>{}),()=>{n=!0}},[]),e?s.jsx(qA,{onDone:()=>t(!1)}):null}function ZA(){const{t:e}=Xe("common"),{ides:t}=bs(),n=l.useMemo(()=>{for(const d of t)if(d.activeInteractivePrompt)return d.instanceId??d.id;return null},[t]),{promptSession:r,hasActivePrompt:a,responseError:o,isSubmitting:i,submit:u,cancel:c,reopen:p}=Lp(n);return a?s.jsxs("div",{className:"relative",children:[!r&&s.jsx("button",{type:"button",onClick:p,className:"fixed bottom-4 right-4 z-[79] btn btn-primary btn-sm shadow-lg",children:e("standalone.machine.awaitingInput")}),s.jsx(cu,{promptSession:r,isSubmitting:i,error:o,onSubmit:u,onCancel:c})]}):null}function eI(){const e=l.useMemo(()=>({sendCommand:rr,sendData:yi,sendPtyInput:sm}),[]);return s.jsx(Wm,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(cf,{client:JA,children:s.jsx(XA,{children:s.jsx(DA,{children:s.jsx(uf,{value:e,children:s.jsxs(ff,{sendDaemonCommand:rr,children:[s.jsx(ZA,{}),s.jsxs(FA,{children:[s.jsx(QA,{}),s.jsxs(Um,{children:[s.jsx(Ns,{path:"/dashboard",element:s.jsx(s2,{})}),s.jsx(Ns,{path:"/machine",element:s.jsx(Pd,{})}),s.jsx(Ns,{path:"/machines/:id",element:s.jsx(uM,{})}),s.jsx(Ns,{path:"/machines",element:s.jsx(Pd,{})}),s.jsx(Ns,{path:"/about",element:s.jsx(WA,{})}),s.jsx(Ns,{path:"/settings",element:s.jsx(KA,{})}),s.jsx(Ns,{path:"/mesh",element:s.jsx(kA,{children:s.jsx(yA,{})})}),s.jsx(Ns,{path:"*",element:s.jsx(Oo,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}j0({connectionManager:hs});Km(document.getElementById("root")).render(s.jsx(eI,{}));