@adhdev/daemon-standalone 0.9.82-rc.262 → 0.9.82-rc.264

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.
@@ -0,0 +1,113 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-DsCRNxW_.js","assets/vendor-BHUMCOj6.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
+ var xp=Object.defineProperty;var bp=(e,t,r)=>t in e?xp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ue=(e,t,r)=>bp(e,typeof t!="symbol"?t+"":t,r);import{r as l,j as s,M as Wo,a as gp,b as yp,c as vp,R as yt,d as Ir,t as wp,e as jp,u as $r,D as kp,f as fo,g as xo,E as Np,i as Sp,C as Cp,h as Ip,B as Mp,k as Ap,l as Tp,m as _p,H as tn,P as ts,n as Lp,o as Pp,p as Rp,q as Dp,s as $p,v as Ep,w as Ko,x as Bp,y as Fp,z as Op,A as zp,F as ss,N as bo,G as Hp}from"./vendor-BHUMCOj6.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&n(i)}).observe(document,{childList:!0,subtree:!0});function r(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(a){if(a.ep)return;a.ep=!0;const o=r(a);fetch(a.href,o)}})();function Wp(e={}){const t=Math.max(1,Math.floor(e.capacity||200)),r=[];return{record(n){const a={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...n,payload:n.payload?{...n.payload}:{}};return r.push(a),r.length>t&&r.splice(0,r.length-t),a},list(n={}){const a=Math.max(1,Math.floor(n.limit||100));return r.filter(o=>!n.interactionId||o.interactionId===n.interactionId).filter(o=>!n.topic||o.topic===n.topic).filter(o=>!n.kind||o.kind===n.kind).slice(-a).map(o=>({...o,payload:o.payload?{...o.payload}:{}}))},clear(){r.splice(0,r.length)}}}const Bs=Wp();function Ki(e){const t={};for(const r of e)r.transport&&(t[r.transport]=(t[r.transport]||0)+1);return{count:e.length,ids:e.map(r=>r.id),statuses:e.map(r=>String(r.status||"unknown")),transports:t}}function Kp(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Ui(e){return Array.isArray(e)?[...e]:[]}function Gc(e,t){if(!e)return t??null;const r=Object.prototype.hasOwnProperty.call(e,"messages"),n=Object.prototype.hasOwnProperty.call(e,"activeModal"),a=typeof e.id=="string"?e.id.trim():"",o=typeof(t==null?void 0:t.id)=="string"?t.id.trim():"",i=!!a&&!!o&&a!==o;return t?{...t,...e,messages:r?Ui(e.messages):i?[]:t.messages,activeModal:n?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...r?{messages:Ui(e.messages)}:{},...n?{activeModal:e.activeModal??null}:{}}}function hr(e,t){const r=Kp(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(t==null?void 0:t.parentSessionId)??null,providerSessionId:e.providerSessionId??(t==null?void 0:t.providerSessionId),providerName:r??(t==null?void 0:t.providerName)??(t==null?void 0:t.cliName)??(t==null?void 0:t.type)??e.providerName??e.providerType,title:e.title??(t==null?void 0:t.title)??r??(t==null?void 0:t.providerName)??e.providerName??e.providerType,workspace:e.workspace??(t==null?void 0:t.workspace)??null,mode:e.mode??(t==null?void 0:t.mode),capabilities:e.capabilities??(t==null?void 0:t.sessionCapabilities)??(t==null?void 0:t.capabilities)??[],cdpConnected:e.cdpConnected??(t==null?void 0:t.cdpConnected),activeChat:Gc(e.activeChat,t==null?void 0:t.activeChat),activeInteractivePrompt:Object.prototype.hasOwnProperty.call(e,"activeInteractivePrompt")?e.activeInteractivePrompt??null:(t==null?void 0:t.activeInteractivePrompt)??null,controlValues:e.controlValues??(t==null?void 0:t.controlValues),providerControls:e.providerControls??(t==null?void 0:t.providerControls),summaryMetadata:e.summaryMetadata??(t==null?void 0:t.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(t==null?void 0:t.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(t==null?void 0:t.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(t==null?void 0:t.lastMessagePreview),lastMessageRole:e.lastMessageRole??(t==null?void 0:t.lastMessageRole),lastMessageAt:e.lastMessageAt??(t==null?void 0:t.lastMessageAt),lastMessageHash:e.lastMessageHash??(t==null?void 0:t.lastMessageHash),unread:e.unread??(t==null?void 0:t.unread),lastSeenAt:e.lastSeenAt??(t==null?void 0:t.lastSeenAt),inboxBucket:e.inboxBucket??(t==null?void 0:t.inboxBucket),completionMarker:e.completionMarker??(t==null?void 0:t.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(t==null?void 0:t.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(t==null?void 0:t.surfaceHidden),resume:e.resume??(t==null?void 0:t.resume),runtimeKey:e.runtimeKey??(t==null?void 0:t.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(t==null?void 0:t.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(t==null?void 0:t.runtimeWorkspaceLabel),settings:e.settings??(t==null?void 0:t.settings)}}function Vc(e,t,r){if(!(t!=null&&t.length))return(r==null?void 0:r.preserveMissing)===!1&&Array.isArray(t)?t:e;if(!(e!=null&&e.length))return t;const n=t.map(a=>{const o=e.find(i=>i.id===a.id);return o?hr(a,o):a});if((r==null?void 0:r.preserveMissing)!==!1){const a=new Set(t.map(o=>o.id));for(const o of e)a.has(o.id)||n.push(o)}return n}function Gi(e){return!!e&&typeof e=="object"&&"text"in e}function Uo(e,t){const r=(t==null?void 0:t.joiner)??" ",n=(t==null?void 0:t.normalizeWhitespace)??!1;let a="";return typeof e=="string"?a=e:Array.isArray(e)?a=e.map(o=>typeof o=="string"?o:Gi(o)?String(o.text||""):"").join(r):Gi(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Fs(e){return Uo(e,{normalizeWhitespace:!0})}const qc=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}),Yc=l.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Vi(e){var r,n;let t=0;return e.activeChat!==void 0&&(t+=4),e.activeInteractivePrompt!==void 0&&(t+=2),(r=e.childSessions)!=null&&r.length&&(t+=2),e.workspace&&(t+=1),e.machine&&(t+=1),(n=e.agents)!=null&&n.length&&(t+=1),t}function Jc(e,t,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=t.version??r.version??e.version,o=t.serverVersion??e.serverVersion??r.serverVersion,i=t.versionMismatch===!0||e.versionMismatch===!0,c=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,u=t.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),o&&(n.serverVersion=o),u&&(n.versionUpdateReason=u),a&&o&&a===o?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((t.versionMismatch===!0||i&&a&&o&&a!==o)&&(n.versionMismatch=!0),c&&(n.versionUpdateRequired=!0),n)}function Up(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function ya(e){if(!e||typeof e!="object")return"";const t=e,r=Up(Fs(t.content).slice(0,512));return[String(t.id||""),String(t._localId||""),String(t._turnKey||""),String(t.index??""),String(t.role||""),String(t.receivedAt??t.timestamp??""),r].join(":")}function Gp(e,t){if(!Array.isArray(e))return e;if(t!=null&&t.has(e))return{count:e.length,sharedRef:!0};let r=2166136261;for(const n of e){const a=ya(n);for(let o=0;o<a.length;o+=1)r^=a.charCodeAt(o),r=Math.imul(r,16777619)>>>0}return{count:e.length,hash:r.toString(16).padStart(8,"0"),first:ya(e[0]),last:ya(e[e.length-1])}}function go(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function yo(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(go(e)&&go(t)){const i=e.messages;Array.isArray(i)&&i===t.messages&&r.add(i)}if(Array.isArray(e)&&Array.isArray(t)){const i=Math.min(e.length,t.length);for(let c=0;c<i;c+=1)yo(e[c],t[c],r);return}const n=e,a=t,o=new Set([...Object.keys(n),...Object.keys(a)]);for(const i of o)i!=="messages"&&yo(n[i],a[i],r)}function gr(e,t){return Array.isArray(e)?e.map(r=>gr(r,t)):!e||typeof e!="object"?e:go(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?Gp(a,t):gr(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,gr(n,t)]))}function Vp(e,t){try{const r=new WeakSet;return yo(e,t,r),JSON.stringify(gr(e,r))===JSON.stringify(gr(t,r))}catch{return!1}}function vo(e,t,r){return Vp(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Xc(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function qp(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function qi(e,t,r,n){var c;const a=(c=t.chats)!=null&&c.length?t.chats:e.chats,o=Vc(e.childSessions,t.childSessions,{preserveMissing:n}),i=Gc(t.activeChat,e.activeChat);return Jc(e,t,{...e,...t,chats:a,childSessions:o,activeChat:i,_lastUpdate:r})}function Yp(e,t,r){var a,o;const n={};t.status&&t.status!==e.status&&(n.status=t.status),t.cdpConnected!==void 0&&(n.cdpConnected=t.cdpConnected),t.childSessions!==void 0&&(n.childSessions=Vc(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((o=e.chats)!=null&&o.length)&&(n.chats=t.chats);for(const i of["title","workspace","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","activeInteractivePrompt","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion","versionUpdateReason","versionUpdateRequired","updateCommand","updatePolicy","updateChannel","releaseChannel"])qp(n,t,i);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function Jp(e,t,r,n){const a=Yp(e,t,n),o=Object.keys(a).length>0?Jc(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return vo(e,o,r)}function Xp(e){const t=new Set(e.map(o=>o.id)),r=new Set,n=new Set,a=new Set;for(const o of e){const i=Xc(o);i&&r.add(i),i&&o.type!=="adhdev-daemon"&&n.add(i),i&&o.type==="adhdev-daemon"&&o._sessionListAuthoritative&&a.add(i)}return{incomingIds:t,incomingDaemonIds:r,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:a}}function Qp(e,t,r,n,a,o){return!a.has(t)||!o.has(t)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function Zp(e,t,r,n,a){return e.transport?r.has(t)&&!n.has(t)?!0:a.has(t):!1}function eh(e,t,r){var d,p;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(h=>({...h,_lastUpdate:n}));const o=new Map;for(const h of t)o.set(h.id,h);const{incomingIds:i,incomingDaemonIds:c,daemonIdsWithSessionEntries:u,daemonIdsWithAuthoritativeSessionList:m}=Xp(e);for(const h of e){const b=o.get(h.id);if(!b){o.set(h.id,{...h,_lastUpdate:n});continue}const g=Vi(h),f=Vi(b),w=Xc(h),j=!a.has(w);if(g>f){const N=qi(b,h,n,j);o.set(h.id,vo(b,N,n));continue}if(g<f){o.set(h.id,Jp(b,h,n,j));continue}const y=h.timestamp||n,v=b._lastUpdate||b.timestamp||0;if(y>=v){const N=qi(b,h,n,j);o.set(h.id,vo(b,N,n));continue}(d=h.chats)!=null&&d.length&&!((p=b.chats)!=null&&p.length)&&o.set(h.id,{...b,chats:h.chats})}for(const[h,b]of o){const g=b.daemonId||h.split(":")[0];if(!c.has(g))continue;if(a.has(g)&&m.has(g)&&!i.has(h)){o.delete(h);continue}const f=n-(b._lastUpdate||b.timestamp||0);Qp(b,g,f,i,a,u)&&o.delete(h)}for(const[h,b]of o){const g=b.daemonId||h.split(":")[0];if(Zp(b,g,c,u,o))continue;n-(b._lastUpdate||b.timestamp||0)>3e5&&b.status!=="online"&&o.delete(h)}return Array.from(o.values())}function th(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function sh({children:e,connectionOverrides:t}){const[r,n]=l.useState([]),[a,o]=l.useState(!1),[i,c]=l.useState([]),[u,m]=l.useState(void 0),d=l.useRef(r);l.useEffect(()=>{d.current=r},[r]);const p=l.useCallback((j,y)=>{n(v=>{let N=!1;const k=v.map(x=>x.id!==j||x.chats===y?x:(N=!0,{...x,chats:y}));return N?k:v})},[]),h=l.useCallback((j,y)=>{n(v=>{const N=v.length===0?j:eh(j,v,y),k=!th(v,N);return k&&Bs.record({kind:"dashboard.entries_applied",payload:{incoming:Ki(j),next:Ki(N)}}),k?N:v})},[]),b=l.useCallback(()=>o(!0),[]),g=l.useMemo(()=>({injectEntries:h,markLoaded:b,getIdes:()=>d.current}),[h,b]),f=t,w=l.useMemo(()=>({ides:r,updateRouteChats:p,initialLoaded:a,toasts:i,setToasts:c,wsStatus:(f==null?void 0:f.wsStatus)??"connected",isConnected:(f==null?void 0:f.isConnected)??!0,connectionStates:(f==null?void 0:f.connectionStates)??{},connectionTransports:(f==null?void 0:f.connectionTransports)??{},showReconnected:(f==null?void 0:f.showReconnected)??!1,retryConnection:f==null?void 0:f.retryConnection,retryServerConnection:f==null?void 0:f.retryServerConnection,connectionLoginUrl:f==null?void 0:f.connectionLoginUrl,isP2PActive:(f==null?void 0:f.isP2PActive)??!1,p2pStates:(f==null?void 0:f.p2pStates)??{},userRole:f==null?void 0:f.userRole,connectionRetryStatuses:f==null?void 0:f.connectionRetryStatuses,userName:u,setUserName:m}),[r,p,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,u]);return s.jsx(Yc.Provider,{value:g,children:s.jsx(qc.Provider,{value:w,children:e})})}function Yt(){return l.useContext(qc)}function Mr(){return l.useContext(Yc)}function Qc(e){const{baseUrl:t,getToken:r,onUnauthorized:n}=e;function a(c){return c.startsWith("http")?c:`${t}${c.startsWith("/")?"":"/"}${c}`}function o(c){const u=r==null?void 0:r(),m=a(c),d=c.startsWith("http")?new URL(m):new URL(m,typeof window<"u"?window.location.origin:"http://localhost");return u&&d.searchParams.set("token",u),!c.startsWith("http")&&!t?`${d.pathname}${d.search}${d.hash}`:d.toString()}async function i(c,u={}){const m={"Content-Type":"application/json",...u.headers||{}},d=r==null?void 0:r();d&&(m.Authorization=`Bearer ${d}`);const p=a(c),h=new AbortController,b=setTimeout(()=>h.abort(),15e3);try{const g=await fetch(p,{...u,headers:m,signal:h.signal});if(g.status===401)throw n==null||n(),new Error("Unauthorized");if(!g.ok){const f=await g.json().catch(()=>({error:g.statusText}));throw new Error(f.error||`API Error: ${g.status}`)}return g.json()}finally{clearTimeout(b)}}return{getDaemons:()=>i("/api/v1/daemons"),getDaemonStatus:c=>i(`/api/v1/daemons/${c}/status`),sendCommand:(c,u,m={})=>i(`/api/v1/daemons/${c}/command`,{method:"POST",body:JSON.stringify({type:u,payload:m})}),execTerminal:(c,u,m)=>i(`/api/v1/daemons/${c}/terminal`,{method:"POST",body:JSON.stringify({command:u,name:m})}),sendAgentMessage:(c,u,m)=>i(`/api/v1/shortcuts/${c}/chat`,{method:"POST",body:JSON.stringify({agentType:u,message:m})}),getAgentStatus:c=>i(`/api/v1/shortcuts/${c}/status`),approveAgent:(c,u,m)=>i(`/api/v1/shortcuts/${c}/approve`,{method:"POST",body:JSON.stringify({agentType:u,action:m?"approve":"reject"})}),getMuxState:c=>i(`/api/v1/mux/${encodeURIComponent(c)}/state`),getMuxSocketInfo:c=>i(`/api/v1/mux/${encodeURIComponent(c)}/socket-info`),controlMux:(c,u,m={})=>i(`/api/v1/mux/${encodeURIComponent(c)}/control`,{method:"POST",body:JSON.stringify({type:u,payload:m})}),getMuxEventsUrl:c=>o(`/api/v1/mux/${encodeURIComponent(c)}/events`),getRuntimeEventsUrl:c=>o(`/api/v1/runtime/${encodeURIComponent(c)}/events`),request:i}}const rh=Qc({baseUrl:"http://localhost:3847"}),nh=l.createContext(rh);function ah({client:e,children:t}){return s.jsx(nh.Provider,{value:e,children:t})}const oh={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Zc=l.createContext(oh);function ih({value:e,children:t}){return s.jsx(Zc.Provider,{value:e,children:t})}function lt(){return l.useContext(Zc)}function ed(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function lh(e){const t=ed(e);if(!t||t.error!=="untrusted_external_provider")return null;const r=t.provider&&typeof t.provider=="object"?t.provider:null;return{providerType:typeof(r==null?void 0:r.type)=="string"?r.type:null,sourceName:typeof(r==null?void 0:r.sourceName)=="string"?r.sourceName:null,description:typeof t.hint=="string"?t.hint:void 0}}function ch(e){const[t,r]=l.useState(null),n=l.useCallback(async(i,c)=>{const u=p=>e(i,"launch_cli",{...c,...p}),m=await u({}),d=lh(m);return d?new Promise(p=>{r({providerType:d.providerType||String(c.cliType??"?"),sourceName:d.sourceName,description:d.description,retry:()=>u({confirmExternalUntrusted:!0}),resolve:h=>{h.cancelled?p({success:!1,error:"user_cancelled_untrusted_launch"}):p(h.response)}})}):m},[e]),a=l.useCallback(async()=>{const i=t;if(i){r(null);try{const c=await i.retry(),u=ed(c);u!=null&&u.success?i.resolve({ok:!0,response:c}):i.resolve({ok:!1,error:(u==null?void 0:u.error)||"launch failed after confirm",response:c})}catch(c){i.resolve({ok:!1,error:(c==null?void 0:c.message)||String(c)})}}},[t]),o=l.useCallback(()=>{const i=t;i&&(r(null),i.resolve({ok:!1,cancelled:!0}))},[t]);return{launchCli:n,pending:t,confirm:a,cancel:o}}function dh({providerType:e,sourceName:t,description:r,onConfirm:n,onCancel:a}){const o=l.useRef(null);return l.useEffect(()=>{var i;(i=o.current)==null||i.focus()},[]),l.useEffect(()=>{const i=c=>{c.key==="Escape"&&a()};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[a]),s.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Confirm untrusted external provider",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",onClick:a,style:{pointerEvents:"auto"},children:s.jsxs("div",{className:"bg-[var(--surface-primary)] text-text-primary border border-amber-500/40 rounded-lg shadow-xl max-w-lg w-full",onClick:i=>i.stopPropagation(),children:[s.jsxs("div",{className:"px-4 py-3 border-b border-border-subtle flex items-center gap-2",children:[s.jsx("span",{"aria-hidden":!0,className:"text-amber-400 text-base",children:"⚠"}),s.jsx("h2",{className:"text-sm font-semibold",children:"Activate untrusted external provider?"})]}),s.jsxs("div",{className:"px-4 py-3 text-[12px] flex flex-col gap-3",children:[s.jsxs("p",{children:["You're about to activate ",s.jsx("span",{className:"font-mono",children:e}),t?s.jsxs(s.Fragment,{children:[" from ",s.jsx("span",{className:"font-mono",children:t})]}):null,"."]}),s.jsx("p",{className:"text-text-secondary",children:r??"This manifest ships JavaScript that the daemon will execute. Treat as untrusted code — review the source before enabling."}),s.jsx("p",{className:"text-text-secondary",children:"Only proceed if you trust the source URL you added and have reviewed the manifest."})]}),s.jsxs("div",{className:"px-4 py-2 border-t border-border-subtle flex justify-end gap-2",children:[s.jsx("button",{ref:o,type:"button",onClick:a,className:"px-3 py-1 text-sm rounded border border-border-default hover:bg-surface-secondary",children:"Cancel"}),s.jsx("button",{type:"button",onClick:n,className:"px-3 py-1 text-sm rounded bg-amber-500 text-black font-semibold hover:opacity-90",children:"Activate"})]})]})})}const td=l.createContext(null);function uh({sendDaemonCommand:e,children:t}){const r=ch(e),n=l.useMemo(()=>({launchCli:r.launchCli}),[r.launchCli]);return s.jsxs(td.Provider,{value:n,children:[t,r.pending&&s.jsx(dh,{providerType:r.pending.providerType,sourceName:r.pending.sourceName,description:r.pending.description,onConfirm:r.confirm,onCancel:r.cancel})]})}function oa(){const e=l.useContext(td);return e||{launchCli:async()=>{throw new Error("useLaunchCli must be used inside <LaunchCliProvider>")}}}function mh(e){let t=2166136261;for(const r of e){const n=String(r||"");for(let a=0;a<n.length;a+=1)t^=n.charCodeAt(a),t=Math.imul(t,16777619)>>>0;t^=255,t=Math.imul(t,16777619)>>>0}return t.toString(16).padStart(8,"0")}function ph(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function hh(e){return e?mh([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),ph(e.content)]):""}const Fe={size:18};function sd({size:e=Fe.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 Go({size:e=Fe.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=Fe.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 rd({size:e=Fe.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 fh({size:e=Fe.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 xh({size:e=Fe.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 nd({size:e=Fe.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 bh({size:e=Fe.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 ia({size:e=Fe.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 ad({size:e=Fe.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 gh({size:e=Fe.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 Is({size:e=Fe.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 Ot({size:e=Fe.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 Vo({size:e=Fe.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 Os({size:e=Fe.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 la({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function zs({size:e=Fe.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 Hs({size:e=Fe.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 Qt({size:e=Fe.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 yh({size:e=Fe.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 od({size:e=Fe.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 qo({size:e=Fe.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 id({size:e=Fe.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 vh({size:e=Fe.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 Yo({size:e=Fe.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 wh({size:e=Fe.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 ld({size:e=Fe.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 cd({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function vt({size:e=Fe.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 jh({size:e=Fe.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 kh({size:e=Fe.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 Nh({size:e=Fe.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 Sh({size:e=Fe.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 Er({size:e=Fe.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 Ch({size:e=Fe.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 Ih({size:e=Fe.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 Mh({size:e=Fe.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 dd({size:e=Fe.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 Ah({size:e=Fe.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 Th({size:e=Fe.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 _h({size:e=Fe.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 Lh({size:e=Fe.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 Ph({size:e=Fe.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 Rh({size:e=Fe.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 Dh({size:e=Fe.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 $h({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),s.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}const ud="adhdev_chat_activity_visible",Yi=new Set(["hidden","debug","internal"]),Ji=new Set(["visible","user","chat"]),Eh=new Set(["debug","trace","internal"]),Bh=new Set(["tool_call","terminal_command","runtime_activity"]),Fh=new Set(["runtime_status","provider_chrome","control"]),Oh=new Set(["thought","tool","terminal"]);function md(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function _s(e){return typeof e=="string"?e.trim().toLowerCase():""}function va(e,t,r){return e[r]??(t==null?void 0:t[r])}function Xi(e,t,r){const n=e;return r.some(a=>n[a]===!0||(t==null?void 0:t[a])===!0)}function zh(e,t){const r=_s(e.kind);return r||(t==="tool"?"tool":"standard")}function wa(e,t,r){const n=md(e),a=typeof(n==null?void 0:n.label)=="string"?n.label.trim():"";return a||(t==="terminal"||r==="terminal_command"?"Terminal":t==="tool"||r==="tool_call"?"Tool":t==="thought"?"Thought":r==="runtime_activity"?"Runtime":"Activity")}function Hh(e){const t=e.content;return Array.isArray(t)&&t.some(r=>!!r&&typeof r=="object"&&r.type!=="text")}function Jo(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=md(e),r=_s(e.role),n=zh(e,r),a=_s(va(e,t,"visibility")),o=_s(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??a),i=_s(va(e,t,"audience")),c=_s(va(e,t,"source")),u=Yi.has(a)||Yi.has(o)||Eh.has(i)||Xi(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),m=Ji.has(a)||Ji.has(o)||i==="chat"||Xi(e,t,["userFacing"]),d=Oh.has(n)||Bh.has(c);if(u)return{surface:d?"activity":"internal",isUserFacing:!1,isActivityFacing:d,isInternal:!d,role:r,kind:n,label:wa(e,n,c)};if(m)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:wa(e,n,c)};if((r==="system"||n==="system")&&Hh(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:"Chat"};if(Fh.has(c)||r==="system"||n==="system")return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:r,kind:n,label:"Internal"};if(d)return{surface:"activity",isUserFacing:!1,isActivityFacing:!0,isInternal:!1,role:r,kind:n,label:wa(e,n,c)};const p=(r==="user"||r==="human"||r==="assistant")&&(n==="standard"||n==="");return{surface:p?"chat":"internal",isUserFacing:p,isActivityFacing:!1,isInternal:!p,role:r,kind:n,label:p?"Chat":"Internal"}}function Wh(e){return(Array.isArray(e)?e:[]).filter(t=>Jo(t).isUserFacing)}function pd(e){return(Array.isArray(e)?e:[]).filter(t=>Jo(t).isActivityFacing)}function Kh(e,t,r){return!r||t.length===0?e:[...e,...t].sort((n,a)=>{const o=Number(n.receivedAt??n.timestamp??0)||0,i=Number(a.receivedAt??a.timestamp??0)||0;if(o!==i)return o-i;const c=Number(n.index??0)||0,u=Number(a.index??0)||0;return c-u})}function Qi(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(ud))==="1"}catch{return!1}}const hd=[gp,{singleTilde:!1}],fd=[hd,yp,vp],Uh=[hd],Xo=200,Gh=80,Zi=650,Qs=new Map;function Fn(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function Vh(e,t){if(!Array.isArray(e)||e.length===0)return"0:empty";const r=String(t||"").trim();if(r)return`${e.length}:${r}`;const n=e[e.length-1];return`${e.length}:${hh(n)}`}function qh(e,t,r,n){return e||!t?!1:Fn(r,n)}function Yh({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=Gh,bottomThresholdPx:a=Xo}){const o=Math.max(0,Number(e)||0),i=Math.max(0,Number(t)||0),c=Math.max(0,Number(r)||0);return Math.max(0,i-c)<=0?{showTop:!1,showBottom:!1}:{showTop:o>n,showBottom:Math.max(0,i-o-c)>a}}function Jh(e){return Yh({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function fr(e,t=Xo){return!!e&&e.fromBottom>=t}function Xh(e,t){return Fn(e,t)?!fr(e):!0}function Qh({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function Zh({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function ja(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function xd(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function ef(e,t,r){return Number(e.receivedAt||r[On(e,t)]||0)||0}function bd(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function tf(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function Zs(e,t){if(!e)return t;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||t}catch{return e.split(/[\\/]/).filter(Boolean).pop()||t}}function ka(e){if(typeof e.uri=="string"&&e.uri)return e.uri;if(typeof e.data=="string"&&e.data&&typeof e.mimeType=="string"&&e.mimeType)return`data:${e.mimeType};base64,${e.data}`}function sn(e,t,r){return s.jsxs("div",{className:"rounded-md border border-border-subtle p-2 text-sm",role:"note",children:[s.jsx("span",{className:"font-medium",children:e}),t?s.jsx("span",{className:"ml-1 break-all",children:t}):null,r?s.jsx("div",{className:"mt-1 opacity-80",style:{whiteSpace:"pre-wrap"},children:r}):null]})}function el(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):bd(e)?s.jsx(Wo,{remarkPlugins:fd,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function er({parts:e,renderAsPreformatted:t}){return s.jsx("div",{className:"flex flex-col gap-2",children:e.map((r,n)=>{if(r.type==="text")return s.jsx("div",{children:el(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=ka(r),o=r.alt||r.description||Zs(r.uri,"image");return a?s.jsx("img",{src:a,alt:o,className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):s.jsx("div",{children:sn("Image",o,r.mimeType)},`image-fallback-${n}`)}if(r.type==="audio"){const a=ka(r);return a?s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("audio",{controls:!0,src:a,className:"max-w-full"}),r.transcript?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:r.transcript}):null]},`audio-${n}`):s.jsx("div",{children:sn("Audio",Zs(r.uri,"audio"),r.transcript||r.mimeType)},`audio-fallback-${n}`)}if(r.type==="video"){const a=ka(r),o=r.title||r.name||r.alt||Zs(r.uri,"video"),i=[r.transcript,r.description,r.mimeType].filter(Boolean).join(`
3
+ `);return s.jsxs("div",{className:"flex flex-col gap-1",children:[a?s.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"}):sn("Video",o,i),a&&i?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:i}):null]},`video-${n}`)}if(r.type==="resource_link"){const a=r.title||r.name||Zs(r.uri,"resource"),o=[r.description,r.mimeType].filter(Boolean).join(`
4
+ `);return s.jsxs("div",{className:"flex flex-col gap-1",children:[r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",download:!0,className:"underline break-all",children:a}):sn("Resource",a,o),r.uri&&o?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:o}):null]},`resource-link-${n}`)}if(r.type==="resource"&&r.resource){const a=Zs(r.resource.uri,"resource");if(r.resource.text)return s.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[s.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:a}),el(r.resource.text,!0)]},`resource-${n}`);if(r.resource.uri)return s.jsx("a",{href:r.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:a},`resource-uri-${n}`)}return null})})}function On(e,t){const r=e,n=Uo(e.content,{joiner:`
5
+ `});return[e.id?`id:${e.id}`:"",r._localId?`local:${r._localId}`:"",r._turnKey?`turn:${r._turnKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",e.role?`role:${e.role}`:"",n?`content:${n.slice(0,80)}`:"",`fallback:${t}`].filter(Boolean).join("|")}const sf=l.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(Wo,{remarkPlugins:Uh,children:t.text}),s.jsx("span",{className:"action-time",children:xd(t.timestamp)})]})},(e,t)=>e.log===t.log),rf=l.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:o,isTextExpanded:i,onToggleTextExpanded:c}){var C,M,D;const u=(t.role||"").toLowerCase(),m=u==="user"||u==="human",d=t.kind||(u==="tool"?"tool":"standard"),p=Jo(t),h=tf(t.content)?t.content:null,b=!!(h!=null&&h.some(P=>P.type!=="text")),g=Uo(t.content,{joiner:`
6
+ `});if(p.isActivityFacing&&d!=="thought"&&d!=="tool"&&d!=="terminal"){const P=p.label||"Activity";return s.jsxs("div",{className:"self-start chat-msg-activity","data-chat-activity-row":"true",children:[s.jsxs("div",{className:"chat-msg-activity-meta","aria-label":"Activity message",children:[s.jsx("span",{className:"activity-dot"}),s.jsx("span",{children:P})]}),b&&h?s.jsx("div",{className:"chat-msg-activity-body",children:s.jsx(er,{parts:h,renderAsPreformatted:!1})}):s.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:g})]})}if(d==="thought"){const P=typeof((C=t.meta)==null?void 0:C.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":p.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(Nh,{size:13}),s.jsx("span",{children:P})]}),s.jsx("div",{className:"chat-msg-body",children:g})]})}if(d==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":p.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-tool-meta","aria-label":"Tool message",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),s.jsx("span",{className:"tool-label",children:"Tool"})]}),b&&h?s.jsx("div",{className:"tool-text w-full",children:s.jsx(er,{parts:h,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:g})]});if(d==="terminal"){const P=(M=t.meta)!=null&&M.isRunning?"⏳":"✅",T=typeof((D=t.meta)==null?void 0:D.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal","data-chat-activity-row":p.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:P}),s.jsx("span",{children:T})]}),b&&h?s.jsx("div",{className:"chat-msg-body",children:s.jsx(er,{parts:h,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:g})]})}if(d==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:b&&h?s.jsx(er,{parts:h,renderAsPreformatted:!1}):g.slice(0,100)});const f=t.meta,j=(typeof(f==null?void 0:f.renderMode)=="string"?f.renderMode.trim():"")==="preformatted",y=g,v=!1,N=y,k=j,x=!m&&!k&&bd(N),I=["chat-message-row",m?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return s.jsx("div",{className:I,children:(y||b||m)&&s.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${y||b?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:m?a||"You":t.senderName||n}),r!=null&&s.jsx("span",{className:"chat-time",children:xd(r)})]}),(y||b)&&s.jsx("div",{className:"chat-markdown",children:b&&h?s.jsx(er,{parts:h,renderAsPreformatted:k}):k?s.jsx("pre",{className:"chat-preformatted",children:N}):x?s.jsx(Wo,{remarkPlugins:fd,children:N}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:N})}),v]})})},(e,t)=>e.message===t.message&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),nf=l.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:o=!1,isWorking:i=!1,contextKey:c="",receivedAtMap:u={},lastMessageHash:m,showActivityMessages:d=!1,emptyState:p,onLoadMore:h,isLoadingMore:b,hasMoreHistory:g,hiddenLiveCount:f=0,loadError:w,scrollToBottomRequestNonce:j,isVisible:y=!0},v){const N=l.useRef(null),k=l.useRef(null),x=l.useRef(null),I=l.useRef(0),C=l.useRef(""),M=l.useRef(""),D=l.useRef(!1),P=l.useRef(null),T=l.useRef(!1),R=l.useRef(null),O=l.useRef(!1),[K,S]=l.useState(new Set),[A,B]=l.useState({showTop:!1,showBottom:!1}),L=l.useRef(!1),$=l.useRef(!1),F=l.useRef(y),z=l.useRef(y),re=l.useRef(null);z.current=y;const J=()=>{const W=N.current;return W?W.scrollHeight-W.scrollTop-W.clientHeight<Xo:!0},Y=l.useCallback(()=>{const W=N.current,_=W?Jh(W):{showTop:!1,showBottom:!1};B(ie=>ie.showTop===_.showTop&&ie.showBottom===_.showBottom?ie:_)},[]),se=l.useCallback((W="auto")=>{var ie;const _=N.current;_&&(_.scrollTo({top:_.scrollHeight,behavior:W}),(ie=_.ownerDocument.defaultView)==null||ie.requestAnimationFrame(()=>Y()))},[Y]),fe=l.useCallback((W="auto")=>{var ie;const _=N.current;_&&(_.scrollTo({top:0,behavior:W}),(ie=_.ownerDocument.defaultView)==null||ie.requestAnimationFrame(()=>Y()))},[Y]),be=l.useCallback(()=>{var ue;const W=N.current,_=(ue=window.getSelection)==null?void 0:ue.call(window);if(!W||!_||_.rangeCount===0||_.isCollapsed){O.current=!1;return}const ie=_.anchorNode,pe=_.focusNode;O.current=!!(ie&&pe&&W.contains(ie)&&W.contains(pe))},[]),X=l.useMemo(()=>{const W=Wh(t),_=pd(t);return Kh(W,_,d)},[t,d]),Q=X.length===t.length?m:void 0,we=Vh(X,Q),ve=l.useCallback(()=>{const W=N.current;if(!W||!c||!z.current)return;const _={top:W.scrollTop,fromBottom:Math.max(0,W.scrollHeight-W.scrollTop-W.clientHeight),messageFingerprint:we};re.current={contextKey:c,snapshot:_},Qs.set(c,_)},[c,we]),xe=l.useCallback((W="auto")=>{P.current!=null&&cancelAnimationFrame(P.current),P.current=requestAnimationFrame(()=>{P.current=null,se(W)})},[se]),Ne=l.useCallback(()=>{L.current=!1,T.current=!0,$.current=!0,R.current!=null&&window.clearTimeout(R.current),R.current=window.setTimeout(()=>{T.current=!1,R.current=null},Zi)},[]);l.useEffect(()=>{const W=!D.current,_=M.current!==c;if(M.current=c,W||_){D.current=!0;const pe=c?Qs.get(c):null,ue=!!pe&&Fn(pe,we);L.current=ue?fr(pe):!1,T.current=Xh(pe,we),O.current||(ue?requestAnimationFrame(()=>{const oe=N.current;oe&&(ja(oe,pe),L.current=fr(pe),Y(),$.current=!0)}):xe("auto")),I.current=X.length,C.current=we;return}X.length>I.current;const ie=we!==C.current;Qh({hasSelection:O.current,userScrolledUp:L.current,hasChatContentChanged:ie})&&xe("auto"),I.current=X.length,C.current=we},[we,c,X.length,xe,Y]),l.useEffect(()=>{j&&(Ne(),O.current||xe("auto"))},[Ne,xe,j]),l.useEffect(()=>{const W=F.current;W&&!y&&ve(),z.current=y,F.current=y;const _=c?Qs.get(c):null;if(qh(W,y,_,we)){if(!_)return;L.current=fr(_),T.current=!1,O.current||requestAnimationFrame(()=>{const ie=N.current;ie&&(ja(ie,_),Y())});return}},[y,c,we,Ne,ve,xe,Y]),l.useEffect(()=>()=>{const W=re.current;W&&Qs.set(W.contextKey,W.snapshot),P.current!=null&&cancelAnimationFrame(P.current),R.current!=null&&window.clearTimeout(R.current)},[]),l.useEffect(()=>{const W=k.current,_=N.current;if(!W||!_)return;const ie=()=>{R.current!=null&&window.clearTimeout(R.current),R.current=window.setTimeout(()=>{T.current=!1,R.current=null},Zi)},pe=new ResizeObserver(()=>{Y();const ue=T.current;Zh({hasSelection:O.current,userScrolledUp:L.current,contextAutoScrollActive:ue})&&(xe("auto"),ue&&ie())});return pe.observe(W),_!==W&&pe.observe(_),()=>{pe.disconnect(),R.current!=null&&(window.clearTimeout(R.current),R.current=null)}},[xe,c,Y]),l.useImperativeHandle(v,()=>({scrollToBottom:(W="smooth")=>{se(W)}}),[se]),l.useEffect(()=>{const W=N.current;if(!W)return;let _;const ie=()=>{ve(),clearTimeout(_),_=setTimeout(()=>{L.current=!J(),Y()},50)};return W.addEventListener("scroll",ie,{passive:!0}),()=>{W.removeEventListener("scroll",ie),clearTimeout(_)}},[ve,Y]),l.useEffect(()=>(document.addEventListener("selectionchange",be),()=>document.removeEventListener("selectionchange",be)),[be]);const ae=l.useRef(0),ge=l.useRef(!1);l.useEffect(()=>{const W=N.current;if(!W||!ge.current||ae.current===0)return;const _=W.scrollHeight-ae.current;_>0&&(W.scrollTop=_),Y(),ve(),ae.current=0,ge.current=!1},[X.length,ve,Y]),l.useEffect(()=>{if($.current||!c)return;const W=Qs.get(c),_=N.current;if(!(!W||!_)){if(!Fn(W,we)){se("auto"),$.current=!0;return}ja(_,W),L.current=fr(W),Y(),$.current=!0}},[c,we,X.length,se,Y]);const me=()=>{const W=N.current;W&&(ae.current=W.scrollHeight),ge.current=!0,h==null||h()},U=()=>{L.current=!0,fe("smooth"),ve()},H=()=>{Ne(),se("smooth"),ve()},q=l.useMemo(()=>{const W=X.map((ue,oe)=>({type:"message",data:ue,index:oe,ts:ef(ue,oe,u)}));if(!r||r.length===0)return W;const _=[...r].sort((ue,oe)=>ue.timestamp-oe.timestamp).map((ue,oe)=>({type:"action",data:ue,index:oe,ts:ue.timestamp})),ie=[];let pe=0;for(const ue of W){for(;pe<_.length&&ue.ts>0&&_[pe].ts<ue.ts;)ie.push(_[pe++]);ie.push(ue)}for(;pe<_.length;)ie.push(_[pe++]);return ie},[X,r,u]),ne=f>0||!!g,E=f>0?`↑ Show ${Math.min(f,80)} earlier messages${f>80?` (${f} hidden)`:""}`:w?`↻ ${w}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:N,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:k,className:"chat-container-content",children:[b&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),ne&&!b&&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 ${w&&f===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:E})}),q.length===0&&!ne&&(p||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),q.map(W=>{if(W.type==="action"){const Ee=W.data;return s.jsx(sf,{log:Ee},`action-${W.index}`)}const _=W.data,ie=W.index,pe=On(_,ie),ue=_.receivedAt||u[pe],oe=`${c}-${pe}`,Pe=K.has(oe);return s.jsx(rf,{message:_,receivedAt:ue,agentName:n,userName:a,isCliMode:o,isTextExpanded:Pe,onToggleTextExpanded:()=>S(Ee=>{const $e=new Set(Ee);return Pe?$e.delete(oe):$e.add(oe),$e})},`msg-${pe}`)}),i&&s.jsx("div",{className:"self-start chat-typing-wrapper",children:s.jsxs("div",{className:"typing-indicator",children:[s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),s.jsx("div",{className:"min-h-10",ref:x})]})}),(A.showTop||A.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[A.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:U,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),A.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:H,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),af=l.memo(nf,(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),of="modulepreload",lf=function(e){return"/"+e},tl={},cf=function(t,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),c=(i==null?void 0:i.nonce)||(i==null?void 0:i.getAttribute("nonce"));a=Promise.allSettled(r.map(u=>{if(u=lf(u),u in tl)return;tl[u]=!0;const m=u.endsWith(".css"),d=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const p=document.createElement("link");if(p.rel=m?"stylesheet":of,m||(p.as="script"),p.crossOrigin="",p.href=u,c&&p.setAttribute("nonce",c),document.head.appendChild(p),m)return new Promise((h,b)=>{p.addEventListener("load",h),p.addEventListener("error",()=>b(new Error(`Unable to preload CSS for ${u}`)))})}))}function o(i){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=i,window.dispatchEvent(c),!c.defaultPrevented)throw i}return a.then(i=>{for(const c of i||[])c.status==="rejected"&&o(c.reason);return t().catch(o)})};let sl=!1;const gd=l.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:o="measured"},i)=>{const c=l.useRef(null),[u,m]=l.useState(null),d=l.useRef([]),p=l.useRef(!1),h=l.useRef(!1),b=l.useRef(!1),g=l.useRef(!1),f=()=>{const w=c.current;if(w){p.current&&(w.clear(),p.current=!1);for(const j of d.current)w.write(j.data,j.onProcessed);d.current=[],h.current&&(w.fit(),h.current=!1),b.current&&(w.bumpResize(),b.current=!1),g.current&&(w.scrollToTop(),g.current=!1)}};return l.useImperativeHandle(i,()=>({write:(w,j)=>{c.current?c.current.write(w,j):d.current.push({data:w,onProcessed:j})},clear:()=>{c.current?c.current.clear():(d.current=[],p.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(d.current=[],p.current=!0)},resize:(w,j)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(w,j)},fit:()=>{c.current?c.current.fit():h.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():b.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():g.current=!0},getSelection:()=>{var w,j;return((j=(w=c.current)==null?void 0:w.getSelection)==null?void 0:j.call(w))||""},getVisibleText:()=>{var w,j;return((j=(w=c.current)==null?void 0:w.getVisibleText)==null?void 0:j.call(w))||""}}),[]),l.useEffect(()=>{u&&f()},[u]),l.useEffect(()=>{let w=!1;return cf(()=>import("./terminal-DsCRNxW_.js"),__vite__mapDeps([0,1,2])).then(j=>{sl||(sl=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),w||m(()=>j.GhosttyTerminalView)}).catch(j=>{console.error("[CliTerminal] failed to load terminal renderer",j)}),()=>{w=!0}},[]),u?s.jsx(u,{ref:c,onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n,readOnly:a,sizingMode:o,className:"w-full h-full rounded-lg overflow-hidden"}):s.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});gd.displayName="CliTerminal";function rn({label:e,value:t,sub:r,icon:n}){return s.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsx("span",{className:"text-base flex items-center",children:n}),s.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),s.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:t}),r&&s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function rl({value:e,max:t,label:r,color:n="#8b5cf6",detail:a,compact:o=!1}){const i=t>0?Math.min(Math.round(e/t*100),100):0,c=i>85?"#ef4444":i>60?"var(--status-warning)":n;return o?s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-0.5",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:r}),s.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[i,"%"]})]}),s.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${i}%`,background:c}})})]}):s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-1.5",children:[s.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:r}),s.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[i,"%"]})]}),s.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${i}%`,background:`linear-gradient(90deg, ${c}, ${c}cc)`}})}),a&&s.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function df({cursorPos:e,viewportRef:t,imgRef:r}){var y;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),o=(y=t.current)==null?void 0:y.getBoundingClientRect();if(!o)return null;const i=n.naturalWidth||a.width,c=n.naturalHeight||a.height,u=i/c,m=a.width/a.height;let d,p,h,b;u>m?(d=a.width,p=a.width/u,h=0,b=(a.height-p)/2):(p=a.height,d=a.height*u,h=(a.width-d)/2,b=0);const g=a.left-o.left+h+d*e.nx,f=a.top-o.top+b+p*e.ny,w=Math.max(8,Math.min(o.width-8,g)),j=Math.max(8,Math.min(o.height-8,f));return s.jsxs("div",{style:{position:"absolute",left:w-8,top:j-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[s.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:5,top:5,width:6,height:6,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 0 8px rgba(59,130,246,0.6)"}})]})}function uf({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:o,imeText:i,setImeText:c,handleImeSubmit:u,isConnActive:m,zoom:d,isMobile:p,mobileFillZoom:h,onZoomOut:b,onZoomReset:g,onZoomIn:f,transportType:w,screenshotUsage:j,lastActionStatus:y}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:v=>v.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[s.jsxs("div",{onClick:t,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[s.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),s.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),s.jsxs("div",{className:"relative",children:[s.jsx("div",{onClick:()=>{n(v=>!v),o(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&s.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:s.jsx("input",{type:"text",placeholder:"Type & Enter...",value:i,autoFocus:!0,onTouchStart:v=>v.stopPropagation(),onChange:v=>c(v.target.value),onKeyDown:v=>{u(v)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{o(v=>!v),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:m?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[s.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:m?"#22c55e":"#eab308",boxShadow:m?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:m?"#22c55e":"#eab308"},children:m?"Connected":"WS"})]}),d>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(d*100),"%"]}),w==="direct"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:"Direct P2P connection",children:"Direct"}),w==="relay"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),j&&j.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:j.budgetExhausted?"#ef4444":"#c4b5fd",background:j.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:j.budgetExhausted?"TURN blocked":`TURN ${j.dailyUsedMinutes}/${j.dailyBudgetMinutes}m`}),y&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:y})]})]}),a&&s.jsxs("div",{onTouchStart:v=>v.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",d<=(p?h:1)+.01?p?"FILL":"FIT":`${Math.round(d*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:v=>{v.stopPropagation(),b()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),s.jsx("button",{onClick:v=>{v.stopPropagation(),g()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:p?"FILL":"FIT"}),s.jsx("button",{onClick:v=>{v.stopPropagation(),f()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function mf({waitingLabel:e,waitingHint:t,transportType:r}){return s.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[s.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center border border-white/10 bg-white/[0.04] shadow-[0_10px_30px_rgba(0,0,0,0.35)]",style:{animation:"remote-float 2.8s ease-in-out infinite"},children:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),s.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:e}),s.jsx("div",{className:"text-[11px] text-white/40",children:t}),r==="relay"&&s.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function pf(){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 nl(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 Br(e,t){const r=l.useRef(null),n=l.useRef(0);l.useEffect(()=>{if(!pf())return;n.current+=1;const a=r.current;if(!a){console.debug(`[render-trace] ${e}#${n.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(t).map(([i,c])=>[i,nl(c)]))}),r.current=t;return}const o=Object.keys({...a,...t}).filter(i=>!Object.is(a[i],t[i]));o.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:o,snapshot:Object.fromEntries(o.map(i=>[i,nl(t[i])]))}),r.current=t})}function hf({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:o,zoomRef:i,panXRef:c,panYRef:u,setPanX:m,setPanY:d,setZoom:p,lastWheelTimeRef:h,onAction:b,setLastActionStatus:g,spawnRippleFromNormalized:f,clampPan:w,isMobile:j,mobileFillZoom:y}){const[v,N]=l.useState(null),k=l.useRef(null),x=l.useRef(null),I=l.useRef(null),C=l.useRef(!1),M=l.useRef(null),D=l.useRef(0),P=l.useRef(null),T=l.useRef(1),R=l.useRef({x:0,y:0}),O=l.useRef(!1),K=l.useRef(n),S=l.useRef(b),A=30,B=550,L=18,$=60,F=400,z=12,re=()=>{if(k.current)return;const se={nx:.5,ny:.5};k.current=se,N(se)};return l.useEffect(()=>{K.current=n,n==="mouse"&&re()},[n]),l.useEffect(()=>{S.current=b},[b]),l.useEffect(()=>{const se=e.current;if(!se)return;const fe=xe=>{if(!r.current)return null;const Ne=r.current.getBoundingClientRect();return!Ne.width||!Ne.height?null:{nx:Math.max(0,Math.min(1,(xe.clientX-Ne.left)/Ne.width)),ny:Math.max(0,Math.min(1,(xe.clientY-Ne.top)/Ne.height))}},be=(xe,Ne)=>{if(!r.current)return{dnx:0,dny:0};const ae=r.current,ge=ae.getBoundingClientRect(),me=ae.naturalWidth||ge.width,U=ae.naturalHeight||ge.height,H=me/U,q=ge.width/ge.height;let ne,E;return H>q?(ne=ge.width,E=ge.width/H):(E=ge.height,ne=ge.height*H),{dnx:xe/ne,dny:Ne/E}},X=(xe,Ne,ae)=>{if(ae<=1.05)return;const ge=-(xe-.5)*100,me=-(Ne-.5)*100,U=w(ge,me,ae);(Math.abs(U.x-c.current)>.1||Math.abs(U.y-u.current)>.1)&&(m(U.x),d(U.y),c.current=U.x,u.current=U.y)},Q=xe=>{const Ne=t.current;if(Ne&&xe.target instanceof Node&&Ne.contains(xe.target))xe.preventDefault();else return;if(xe.touches.length===1){const ae=xe.touches[0];x.current={x:ae.clientX,y:ae.clientY,time:Date.now()},I.current={x:ae.clientX,y:ae.clientY},O.current||(C.current=!1),M.current=setTimeout(()=>{if(!C.current&&!O.current)if(C.current=!0,K.current==="mouse"){const ge=k.current||{nx:.5,ny:.5};g("Right Click"),f(ge.nx,ge.ny,"right"),S.current("input_click",{...ge,button:"right"}).catch(()=>{})}else{const ge=fe(ae);ge&&(g("Right Click"),f(ge.nx,ge.ny,"right"),S.current("input_click",{...ge,button:"right"}).catch(()=>{}))}},500);return}if(xe.touches.length===2){M.current&&clearTimeout(M.current),C.current=!0,O.current=!0;const ae=xe.touches[1].clientX-xe.touches[0].clientX,ge=xe.touches[1].clientY-xe.touches[0].clientY;P.current=Math.sqrt(ae*ae+ge*ge),T.current=i.current,R.current={x:(xe.touches[0].clientX+xe.touches[1].clientX)/2,y:(xe.touches[0].clientY+xe.touches[1].clientY)/2}}},we=xe=>{const Ne=t.current;if(Ne&&xe.target instanceof Node&&Ne.contains(xe.target)&&xe.preventDefault(),xe.touches.length===1&&I.current){const ae=xe.touches[0],ge=ae.clientX-I.current.x,me=ae.clientY-I.current.y;if(!C.current&&x.current){const U=ae.clientX-x.current.x,H=ae.clientY-x.current.y;Math.sqrt(U*U+H*H)>8&&(C.current=!0,M.current&&clearTimeout(M.current))}if(C.current)if(K.current==="mouse"){const U=be(ge,me),H=k.current||{nx:.5,ny:.5},q=Math.max(0,Math.min(1,H.nx+U.dnx)),ne=Math.max(0,Math.min(1,H.ny+U.dny));k.current={nx:q,ny:ne},N({nx:q,ny:ne}),g(`Cursor: ${Math.round(q*100)}%, ${Math.round(ne*100)}%`),X(q,ne,i.current);const E=Date.now();E-h.current>=30&&(h.current=E,S.current("input_mouseMoved",{nx:q,ny:ne}).catch(()=>{}))}else if(i.current>1){const U=t.current;if(U){const H=U.clientWidth,q=U.clientHeight,ne=c.current+ge/H*100,E=u.current+me/q*100,W=w(ne,E,i.current);m(W.x),d(W.y),c.current=W.x,u.current=W.y}}else{const U=fe(ae);if(U){const H=Date.now();H-h.current>=40&&(h.current=H,g("Scroll"),S.current("input_wheel",{nx:U.nx,ny:U.ny,deltaX:Math.round(-ge*2.5),deltaY:Math.round(-me*2.5)}).catch(()=>{}))}}I.current={x:ae.clientX,y:ae.clientY};return}if(xe.touches.length===2&&P.current!==null){const ae=xe.touches[1].clientX-xe.touches[0].clientX,ge=xe.touches[1].clientY-xe.touches[0].clientY,U=Math.sqrt(ae*ae+ge*ge)/P.current,H=(xe.touches[0].clientX+xe.touches[1].clientX)/2,q=(xe.touches[0].clientY+xe.touches[1].clientY)/2,ne=H-R.current.x,E=q-R.current.y,W=Math.abs(U-1)>.03;if(K.current==="mouse"){if(W){const _=Math.max(o,Math.min(5,T.current*U));p(_),i.current=_}else if(Math.abs(ne)>2||Math.abs(E)>2){const _=k.current||{nx:.5,ny:.5},ie=Date.now();ie-h.current>=30&&(h.current=ie,g("Scroll"),S.current("input_wheel",{nx:_.nx,ny:_.ny,deltaX:Math.round(-ne*3),deltaY:Math.round(-E*3)}).catch(()=>{}))}}else{const _=Math.max(o,Math.min(5,T.current*U));p(_),i.current=_;const ie=t.current;if(ie&&_>1){const pe=ie.clientWidth,ue=ie.clientHeight,oe=c.current+ne/pe*100,Pe=u.current+E/ue*100,Ee=w(oe,Pe,_);m(Ee.x),d(Ee.y),c.current=Ee.x,u.current=Ee.y}}R.current={x:H,y:q}}},ve=xe=>{var Ne;if(M.current&&clearTimeout(M.current),P.current=null,xe.touches.length===1&&O.current){const ae=xe.touches[0];x.current={x:ae.clientX,y:ae.clientY,time:Date.now()},I.current={x:ae.clientX,y:ae.clientY},C.current=!0;return}if(xe.touches.length===0){if(O.current){O.current=!1,C.current=!1;return}if(xe.changedTouches.length===1){const ae=xe.changedTouches[0],ge=Date.now(),me=ge-(((Ne=x.current)==null?void 0:Ne.time)||0),U=x.current?ae.clientX-x.current.x:0,H=x.current?ae.clientY-x.current.y:0,q=Math.sqrt(U*U+H*H);if(K.current==="mouse"){if(me<A||me>B||q>L){C.current=!1;return}const ne=k.current||fe(ae);ne&&(g(`Click: ${Math.round(ne.nx*100)}%, ${Math.round(ne.ny*100)}%`),f(ne.nx,ne.ny,"left"),S.current("input_click",{...ne}).catch(()=>{}))}else{if(C.current){C.current=!1;return}if(me<$||me>F||q>z){C.current=!1;return}const ne=fe(ae);if(!ne)return;ge-D.current<300?(g("Double tap"),f(ne.nx,ne.ny,"double"),S.current("input_click",{...ne,clickCount:2}).catch(()=>{}),D.current=0):(g(`Tap: ${Math.round(ne.nx*100)}%, ${Math.round(ne.ny*100)}%`),f(ne.nx,ne.ny,"left"),S.current("input_click",{...ne}).catch(()=>{}),D.current=ge)}}C.current=!1}};return se.addEventListener("touchstart",Q,{passive:!1}),se.addEventListener("touchmove",we,{passive:!1}),se.addEventListener("touchend",ve,{passive:!1}),()=>{se.removeEventListener("touchstart",Q),se.removeEventListener("touchmove",we),se.removeEventListener("touchend",ve),M.current&&clearTimeout(M.current)}},[e,t,r,o,i,c,u,m,d,p,h,g,f,w]),{cursorPos:v,cursorPosRef:k,handleToggleInputMode:()=>{a(se=>{const fe=se==="touch"?"mouse":"touch";return fe==="mouse"&&re(),fe})},handleZoomReset:()=>{const se=j?y:1;p(se),i.current=se,m(0),d(0),c.current=0,u.current=0}}}function yd({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:o}){const i=l.useRef(null),c=l.useRef(null),u=l.useRef(null),[m,d]=l.useState(null),[p,h]=l.useState(""),[,b]=l.useState(!1),[g,f]=l.useState([]),w=l.useRef(0),[j,y]=l.useState(!1),[v,N]=l.useState(!1),k=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[x,I]=l.useState(k?"mouse":"touch"),[C,M]=l.useState(1),D=l.useRef(!1),[P,T]=l.useState(1),[R,O]=l.useState(0),[K,S]=l.useState(0);Br("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:x,zoom:P,panX:R,panY:K,isMenuOpen:j,isImeOpen:v});const A=l.useRef(0),B=l.useRef(P),L=l.useRef(R),$=l.useRef(K);l.useEffect(()=>{B.current=P},[P]),l.useEffect(()=>{L.current=R},[R]),l.useEffect(()=>{$.current=K},[K]),l.useEffect(()=>{var me;(me=i.current)==null||me.focus()},[]);const F=r==="connected",z=n,re=F?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",J=F?"The remote stream is warming up":"Waiting for the remote stream to catch up";l.useEffect(()=>{if(!k||D.current||!z)return;const me=u.current,U=c.current;if(!me||!U)return;const H=()=>{const q=U.clientWidth,ne=U.clientHeight,E=me.naturalWidth,W=me.naturalHeight;if(!E||!W||!q||!ne)return;const _=Math.min(q/E,ne/W),pe=Math.max(q/E,ne/W)/_;pe>1.01&&(M(pe),T(pe),B.current=pe),D.current=!0};me.complete&&me.naturalWidth?H():me.addEventListener("load",H,{once:!0})},[z,k]);const Y=.5;l.useEffect(()=>{P<=Y&&(O(0),S(0))},[P,Y]);const se=(me,U,H)=>{if(H<=Y)return{x:0,y:0};const q=(H-1)/(2*H)*100,ne=(H-1)/(2*H)*100;return{x:Math.max(-q,Math.min(q,me)),y:Math.max(-ne,Math.min(ne,U))}},fe=(me,U)=>{if(!u.current)return null;const H=u.current.getBoundingClientRect();return!H.width||!H.height?null:{nx:Math.max(0,Math.min(1,(me-H.left)/H.width)),ny:Math.max(0,Math.min(1,(U-H.top)/H.height))}},be=(me,U,H)=>{const q=c.current;if(!q)return;const ne=q.getBoundingClientRect(),E=++w.current;f(W=>[...W,{id:E,x:me-ne.left,y:U-ne.top,type:H}]),setTimeout(()=>f(W=>W.filter(_=>_.id!==E)),600)},X=(me,U,H)=>{const q=u.current,ne=c.current;if(!q||!ne)return;const E=q.getBoundingClientRect(),W=ne.getBoundingClientRect(),_=q.naturalWidth||E.width,ie=q.naturalHeight||E.height,pe=_/ie,ue=E.width/E.height;let oe,Pe,Ee,$e;pe>ue?(oe=E.width,Pe=E.width/pe,Ee=0,$e=(E.height-Pe)/2):(Pe=E.height,oe=E.height*pe,Ee=(E.width-oe)/2,$e=0);const He=E.left-W.left+Ee+oe*me,Xe=E.top-W.top+$e+Pe*U,Je=++w.current;f(nt=>[...nt,{id:Je,x:He,y:Xe,type:H}]),setTimeout(()=>f(nt=>nt.filter(et=>et.id!==Je)),600)},Q=async me=>{var H;const U=fe(me.clientX,me.clientY);if(U){d(`Click: ${Math.round(U.nx*100)}%, ${Math.round(U.ny*100)}%`),be(me.clientX,me.clientY,"left"),(H=i.current)==null||H.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}`)}}},we=async(me,U,H,q=0)=>{try{await e("input_key",{type:H?"char":"keyDown",key:me,code:U,text:H?me:void 0,unmodifiedText:H?me:void 0,modifiers:q})}catch(ne){t(`❌ Key error: ${ne.message||ne}`)}},ve=async me=>{if(me.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(me.key)&&me.preventDefault();let H=0;me.altKey&&(H|=1),me.ctrlKey&&(H|=2),me.metaKey&&(H|=4),me.shiftKey&&(H|=8),d(`Key: ${me.key}`),await we(me.key,me.code,me.key.length===1,H)},xe=async me=>{if(me.key==="Enter"){if(me.nativeEvent.isComposing)return;if(p){const U=p;h(""),d(`IME Sent: ${U}`);try{const H=await e("input_type",{text:U});H!=null&&H.success||t(`❌ IME error: ${H==null?void 0:H.error}`)}catch(H){t(`❌ IME error: ${H.message}`)}}else d("Key: Enter"),await we("Enter","Enter",!1)}};l.useEffect(()=>{const me=i.current;if(!me)return;const U=H=>{var q;if((q=u.current)!=null&&q.contains(H.target)){H.preventDefault();const ne=Date.now();if(ne-A.current<40)return;A.current=ne;const E=fe(H.clientX,H.clientY);if(!E)return;d(`Scroll: ${Math.round(H.deltaY)}`),e("input_wheel",{nx:E.nx,ny:E.ny,deltaX:Math.round(H.deltaX),deltaY:Math.round(H.deltaY)}).catch(()=>{})}};return me.addEventListener("wheel",U,{passive:!1}),()=>me.removeEventListener("wheel",U)},[e]);const{cursorPos:Ne,handleToggleInputMode:ae,handleZoomReset:ge}=hf({containerRef:i,viewportRef:c,imgRef:u,inputMode:x,setInputMode:I,minZoom:Y,zoomRef:B,panXRef:L,panYRef:$,setPanX:O,setPanY:S,setZoom:T,lastWheelTimeRef:A,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:X,clampPan:se,isMobile:k,mobileFillZoom:C});return s.jsxs("div",{ref:i,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ve,onContextMenu:me=>me.preventDefault(),onFocus:()=>b(!0),onBlur:()=>b(!1),tabIndex:0,children:[s.jsxs("div",{ref:c,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[z?s.jsx("img",{ref:u,src:z,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${P}) translate(${R}%, ${K}%)`,transformOrigin:"center center",cursor:x==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:Q,onContextMenu:me=>me.preventDefault(),onDragStart:me=>me.preventDefault()}):s.jsx(mf,{waitingLabel:re,waitingHint:J,transportType:o}),x==="mouse"&&z&&s.jsx(df,{cursorPos:Ne,viewportRef:c,imgRef:u}),g.map(me=>{const H={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(${H}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),s.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${H}, 0.9)`,boxShadow:`0 0 12px rgba(${H}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},me.id)})]}),s.jsx(uf,{inputMode:x,onToggleInputMode:ae,isImeOpen:v,setIsImeOpen:N,isMenuOpen:j,setIsMenuOpen:y,imeText:p,setImeText:h,handleImeSubmit:xe,isConnActive:F,zoom:P,isMobile:k,mobileFillZoom:C,onZoomOut:()=>T(me=>Math.max(.5,me-.25)),onZoomReset:ge,onZoomIn:()=>T(me=>Math.min(5,me+.25)),transportType:o,screenshotUsage:a,lastActionStatus:m}),s.jsx("style",{children:`
7
+ @keyframes slideUp {
8
+ from { opacity: 0; transform: translateY(6px); }
9
+ to { opacity: 1; transform: translateY(0); }
10
+ }
11
+ @keyframes slideUpSidebar {
12
+ from { opacity: 0; transform: translateY(6px); }
13
+ to { opacity: 1; transform: translateY(0); }
14
+ }
15
+ @keyframes click-ripple-ring {
16
+ 0% { transform: scale(0.3); opacity: 1; }
17
+ 100% { transform: scale(2.2); opacity: 0; }
18
+ }
19
+ @keyframes click-ripple-dot {
20
+ 0% { transform: scale(1); opacity: 0.9; }
21
+ 50% { transform: scale(1.8); opacity: 0.6; }
22
+ 100% { transform: scale(0.5); opacity: 0; }
23
+ }
24
+ @keyframes remote-float {
25
+ 0% { transform: translateY(0px); }
26
+ 50% { transform: translateY(-7px); }
27
+ 100% { transform: translateY(0px); }
28
+ }
29
+ `})]})}function al(e){if(!e||typeof e!="object")return null;const t=e;return typeof t.promptId!="string"||!t.promptId.trim()||typeof t.providerType!="string"||!t.providerType.trim()||!Array.isArray(t.questions)||t.questions.length===0?null:t}function ff(e){var t;return al(e.activeInteractivePrompt)||al((t=e.activeChat)==null?void 0:t.activeInteractivePrompt)}function xf(e){return e.sessionId||e.instanceId||e.id}function bf(e,t){const r=typeof t=="string"?t.trim():"";for(const n of e){const a=ff(n);if(!a)continue;const o=xf(n);if(r&&r!==o&&r!==n.id)continue;return{daemonId:n.daemonId||n.id.split(":")[0]||n.id,sessionId:o,routeId:n.id,providerType:n.type,title:n.title||n.cliName||n.type,prompt:a}}return null}function vd(e,t){var n;const r={};for(const a of e.questions){const o=t[a.questionId]||{},i=Array.from(new Set((o.selectedLabels||[]).map(u=>u.trim()).filter(Boolean))),c=(n=o.freeformText)==null?void 0:n.trim();r[a.questionId]={selectedLabels:i,...c?{freeformText:c}:{}}}return{promptId:e.promptId,answers:r}}function ol(e){const t={};for(const r of(e==null?void 0:e.prompt.questions)||[])t[r.questionId]={selectedLabels:[],freeformText:""};return t}function il(e,t){var r,n;return!!((r=t==null?void 0:t.freeformText)!=null&&r.trim())||(((n=t==null?void 0:t.selectedLabels)==null?void 0:n.length)||0)>0||e.options.length===0&&e.allowFreeform}function gf({label:e,description:t,selected:r,multiSelect:n,disabled:a,onClick:o}){return s.jsx("button",{type:"button",disabled:a,role:n?"checkbox":"radio","aria-checked":r,onClick:o,className:`w-full text-left rounded-md border px-3 py-2 transition ${r?"border-accent-primary bg-accent-primary/15 text-text-primary":"border-border-primary bg-surface-secondary text-text-secondary hover:bg-surface-tertiary hover:text-text-primary"} ${a?"cursor-not-allowed opacity-60":""}`,children:s.jsxs("span",{className:"flex items-start gap-2",children:[s.jsx("span",{className:`mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center border ${n?"rounded-sm":"rounded-full"} ${r?"border-accent-primary bg-accent-primary text-accent-on-primary":"border-border-secondary"}`,children:r?s.jsx(dd,{size:12}):null}),s.jsxs("span",{className:"min-w-0",children:[s.jsx("span",{className:"block text-sm font-semibold leading-5",children:e}),t&&s.jsx("span",{className:"mt-0.5 block text-xs leading-5 text-text-muted",children:t})]})]})})}function wd({promptSession:e,isSubmitting:t=!1,error:r,onSubmit:n,onCancel:a}){var I;const[o,i]=l.useState(()=>ol(e)),[c,u]=l.useState(0);l.useEffect(()=>{i(ol(e)),u(0)},[e==null?void 0:e.prompt.promptId]);const m=(e==null?void 0:e.prompt.questions)||[],d=m.length,p=c===d-1,h=d===1,b=m[c],g=b?o[b.questionId]:void 0,f=b?il(b,g):!1,w=l.useMemo(()=>e?e.prompt.questions.every(C=>il(C,o[C.questionId])):!1,[e,o]);if(!e)return null;const j=(C,M)=>{i(D=>{const P=D[C.questionId]||{selectedLabels:[]},T=P.selectedLabels||[],R=C.multiSelect?T.includes(M)?T.filter(O=>O!==M):[...T,M]:[M];return{...D,[C.questionId]:{...P,selectedLabels:R}}})},y=(C,M)=>{i(D=>({...D,[C]:{...D[C]||{selectedLabels:[]},freeformText:M}}))},v=()=>{c<d-1&&u(C=>C+1)},N=()=>{c>0&&u(C=>C-1)},k=()=>{!w||t||n(o)},x=vd(e.prompt,o);return s.jsx("div",{className:"fixed inset-0 z-[80] flex items-center justify-center bg-black/50 px-4 py-6",children:s.jsxs("div",{className:"w-full max-w-2xl overflow-hidden rounded-lg border border-border-primary bg-surface-primary shadow-2xl",children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 border-b border-border-primary px-5 py-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 text-xs font-bold uppercase tracking-normal text-status-warning",children:[s.jsx(zs,{size:15})," Action Required"]}),s.jsx("h2",{className:"mt-1 text-lg font-bold text-text-primary",children:e.title||e.providerType})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[!h&&s.jsxs("span",{className:"text-xs text-text-muted",children:[c+1," / ",d]}),s.jsx("button",{type:"button",onClick:a,className:"btn btn-ghost btn-sm h-8 w-8 p-0","aria-label":"Cancel interactive prompt",children:s.jsx(vt,{size:16})})]})]}),!h&&s.jsx("div",{className:"flex gap-1.5 px-5 pt-3",children:m.map((C,M)=>s.jsx("div",{className:`h-1.5 flex-1 rounded-full transition-colors ${M<c?"bg-accent-primary":M===c?"bg-accent-primary/60":"bg-border-primary"}`},C.questionId))}),s.jsxs("div",{className:"space-y-4 px-5 py-4",children:[b&&s.jsxs("section",{className:"space-y-3",children:[s.jsxs("div",{children:[b.header&&s.jsx("div",{className:"mb-1 text-xs font-semibold uppercase tracking-normal text-text-muted",children:b.header}),s.jsxs("div",{className:"text-sm font-semibold text-text-primary",children:[h?"":`${c+1}. `,b.question]}),b.multiSelect&&b.options.length>0&&s.jsx("div",{className:"mt-0.5 text-xs text-text-muted",children:"Select all that apply"})]}),s.jsx("div",{className:"grid gap-2",role:b.multiSelect?"group":"radiogroup","aria-label":b.question,children:b.options.map(C=>{var M;return s.jsx(gf,{label:C.label,description:C.description||C.preview,selected:(((M=x.answers[b.questionId])==null?void 0:M.selectedLabels)||[]).includes(C.label),multiSelect:b.multiSelect,disabled:t,onClick:()=>j(b,C.label)},C.label)})}),b.allowFreeform&&s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-xs font-semibold text-text-muted",children:"Other"}),s.jsx("textarea",{value:((I=o[b.questionId])==null?void 0:I.freeformText)||"",disabled:t,onChange:C=>y(b.questionId,C.currentTarget.value),className:"w-full min-h-20 rounded-md border border-border-primary bg-surface-secondary px-3 py-2 text-sm text-text-primary outline-none focus:border-accent-primary"})]})]}),r&&s.jsx("div",{className:"rounded-md border border-status-error/30 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:r})]}),s.jsxs("div",{className:"flex items-center justify-between gap-2 border-t border-border-primary px-5 py-4",children:[s.jsx("div",{children:!h&&c>0&&s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:N,disabled:t,children:"Back"})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:a,disabled:t,children:"Cancel"}),h||p?s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:k,disabled:!w||t,children:t?"Submitting...":"Submit"}):s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:v,disabled:!f||t,children:"Next"})]})]})]})})}function ca(e,t={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=t,o=Date.now()-e,i=Math.floor(o/1e3);if(i<a)return n;const c=Math.floor(i/60);if(c<60)return`${c}m${r}`;const u=Math.floor(c/60);if(u<24)return`${u}h${r}`;const m=Math.floor(u/24);return m<7?`${m}d${r}`:new Date(e).toLocaleDateString()}const jd=e=>ca(e);function yf(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden,completionMarker:typeof e.completionMarker=="string"?e.completionMarker:"",seenCompletionMarker:typeof e.seenCompletionMarker=="string"?e.seenCompletionMarker:""}}function Vs(e){const t=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating"||e.status==="long_generating"||e.status==="streaming",a=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:r,isGenerating:n,isWaiting:a}}function vf(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...yf(a)})};for(const n of e)if(n.type!=="adhdev-daemon"){r(n.sessionId,n);for(const a of n.childSessions||[])r(a.id,a)}return t}function zn(e,t){if(e.sessionId){const r=t.get(e.sessionId);if(r)return r}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1,completionMarker:"",seenCompletionMarker:""}}function da(e,t,r){const n=zn(e,t),a=Vs(e),o=a.isReconnecting,i=a.isConnecting,c=a.isGenerating,u=a.isWaiting,m=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||u,d=n.inboxBucket==="working"||c,h=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:h,requiresAction:m,isWorking:d,isReconnecting:o,isConnecting:i,isGenerating:c,isWaiting:u,inboxBucket:m?"needs_attention":d?"working":h?"task_complete":"idle"}}function wf(e,t,r){return da(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function kd({activeConv:e,onModalButton:t}){const[r,n]=l.useState(null);if(l.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Vs(e).isWaiting||!e.modalButtons)return null;const o=c=>{r||(n(c),t(c))},i=c=>c.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return s.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&s.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:e.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[s.jsx(zs,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((c,u)=>{const m=i(c).toLowerCase(),d=/^(run|approve|accept|yes|allow|always)/.test(m),p=/^(reject|deny|delete|remove|abort)/.test(m),h=r===c,b=r!==null;return s.jsx("button",{onClick:()=>o(c),disabled:b,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${d?"font-extrabold":p?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${b&&!h?"opacity-40":"opacity-100"} ${b?"cursor-not-allowed":"cursor-pointer"}`,style:d?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:p?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:h?"⏳ ...":i(c)},u)})})]})]})}const Qo="adhdev_controls_bar_visible",wo="adhdev:controlsbarvisibilitychange";function Na(e){if(!e)return!1;try{return e.getItem(Qo)==="1"}catch{return!1}}function jf(e,t){if(t)try{t.setItem(Qo,e?"1":"0")}catch{}}function kf(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(wo,{detail:{visible:e}}))}function Zo(){const[e,t]=l.useState(()=>typeof window>"u"?!1:Na(window.localStorage)),r=l.useRef(e),n=l.useCallback((i,c=!0)=>{r.current=i,t(i),typeof window<"u"&&jf(i,window.localStorage),c&&kf(i)},[]);l.useEffect(()=>{const i=u=>{const m=u.detail,d=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:Na(window.localStorage);r.current=d,t(d)},c=u=>{if(u.key!==Qo)return;const m=Na(window.localStorage);r.current=m,t(m)};return window.addEventListener(wo,i),window.addEventListener("storage",c),()=>{window.removeEventListener(wo,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{n(i)},[n]),o=l.useCallback(()=>{n(!r.current)},[n]);return{isVisible:e,setVisibility:a,toggleVisibility:o}}var Nf=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Sf(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function Lt(e,t){if(Sf(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":r==="waiting_choice"?"waiting_choice":Nf.has(r)?"generating":r==="error"?"error":r==="stopped"?"stopped":r==="starting"?"starting":r==="panel_hidden"?"panel_hidden":r==="not_monitored"?"not_monitored":r==="disconnected"?"disconnected":"idle"}function jo(e){return Lt(e)==="generating"}function ll(e,t){return Lt(e,t)==="waiting_approval"}function wt(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function Cf(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const r=Math.floor(t/60),n=t%60;if(r<24)return n>0?`${r}h ${n}m`:`${r}h`;const a=Math.floor(r/24),o=r%24;return`${a}d ${o}h`}function Sa(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Nd(e,t){const r=typeof t=="string"?t.trim():"";if(r)return r;const n=typeof e=="string"?e.trim():"";if(!n)return"";const a=n.replace(/[\\/]+$/,""),o=a.split(/[\\/]/).filter(Boolean);return o[o.length-1]||a}function If(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const t=e.split("_"),r=t[t.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return e}function Mf(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function Af(e){return If(e.trim().replace(/\.local$/i,""))}function Tf(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function Sd(e,t={}){var a,o;const r=[e.hostname,(a=e.machine)==null?void 0:a.hostname,(o=e.system)==null?void 0:o.hostname].find(i=>typeof i=="string"&&i.trim().length>0&&!Mf(i));if(r&&r!=="Unknown")return Af(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Pt(e,t={}){return Tf(e)||Sd(e,t)}function Cd(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 Id(e,t,r={}){const n=String(t).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(o=>String((o==null?void 0:o.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function Ns(e,t){return Cd(e).join(" · ")}function Ar(e){return e.transport==="pty"}function $s(e){return e.transport==="acp"}function _f(e,t){var r,n;return(r=t==null?void 0:t.providerLabels)!=null&&r[e]?t.providerLabels[e]:(n=t==null?void 0:t.providerLabels)!=null&&n[e==null?void 0:e.toLowerCase()]?t.providerLabels[e.toLowerCase()]:t!=null&&t.agentName&&t.agentName!==e?t.agentName:wt(e)}function cl(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),i=wt(r||"").trim().toLowerCase();return n===a||n===o||n===i}function Lf(e,t=[],r=[]){var u,m,d,p;const n=Lt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal});if(n==="waiting_approval")return"waiting_approval";if(n==="waiting_choice")return"waiting_choice";if(n==="generating")return"generating";const a=t.find(h=>ll(h.status,{activeModal:h.activeModal})||jo(h.status));if(a)return Lt(a.status,{activeModal:a.activeModal});const o=r.find(h=>ll(h.status,{activeModal:h.activeModal})||jo(h.status));if(o)return Lt(o.status,{activeModal:o.activeModal});if(n&&n!=="idle")return n;const i=Lt((u=t[0])==null?void 0:u.status,{activeModal:(m=t[0])==null?void 0:m.activeModal});if(i!=="idle")return i;const c=Lt((d=r[0])==null?void 0:d.status,{activeModal:(p=r[0])==null?void 0:p.activeModal});return c!=="idle"?c:"idle"}function Pf(e){return Lt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Rf(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,r=["generating","waiting_approval","waiting_choice","connected","idle","panel_hidden"];for(const n of e){const a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),o=t.get(a),i=Lt(n.status);if(!o){t.set(a,{...n,status:i});continue}const c=r.indexOf(o.status||"idle"),u=r.indexOf(i||"idle");u>=0&&(c<0||u<c)&&t.set(a,{...n,status:i})}return Array.from(t.values())}function Df(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 $f(e){var r,n;const t=(n=(r=e==null?void 0:e.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return t&&Df(t.receivedAt)||0}function Ef(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function ko(e){return Math.max(Ef(e),$f(e.activeChat))}function Bf(e,t,r,n,a,o){const i=t-e;if(i!==0)return i;const c=r.localeCompare(n);return c!==0?c:a.localeCompare(o)}function ei(e,t){return Bf(ko(e),ko(t),Pt(e,{fallbackId:e.id}),Pt(t,{fallbackId:t.id}),e.id,t.id)}const Md="adhdev_notification_prefs",dl={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Ff(){try{const e=localStorage.getItem(Md);if(e){const t=JSON.parse(e);return{...dl,...t}}}catch{}return{...dl}}function Of(e){try{localStorage.setItem(Md,JSON.stringify(e))}catch{}}let Jt=Ff(),Nn=[];function zf(){Nn.forEach(e=>e())}function Hf(e){Jt={...Jt,...e},Of(Jt),zf()}function Wf(){const[,e]=l.useState(0);l.useEffect(()=>{const r=()=>e(n=>n+1);return Nn.push(r),()=>{Nn=Nn.filter(n=>n!==r)}},[]);const t=l.useCallback(r=>{Hf(r)},[]);return[{...Jt},t]}function yr(e){if(!Jt.globalEnabled)return!1;switch(e){case"disconnect":return Jt.disconnectAlert;case"completion":return Jt.completionAlert;case"approval":return Jt.approvalAlert;case"browser":return Jt.browserNotifications;default:return!0}}const Kf={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Ad(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Td(){return"Notification"in window&&Notification.permission==="granted"}let ms=null;function Uf(e){return e!==!1}async function Gf(){if(ms!==null)return ms;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return ms=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(ms=!!await e.pushManager.getSubscription(),ms):(ms=!1,!1)}catch{return ms=!1,!1}}function No(e,t,r){if(Td())try{const n=new Notification(e,{body:t,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function Vf(e,t={}){const r={...Kf,...t},n=l.useRef(new Map),a=l.useRef(0),[o,i]=l.useState(null);l.useEffect(()=>{let u=!1;return Gf().then(m=>{u||i(m)}),()=>{u=!0}},[]);const c=l.useCallback((u,m,d)=>{const p=Date.now();p-a.current<r.throttleMs||(a.current=p,No(u,m,d))},[r.throttleMs]);l.useEffect(()=>{var u;if(!(!r.enabled||!Td())&&yr("browser")&&!Uf(o)){if(document.hasFocus()){for(const m of e)n.current.set(m.id,Lt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const d=n.current.get(m.id),p=Lt(m.status,{activeModal:m.activeModal}),h=m.name||m.id;if(r.onApproval&&yr("approval")&&p==="waiting_approval"&&d!=="waiting_approval"){const b=((u=m.activeModal)==null?void 0:u.message)||"Action requires your approval";c(`🔔 ${h} — Approval needed`,b.slice(0,120),`approval-${m.id}`)}r.onComplete&&yr("completion")&&jo(d)&&p==="idle"&&c(`✅ ${h} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&p==="error"&&d!=="error"&&c(`⚠️ ${h} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,p)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,c])}const qf=/^(run|approve|accept|yes|allow|always)/,Yf=/^(run|approve|accept|yes|allow|always|proceed|save)/,Jf=/^(reject|deny|delete|remove|abort|cancel|no)/;function ti(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Xf(e){const t=ti(e).toLowerCase();return qf.test(t)?"primary":Jf.test(t)?"danger":"default"}function Qf(e){return Yf.test(ti(e).toLowerCase())?"approve":"reject"}function Zf(e){return e.map((t,r)=>({label:ti(t),variant:Xf(t),action:Qf(t),button:t,buttonIndex:r}))}function ex(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function tx(e,t,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,t,"approve").catch(a=>n==null?void 0:n("approve",a))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,t,"reject").catch(a=>n==null?void 0:n("reject",a))}}]}class sx{constructor(){Ue(this,"dedupMap",new Map);Ue(this,"DEDUP_WINDOW_MS",5e3);Ue(this,"DEDUP_MAX_SIZE",50);Ue(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ue(this,"toastCallbacks",[]);Ue(this,"statusEventCallbacks",[]);Ue(this,"resolveActionFn",null);Ue(this,"viewRequestRespondFn",null);Ue(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(r=>r!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const r of this.toastCallbacks)r(t)}showToast(t,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:t,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(t){const r=Date.now(),n=this.dedupMap.get(t)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,o]of this.dedupMap)r-o>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(t){if(t.daemonId){const a=this.ides.find(o=>o.id===t.daemonId&&o.type==="adhdev-daemon");if(a)return a}const r=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const o=this.ides.find(i=>i.id===a&&i.type==="adhdev-daemon");if(o)return o}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(t){for(const r of this.ides)if(r.id===t||r.sessionId===t||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===t))return r;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const r=this.findOwningSession(t.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}handleRawEvent(t,r){var g;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),o=n||t.daemonId||"",i=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),c=`${o}:${t.event}:${i}`;if(this.isDuplicate(c))return;for(const f of this.statusEventCallbacks)f(t);const u=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(u==null?void 0:u.type)||"";let d=wt(m);const p=this.resolveOwningDaemon(t);if(p){const f=Pt(p,{fallbackId:p.id});f&&(d=!m||m==="adhdev-daemon"?f:`${f}/${d}`)}let h="",b="info";if(t.event==="agent:generating_completed"){const f=t.duration?` (${t.duration}s)`:"";h=`✅ ${d} agent task completed${f}`,b="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(t.event!=="agent:generating_started")if(t.event==="agent:waiting_approval"){if(h=`⚡ ${d} approval needed`,b="warning",(g=t.modalButtons)!=null&&g.length&&this.resolveActionFn){const f=this.resolveActionRouteTarget(t);if(!f)return;const w=this.resolveActionFn,j=Zf(t.modalButtons).map(N=>({label:N.label,variant:N.variant,onClick:()=>{w(f,"resolve_action",{action:N.action,button:N.button,buttonIndex:N.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),y=ex(d,t.modalMessage,h),v=Date.now();this.emitToast({id:v,message:y,type:b,timestamp:v,targetKey:n||f,actions:j,duration:15e3}),h=""}}else if(t.event==="monitor:long_generating"){const f=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";h=`⚠️ ${d} agent is taking a long time${f}`,b="warning",yr("browser")&&!document.hasFocus()&&No(`⚠️ ${d} — Long Running`,`Agent has been generating for over ${f.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const f=t.requesterName||"A team member",w=t.requestId,j=t.orgId;if(h=`👁️ ${f} wants to view your session`,b="warning",w&&j&&this.viewRequestRespondFn){const y=Date.now(),v=tx(j,w,this.viewRequestRespondFn,(N,k)=>console.error(`[EventManager] ${N} view request failed:`,k));this.emitToast({id:y,message:h,type:b,timestamp:y,actions:v,duration:3e4}),h=""}yr("browser")&&!document.hasFocus()&&No("👁️ View Request",`${f} wants to view your session`,`view-request-${w}`)}else t.event==="team:view_request_approved"?(h="✅ View request approved",b="success"):t.event==="team:view_request_rejected"&&(h=`❌ ${t.targetName||"Team member"} declined your view request`,b="warning");if(h){const f=Date.now();this.emitToast({id:f,message:h,type:b,timestamp:f,targetKey:n||t.daemonId,duration:5e3})}}}const tt=new sx,ul=new Map;function Hn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Es(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function ua(e){return Hn(e)?Hn(e.result)?e.result:e:null}function rx(e){const t=ua(e);return!t||!Hn(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function nn(e){const t=ua(e);return!t||!Hn(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function tr(e){const t=ua(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function an(e){const t=ua(e);return!!t&&t.success===!1}function nx(e){var t,r;for(const n of e||[]){if(n.type==="toast"&&((t=n.toast)!=null&&t.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";tt.showToast(n.toast.message,a);continue}if(n.type==="notification"&&((r=n.notification)!=null&&r.body)){const a=n.notification.level==="warning"?"warning":n.notification.level==="success"?"success":"info";tt.showToast(n.notification.body,a)}}}function ax(e,t){return e&&Es(e.currentValue)?e.currentValue:t}function ox(e,t){return Es(t)?Es(e)?typeof e=="string"&&e.trim()==="":!0:!1}function ix(e,t){var o,i;if((t.now??Date.now())<t.localOverrideUntil){const c=t.localValues[e];if(Es(c))return c}const n=(o=t.controlValues)==null?void 0:o[e];if(Es(n))return n;const a=(i=t.defaultValues)==null?void 0:i[e];return Es(a)?a:void 0}function Sn(e,t){return e.options||t[e.id]||[]}const lx={antigravity:new Set(["new_session"]),"claude-cli":new Set(["compact","new_session"]),"claude-code-vscode":new Set(["new_session"]),codex:new Set(["new_session"])};function cx(e,t,r){var n;return((n=lx[t])==null?void 0:n.has(r.id))===!0}function si(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!cx(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function Ca(e,t){return{value:t}}function dx(e,t,r){var a;return r?((a=Sn(e,t).find(o=>o.value===r))==null?void 0:a.label)||r:""}const ux={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function mx({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:i}){const{sendCommand:c}=lt(),u=`${e}:${t||n}`,m=ux[n]||"#94a3b8",[d,p]=l.useState({}),h=l.useRef({}),b=l.useRef(i);h.current=d,b.current=i;const g=l.useRef(0),f={};for(const A of o||[])A.defaultValue!==void 0&&(f[A.id]=A.defaultValue);const w={...f,...i||{},...Date.now()<g.current?d:{}};l.useEffect(()=>{i&&Date.now()>g.current&&p({})},[i]);const[j,y]=l.useState(ul.get(u)||{}),[v,N]=l.useState(null),[k,x]=l.useState(null),I=l.useCallback(async(A,B={})=>{const L={...B,...t&&{targetSessionId:t}};return await c(e,A,L)},[e,t,c]),C=l.useCallback(async(A,B={})=>{const L=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await I("invoke_provider_script",{...L,scriptName:A,...B})},[I,n,r,t]),M=l.useCallback((A,B,L)=>{const $=ax(L,B);p(F=>({...F,[A.id]:$})),nx(L==null?void 0:L.effects)},[]),D=l.useCallback((A,B)=>{p(L=>{const $={...L};return B===void 0?delete $[A.id]:$[A.id]=B,$}),g.current=0},[]);if(!o||o.length===0)return null;const P=si(o,{hostIdeType:r,providerType:n});if(P.length===0)return null;const T=async A=>{if(v===A.id){N(null);return}if(Sn(A,j).length>0){N(A.id);return}if(A.dynamic&&A.listScript){x(A.id);try{const L=await C(A.listScript,{}),$=rx(L);if(!$){const re=tr(L);re&&tt.showToast(re,"warning");return}const F=$.options;y(re=>{const J={...re,[A.id]:F};return ul.set(u,J),J});const z=ix(A.id,{localOverrideUntil:g.current,localValues:h.current,controlValues:b.current,defaultValues:f});if(ox(z,$.currentValue)){const re=$.currentValue;p(J=>({...J,[A.id]:re}))}N(A.id)}catch(L){const $=L instanceof Error?L.message:`Could not load ${A.label}`;tt.showToast($,"warning")}finally{x(null)}}},R=async(A,B)=>{N(null);const L=(i==null?void 0:i[A.id])??f[A.id];p($=>({...$,[A.id]:B})),g.current=Date.now()+5e3;try{if(!A.setScript)return;const $=await C(A.setScript,Ca(A,B)),F=nn($);if(F&&!F.ok||an($))throw new Error((F==null?void 0:F.error)||tr($)||`Could not update ${A.label}`);M(A,B,F)}catch($){D(A,L);const F=$ instanceof Error?$.message:`Could not update ${A.label}`;tt.showToast(F,"warning")}},O=async A=>{const B=Sn(A,j).map(J=>J.value);if(B.length===0)return;const L=String(w[A.id]||""),F=(B.indexOf(L)+1)%B.length,z=B[F];if(typeof z!="string")return;const re=(i==null?void 0:i[A.id])??f[A.id];p(J=>({...J,[A.id]:z})),g.current=Date.now()+5e3;try{if(!A.setScript)return;const J=await C(A.setScript,Ca(A,z)),Y=nn(J);if(Y&&!Y.ok||an(J))throw new Error((Y==null?void 0:Y.error)||tr(J)||`Could not update ${A.label}`);M(A,z,Y)}catch(J){D(A,re);const Y=J instanceof Error?J.message:`Could not update ${A.label}`;tt.showToast(Y,"warning")}},K=async A=>{const L=!w[A.id],$=(i==null?void 0:i[A.id])??f[A.id];p(F=>({...F,[A.id]:L})),g.current=Date.now()+5e3;try{if(!A.setScript)return;const F=await C(A.setScript,Ca(A,L)),z=nn(F);if(z&&!z.ok||an(F))throw new Error((z==null?void 0:z.error)||tr(F)||`Could not update ${A.label}`);M(A,L,z)}catch(F){D(A,$);const z=F instanceof Error?F.message:`Could not update ${A.label}`;tt.showToast(z,"warning")}},S=async A=>{if(!A.invokeScript)return;if(A.confirmMessage){const L=[A.confirmTitle,A.confirmMessage,A.confirmLabel].filter(F=>typeof F=="string"&&F.trim().length>0);if(!window.confirm(L.join(`
30
+
31
+ `)))return}const B=(i==null?void 0:i[A.id])??f[A.id];try{const L=await C(A.invokeScript),$=nn(L);if($&&!$.ok||an(L))throw new Error(($==null?void 0:$.error)||tr(L)||`Could not run ${A.label}`);$&&M(A,B??!0,$)}catch(L){D(A,B);const $=L instanceof Error?L.message:`Could not run ${A.label}`;tt.showToast($,"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(A=>{const B=String(w[A.id]||""),L=dx(A,j,B),$=v===A.id,F=k===A.id,z=Sn(A,j),re="inline-flex h-7 max-w-full items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium transition-colors whitespace-nowrap";switch(A.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${re} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:$?`${m}55`:"var(--border-default)",background:$?`${m}10`:"var(--surface-tertiary)",color:B?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void T(A),title:A.label,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:F?"Loading…":L||A.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),$&&z.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>N(null)}),s.jsxs("div",{className:"absolute bottom-full left-0 z-[60] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[s.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:A.label}),z.map(J=>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:J.value===B?`${m}14`:"transparent",color:J.value===B?"var(--text-primary)":"var(--text-secondary)",borderLeft:J.value===B?`2px solid ${m}`:"2px solid transparent"},title:J.description||J.label,onMouseEnter:Y=>{Y.currentTarget.style.background=`${m}10`},onMouseLeave:Y=>{Y.currentTarget.style.background=J.value===B?`${m}14`:"transparent"},onClick:()=>void R(A,J.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:J.label}),J.value===B&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},J.value))]})]})]},A.id);case"cycle":return s.jsxs("button",{type:"button",className:`${re} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:B?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void O(A),title:`Click to cycle: ${z.map(J=>J.label).join(" → ")}`,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:L||A.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},A.id);case"toggle":return s.jsxs("button",{type:"button",className:`${re} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:B?`${m}44`:"var(--border-default)",background:B?`${m}14`:"var(--surface-tertiary)",color:B?m:"var(--text-muted)"},onClick:()=>void K(A),"aria-pressed":!!B,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),A.label]},A.id);case"action":return s.jsxs("button",{type:"button",className:`${re} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void S(A),children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:A.resultDisplay==="inline"&&B?`${A.label}: ${B}`:A.label})]},A.id);case"display":return s.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:B?"var(--text-primary)":"var(--text-muted)"},children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:B?`${A.label}: ${B}`:A.label})]},A.id);default:return null}})]})})}function px({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:i,controls:c,controlValues:u}){const{isVisible:m}=Zo(),d=si(c,{hostIdeType:a,providerType:o});return!e||t||d.length===0||!m?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(mx,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:i,controls:d,controlValues:u})})}const sr=5,_d=10*1024*1024;function hx({hasDraft:e,isBusy:t=!1}){return!e||t}function fx(e){return new Promise((t,r)=>{const n=new FileReader;n.onload=()=>t(n.result),n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(e)})}async function xx(e){if(e.size>_d)return null;const t=await fx(e),r=t.indexOf(",");if(r<0)return null;const n=t.slice(r+1);return{mimeType:e.type||"image/png",data:n,name:e.name,previewUrl:t}}function bx(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const Ld=l.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:o=null,onSend:i,onForceSend:c,canForceSend:u=!1,isActive:m=!0,showControlsToggle:d=!1,animateVisibility:p=!0,onControlsToggle:h,messageInput:b}){const g=l.useRef(null),f=l.useRef(null),[w,j]=l.useState(""),[y,v]=l.useState([]),[N,k]=l.useState(null),[x,I]=l.useState(!1),C=l.useRef(!1),{isVisible:M,toggleVisibility:D}=Zo(),P=bx(b),T=!!w.trim()||y.length>0;l.useEffect(()=>{j(""),v([]),k(null)},[t]),l.useEffect(()=>{var $;m&&(($=g.current)==null||$.focus({preventScroll:!0}))},[t,m]),l.useEffect(()=>{const $=g.current;$&&($.style.height="auto",$.style.height=`${Math.min($.scrollHeight,160)}px`)},[w]);const R=l.useCallback(async $=>{k(null);const F=Array.from($).filter(fe=>fe.type.startsWith("image/"));if(F.length===0)return;const z=sr-y.length;if(z<=0){k(`Max ${sr} images`);return}const re=F.slice(0,z);if(re.filter(fe=>fe.size>_d).length>0){k("Image too large (max 10 MB)");return}const se=(await Promise.all(re.map(xx))).filter(fe=>fe!==null);v(fe=>[...fe,...se])},[y.length]),O=l.useCallback($=>{v(F=>F.filter((z,re)=>re!==$))},[]),K=l.useCallback(async()=>{const $=w.trim();if(!$&&y.length===0||a||C.current)return;C.current=!0;const F=y.length>0?[...y]:void 0;try{await i($,F)!==!1&&(j(""),v([]),k(null))}finally{C.current=!1}},[w,y,a,i]),S=l.useCallback(async()=>{if(!u||!c)return;const $=w.trim();if(!$&&y.length===0||C.current)return;C.current=!0;const F=y.length>0?[...y]:void 0;try{await c($,F)!==!1&&(j(""),v([]),k(null))}finally{C.current=!1}},[y,u,w,c]),A=l.useCallback($=>{P&&($.preventDefault(),I(!0))},[P]),B=l.useCallback(()=>I(!1),[]),L=l.useCallback($=>{P&&($.preventDefault(),I(!1),$.dataTransfer.files.length>0&&R($.dataTransfer.files))},[P,R]);return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",p?"transition-all duration-200 ease-out":"",x?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:m?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:m?200:0,opacity:m?1:0,transform:m?"translateY(0)":"translateY(10px)",padding:m?"10px 12px":"0 12px",pointerEvents:m?"auto":"none"},"aria-hidden":!m,onDragOver:A,onDragLeave:B,onDrop:L,children:[y.length>0&&s.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:y.map(($,F)=>s.jsxs("div",{className:"relative group w-14 h-14 rounded-lg overflow-hidden border border-border-subtle shrink-0",style:{background:"var(--surface-secondary)"},children:[s.jsx("img",{src:$.previewUrl,alt:$.name,className:"w-full h-full object-cover"}),s.jsx("button",{type:"button",onClick:()=>O(F),className:"absolute top-0.5 right-0.5 w-4 h-4 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity text-[10px] leading-none","aria-label":`Remove ${$.name}`,children:"✕"})]},F))}),s.jsxs("div",{className:"flex gap-2 items-center",title:m?`Send message to ${r}`:void 0,children:[d&&s.jsx("button",{type:"button",onClick:()=>{D(),h==null||h()},"aria-label":M?"Hide controls":"Show controls","aria-pressed":M,title:M?"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:f,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:$=>{$.target.files&&R($.target.files),$.target.value=""}}),s.jsx("button",{type:"button",onClick:()=>{var $;return($=f.current)==null?void 0:$.click()},disabled:y.length>=sr,title:y.length>=sr?`Max ${sr} images`:"Attach image",className:"h-10 w-8 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center disabled:opacity-40","aria-label":"Attach image",children:s.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"})})})]}),s.jsx("div",{className:"flex-1 relative",children:s.jsx("textarea",{ref:g,rows:1,placeholder:o||(P&&y.length>0?"Add a message (optional)...":`Send message to ${r}... (Shift+Enter for newline)`),value:w,onChange:$=>j($.target.value),onPaste:$=>{P&&$.clipboardData.files.length>0&&Array.from($.clipboardData.files).some(z=>z.type.startsWith("image/"))&&($.preventDefault(),R($.clipboardData.files))},onKeyDown:$=>{$.key==="Enter"&&($.nativeEvent.isComposing||$.shiftKey||($.preventDefault(),K()))},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:()=>{K()},disabled:hx({hasDraft:T,isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${T&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:T&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,"aria-label":"Send message",children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:T?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})}),u&&s.jsx("button",{type:"button",onClick:()=>{S()},disabled:!T,className:`h-10 px-3 rounded-full text-[11px] font-medium border border-border-subtle shrink-0 transition-colors ${T?"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"})]}),(N||P&&x)&&s.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${N?"text-red-400":"text-[var(--accent-primary)]"}`,children:N||"Drop image here"}),o&&!N&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:o})]})});function ml(e){if(!e||!Number.isFinite(e))return"—";try{return`${new Date(e).toLocaleString()} (${e})`}catch{return String(e)}}function pl(e){if(!e)return"";const t=Date.now()-e;if(t<0)return"";const r=Math.floor(t/1e3);if(r<60)return`${r}s ago`;const n=Math.floor(r/60);if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function gx({sessionId:e,daemonId:t,onClose:r}){const{sendCommand:n}=lt(),[a,o]=l.useState(!0),[i,c]=l.useState(null),[u,m]=l.useState(null),d=l.useCallback(async()=>{o(!0),m(null);try{const p=await n(t,"get_session_info",{targetSessionId:e}),h=p&&typeof p=="object"?p:{},b=h.result&&typeof h.result=="object"?h.result:h;b!=null&&b.success?c(b):(m((b==null?void 0:b.error)||"Failed to load session info"),c(null))}catch(p){m((p==null?void 0:p.message)||String(p)),c(null)}finally{o(!1)}},[n,t,e]);return l.useEffect(()=>{d()},[d]),l.useEffect(()=>{const p=h=>{h.key==="Escape"&&r()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[r]),s.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Session info",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",onClick:r,style:{pointerEvents:"auto"},children:s.jsxs("div",{className:"bg-[var(--surface-primary)] text-text-primary border border-border-default rounded-lg shadow-xl max-w-2xl w-full max-h-[85vh] flex flex-col",onClick:p=>p.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-border-subtle px-4 py-3",children:[s.jsx("h2",{className:"text-base font-semibold",children:"Session info"}),s.jsx("button",{type:"button",onClick:r,className:"text-text-secondary hover:text-text-primary px-2 py-1 rounded","aria-label":"Close",children:"×"})]}),s.jsxs("div",{className:"overflow-y-auto px-4 py-3 text-sm space-y-4",children:[a&&s.jsx("div",{className:"text-text-secondary",children:"Loading…"}),u&&s.jsx("div",{className:"text-red-500",children:u}),(i==null?void 0:i.session)&&s.jsxs(hl,{title:"Session",children:[s.jsx(Dt,{k:"Session ID",v:s.jsx(rr,{children:i.session.sessionId})}),s.jsx(Dt,{k:"Provider",v:`${i.session.providerName||i.session.providerType} (${i.session.providerType})`}),i.session.transport&&s.jsx(Dt,{k:"Transport",v:i.session.transport}),i.session.workspace&&s.jsx(Dt,{k:"Workspace",v:s.jsx(rr,{children:i.session.workspace})}),s.jsx(Dt,{k:"Spawned at",v:s.jsxs(s.Fragment,{children:[ml(i.session.spawnedAtMs),i.session.spawnedAtMs?s.jsx("span",{className:"text-text-secondary ml-2",children:pl(i.session.spawnedAtMs)}):null]})}),i.session.providerSessionId&&s.jsx(Dt,{k:"Provider session ID",v:s.jsx(rr,{children:i.session.providerSessionId})})]}),(i==null?void 0:i.coordinator)&&s.jsxs(hl,{title:"Mesh coordinator",children:[s.jsx(Dt,{k:"Mesh ID",v:s.jsx(rr,{children:i.coordinator.meshId})}),i.coordinator.cliType&&s.jsx(Dt,{k:"Coordinator CLI",v:i.coordinator.cliType}),s.jsx(Dt,{k:"Started at",v:s.jsxs(s.Fragment,{children:[ml(i.coordinator.startedAt),i.coordinator.startedAt?s.jsx("span",{className:"text-text-secondary ml-2",children:pl(i.coordinator.startedAt)}):null]})}),i.coordinator.injection&&s.jsx(Dt,{k:"Prompt injection",v:`${i.coordinator.injection.mode}${i.coordinator.injection.target?` → ${i.coordinator.injection.target}`:""}`}),i.coordinator.mcpConfigPath&&s.jsx(Dt,{k:"MCP config",v:s.jsx(rr,{children:i.coordinator.mcpConfigPath})}),i.coordinator.extraSystemPrompt&&s.jsx(fl,{title:"Per-launch extra prompt",body:i.coordinator.extraSystemPrompt,defaultOpen:!0}),i.coordinator.systemPrompt&&s.jsx(fl,{title:"Final system prompt (click to expand)",body:i.coordinator.systemPrompt})]}),i&&!i.coordinator&&s.jsx("div",{className:"text-text-secondary italic",children:"This isn't a mesh coordinator session, so no coordinator-specific prompt was injected. The agent runs with whatever defaults its CLI ships with."})]}),s.jsxs("div",{className:"border-t border-border-subtle px-4 py-2 flex justify-end gap-2",children:[s.jsx("button",{type:"button",onClick:()=>void d(),className:"px-3 py-1 text-sm rounded border border-border-default hover:bg-surface-secondary",children:"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:"px-3 py-1 text-sm rounded bg-accent text-white hover:opacity-90",children:"Close"})]})]})})}function hl({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 Dt({k:e,v:t}){return s.jsxs("div",{className:"flex gap-3",children:[s.jsx("div",{className:"w-44 shrink-0 text-text-secondary",children:e}),s.jsx("div",{className:"min-w-0 break-all",children:t})]})}function rr({children:e}){return s.jsx("code",{className:"font-mono text-xs",children:e})}function fl({title:e,body:t,defaultOpen:r=!1}){const[n,a]=l.useState(r);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:()=>a(o=>!o),className:"text-xs uppercase tracking-wide text-text-secondary hover:text-text-primary",style:{pointerEvents:"auto"},children:[n?"▾":"▸"," ",e]}),n&&s.jsx("pre",{className:"mt-1 p-2 bg-[var(--surface-secondary)] border border-border-subtle rounded text-xs whitespace-pre-wrap overflow-x-auto max-h-96 overflow-y-auto",children:t})]})}function yx({sessionId:e,daemonId:t}){const[r,n]=l.useState(!1);return!e||!t?null:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",onClick:()=>n(!0),title:"Session info — system prompt, MCP config, spawned at, …","aria-label":"Session info",className:"inline-flex items-center justify-center w-6 h-6 rounded-full text-text-secondary hover:text-text-primary hover:bg-surface-secondary text-sm leading-none",style:{pointerEvents:"auto"},children:"ⓘ"}),r&&s.jsx(gx,{sessionId:e,daemonId:t,onClose:()=>n(!1)})]})}const Ze=e=>e.transport==="pty",qs=(e,t)=>Ze(e)?e.mode||"terminal":"chat",Pd=(e,t)=>Ze(e)&&qs(e)==="terminal",Ye=e=>e.transport==="acp",vx=180;function ls(e){return e.streamSource!=="agent-stream"}function Ms(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function Rd(e){return e.machineName||""}function Fr(e){return Ms(e)}function Vt(e){return e.agentType||""}function Wn(e){return e.hostIdeType||""}function ri(e){return e.displayPrimary||e.agentName||"Agent"}function Dd(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function wx(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function $d(e){const t=wx(e),r=Fs(t==null?void 0:t.content),n=Fs(e.lastMessagePreview);return r||n||""}function jx(e,t=vx){const r=Fs(e);if(!r||t<=0)return"";const n=Array.from(r);return n.length<=t?r:`${n.slice(0,Math.max(0,t-1)).join("").trimEnd()}…`}function kx(e){return jx($d(e)||e.displaySecondary||"")}function Ed(e){return[e.displaySecondary,Rd(e)].filter(Boolean)}function Ws(e){return e.agentName||wt(Vt(e))}function Nx(e){var t,r;if(!ls(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return wt(Wn(e)||Vt(e))}function Bd(e){return ls(e)?e.sessionId:e.nativeSessionId}function xl(e){return ls(e)?"native":e.tabKey}function Sx(e){return e.sessionId}function Cx(e,t){if(t)return ls(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function Ix(e,t){const r=Vt(e),n=ls(e),a=Ze(e)||Ye(e),o=n?a?Ws(e)||(t==null?void 0:t.cliName)||wt(Wn(e)||r):t!=null&&t.type?wt(t.type):wt(Wn(e)||r):Ws(e);return{isNativeConversation:n,isCli:Ze(e),isAcp:Ye(e),isCliTerminal:Pd(e),providerType:r,displayLabel:o,targetEntry:Cx(e,t)}}function bs(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:Ze(e)||Ye(e)?{agentType:Vt(e)}:e.streamSource==="agent-stream"?{agentType:Vt(e)}:t}function gs(e){return e?Fr(e):""}function nr(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function ni(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function bl(e){const t=e instanceof Error?e.message:String(e||""),r=t.toLowerCase();return r.includes("still processing the previous prompt")?"Message queued and will send after the current reply finishes.":r.includes("awaiting confirmation")?"Resolve the pending approval prompt before sending another message.":r.includes("not ready")?"Wait for the runtime to finish starting up before sending a message.":r.includes("not running")?"Runtime is not available right now.":t||"Unable to send message right now."}function Fd(){return"select_session"}function Mx(){return"open_panel"}function Ax({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function gl(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function on(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function vr(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function ai(e){return e instanceof Error?e.message:String(e||"")}function yl(e){const t=ai(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function vl(e,t){const r=ai(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function wl(e,t,r,n={}){const a=bs(r);if(!t||t.length===0)return{message:e,...n.force?{force:!0}:{},...a};const o=t.map(i=>({type:"image",mimeType:i.mimeType,data:i.data,alt:i.name}));return e&&o.push({type:"text",text:e}),{message:e,input:{parts:o,textFallback:e},...n.force?{force:!0}:{},...a}}function ma({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,o]=l.useState(!1),[i,c]=l.useState(!1),[u,m]=l.useState(null),d=l.useRef(!1),p=l.useRef(null);l.useEffect(()=>{m(null)},[t==null?void 0:t.tabKey]);const h=l.useCallback(async(j,y)=>{if(!t||d.current)return!1;const v=j.trim(),N=ni(t);if(Ax({hasMessage:!!v,blockedMessage:N,sendInFlight:d.current}))return N&&m(N),!1;const k=Date.now(),x={tabKey:t.tabKey,message:v,timestamp:k};if(gl(p.current,x))return m(null),!0;d.current=!0,c(!0),m(null),p.current=x;try{const I=gs(t);if(!I)return p.current=on(p.current,x),m("Unable to send message right now."),!1;const C=await e(I,"send_chat",wl(v,y,t)),M=vr(C);if(M!=null&&M.deduplicated)return m(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 m(null),!0}catch(I){const C=ai(I);return C.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",C):console.warn("Send blocked/failed",I),p.current=on(p.current,x),m(bl(I)),!1}finally{d.current=!1,c(!1)}},[t,e]),b=l.useCallback(async(j,y)=>{if(!t||d.current)return!1;const v=j.trim();if(!v&&(!y||y.length===0))return!1;const N=Date.now(),k={tabKey:t.tabKey,message:`force:${v}`,timestamp:N};if(gl(p.current,k))return m(null),!0;d.current=!0,c(!0),m(null),p.current=k;try{const x=gs(t);if(!x)return p.current=on(p.current,k),m("Unable to send message right now."),!1;const I=await e(x,"send_chat",wl(v,y,t,{force:!0})),C=vr(I);if((C==null?void 0:C.success)===!1||(C==null?void 0:C.sent)===!1)throw new Error((C==null?void 0:C.error)||"Send failed");return m(null),!0}catch(x){return console.warn("Force send blocked/failed",x),p.current=on(p.current,k),m(bl(x)),!1}finally{d.current=!1,c(!1)}},[t,e]),g=l.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(j){console.error("Relaunch failed",j)}},[t,e]),f=l.useCallback(async j=>{if(t)try{const v=(t.modalButtons||[]).indexOf(j),N=j.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(N),x=gs(t);if(!x)return;const I=await e(x,"resolve_action",{button:j,action:k?"approve":"reject",...v>=0&&{buttonIndex:v},...bs(t)}),C=vr(I);C.success||r(M=>[...M,{routeId:t.tabKey,text:vl(j,C==null?void 0:C.error),timestamp:Date.now()}])}catch(y){yl(y)||console.error("[ModalButton] Error:",y),r(v=>[...v,{routeId:t.tabKey,text:yl(y)?vl(j,y):`❌ **${j}** error`,timestamp:Date.now()}])}},[t,e,r]),w=l.useCallback(async()=>{if(!(!t||a)){o(!0);try{await e(t.routeId,Mx(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(j){console.error("Focus agent failed",j)}finally{o(!1)}}},[t,a,e]);return{isSendingChat:i,sendFeedbackMessage:u,isFocusingAgent:a,handleSendChat:h,handleForceSendChat:b,handleRelaunch:g,handleModalButton:f,handleFocusAgent:w}}const Tx=10,_x=8e3,Lx=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function Px(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 So(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(Lx.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=Px(e);return n.length>8e3?`${n.slice(0,8e3)}…[truncated ${n.length-8e3} chars]`:n}if(typeof e!="object")return String(e);if(r>=6)return"[MaxDepth]";if(Array.isArray(e)){const n=e.slice(-20).map(a=>So(a,t,r+1));return e.length>20?[{truncatedBefore:e.length-20},...n]:n}return Object.fromEntries(Object.entries(e).slice(0,80).map(([n,a])=>[n,So(a,n,r+1)]))}function ar(e,t){return Array.isArray(e)?e.slice(-t):[]}function Rx(e,t=Date.now()){const r=e&&t-e.firstAt<=_x,n=r?e.count+1:1;return n>=Tx?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function Od(e){var n,a;const{activeConv:t}=e,r={version:1,createdAt:new Date(e.now??Date.now()).toISOString(),url:e.locationHref??(typeof window<"u"?window.location.href:void 0),activeConversation:{routeId:t.routeId,tabKey:t.tabKey,sessionId:t.sessionId,providerSessionId:t.providerSessionId,transport:t.transport,agentName:t.agentName,agentType:t.agentType,hostIdeType:t.hostIdeType,status:t.status,connectionState:t.connectionState,title:t.title,workspaceName:t.workspaceName,displayPrimary:t.displayPrimary,displaySecondary:t.displaySecondary,streamSource:t.streamSource,lastMessageHash:t.lastMessageHash},messageCounts:{live:((n=e.chatTailState.liveMessages)==null?void 0:n.length)??t.messages.length,activeConversation:t.messages.length,visible:e.visibleMessages.length,history:((a=e.chatTailState.historyMessages)==null?void 0:a.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:ar(e.chatTailState.liveMessages??t.messages,10),activeConversationMessagesTail:ar(t.messages,10),visibleMessagesTail:ar(e.visibleMessages,5),historyMessagesTail:ar(e.chatTailState.historyMessages,5),actionLogsTail:ar(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 So(r)}function zd(e,t={}){const r=e&&typeof e=="object"?e:{},n=t.locatorCopyStatus??(t.locatorCopied===!1?"failed":"copied"),a=n==="copied"?"locator copied":n==="manual"?"locator shown for manual copy":"locator copy failed";return r.delivery==="daemon_file"?`Chat debug signal sent${typeof r.bundleId=="string"&&r.bundleId.trim()?` (${r.bundleId})`:""}; saved on daemon, ${a}.`:`Chat debug signal sent; ${a}.`}async function Hd(e){var t;if(typeof navigator<"u"&&((t=navigator.clipboard)!=null&&t.writeText)&&typeof window<"u"&&window.isSecureContext)try{return await navigator.clipboard.writeText(e),"copied"}catch(r){console.warn("[chat-debug-bundle] clipboard API failed, trying execCommand fallback",r)}if(typeof document<"u"&&document.body){let r=null;try{if(r=document.createElement("textarea"),r.value=e,r.setAttribute("readonly","true"),r.style.cssText="position:fixed;left:-9999px;top:0",document.body.appendChild(r),r.focus(),r.select(),document.execCommand("copy"))return"copied"}catch{}finally{r==null||r.remove()}}if(typeof window<"u"&&typeof window.prompt=="function")try{return window.prompt("Copy ADHDev chat debug locator:",e),"manual"}catch{}return"failed"}function Wd(e){const t=e&&typeof e=="object"?e:{};if(t.delivery==="daemon_file"){const r=["# ADHDev Chat Debug Bundle saved on daemon","",`bundleId: ${String(t.bundleId||"")}`,`savedPath: ${String(t.savedPath||"")}`,`sizeBytes: ${String(t.sizeBytes||"")}`,`createdAt: ${String(t.createdAt||"")}`];return t.summary&&typeof t.summary=="object"&&r.push("","summary:",JSON.stringify(t.summary,null,2)),Array.isArray(t.warnings)&&t.warnings.length>0&&r.push("","warnings:",...t.warnings.map(n=>`- ${String(n)}`)),r.join(`
32
+ `)}return typeof t.text=="string"?t.text:t.bundle&&typeof t.bundle=="object"?`# ADHDev Chat Debug Bundle
33
+
34
+ \`\`\`json
35
+ ${JSON.stringify(t.bundle,null,2)}
36
+ \`\`\``:`# ADHDev Chat Debug Bundle
37
+
38
+ \`\`\`json
39
+ ${JSON.stringify(t,null,2)}
40
+ \`\`\``}function Ia(e,t){return`${e}:${t}`}function Dx(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function $x(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function As(e,t){$x()&&console.debug(`[subscription-manager] ${e}`,t)}class Ex{constructor(){Ue(this,"active",new Map);Ue(this,"retryTimers",new Map)}subscribe(t,r,n,a,o){var d,p;const i=Ia(n.topic,n.key),c=this.active.get(i);let u=!0;if(c)c.handlers.add(a),(!Dx(c.request,n)||c.daemonId!==r)&&(c.daemonId=r,c.request=n,u=((d=t.sendData)==null?void 0:d.call(t,r,n))??!1,!u&&(o!=null&&o.retryIntervalMs)?this.scheduleRetry(i,t,o.retryIntervalMs):u&&this.clearRetry(i),As("subscribe_update",{daemonId:r,topic:n.topic,key:n.key,accepted:u})),c.lastUpdate&&a(c.lastUpdate);else{const h={daemonId:r,request:n,handlers:new Set([a])};this.active.set(i,h),As("subscribe",{daemonId:r,topic:n.topic,key:n.key}),u=((p=t.sendData)==null?void 0:p.call(t,r,n))??!1,!u&&(o!=null&&o.retryIntervalMs)&&this.scheduleRetry(i,t,o.retryIntervalMs)}const m=()=>{var g;this.clearRetry(i);const h=this.active.get(i);if(!h||(h.handlers.delete(a),h.handlers.size>0))return;this.active.delete(i);const b={type:"unsubscribe",topic:n.topic,key:n.key};As("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(g=t.sendData)==null||g.call(t,r,b)};return m.initialSendAccepted=u,m}publish(t){const r=Ia(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,Bs.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.publish",topic:t.topic,payload:{key:t.key}}),n.handlers.forEach(a=>{a(t),Bs.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.handler_invoked",topic:t.topic,payload:{key:t.key}})}))}updateParams(t,r,n){const a=Ia(t,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(t){var r;As("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(n=>({daemonId:n.daemonId,topic:n.request.topic,key:n.request.key}))});for(const n of this.active.values())(r=t.sendData)==null||r.call(t,n.daemonId,n.request)}resubscribeForDaemon(t,r){var a;const n=Array.from(this.active.values()).filter(o=>o.daemonId===t);As("resubscribe_daemon",{daemonId:t,count:n.length,subscriptions:n.map(o=>({topic:o.request.topic,key:o.request.key}))});for(const o of n)(a=r.sendData)==null||a.call(r,o.daemonId,o.request)}scheduleRetry(t,r,n){if(this.retryTimers.has(t))return;const a=setTimeout(()=>{var c;this.retryTimers.delete(t);const o=this.active.get(t);if(!o)return;const i=((c=r.sendData)==null?void 0:c.call(r,o.daemonId,o.request))??!1;As("subscribe_retry",{id:t,accepted:i,topic:o.request.topic,key:o.request.key}),i||this.scheduleRetry(t,r,n)},n);this.retryTimers.set(t,a)}clearRetry(t){const r=this.retryTimers.get(t);r!==void 0&&(clearTimeout(r),this.retryTimers.delete(t))}}const qt=new Ex;function Bx(e,t){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===t&&n.sessionId){r.set(n.sessionId,{parentSessionId:n.parentSessionId,providerSessionId:n.providerSessionId,workspace:n.workspace??null,sessionCapabilities:n.sessionCapabilities,cdpConnected:n.cdpConnected,activeChat:n.activeChat,controlValues:n.controlValues,providerControls:n.providerControls,summaryMetadata:n.summaryMetadata,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,mode:n.mode,status:n.status,lastMessagePreview:n.lastMessagePreview,lastMessageRole:n.lastMessageRole,lastMessageAt:n.lastMessageAt,lastMessageHash:n.lastMessageHash,completionMarker:n.completionMarker,seenCompletionMarker:n.seenCompletionMarker,settings:n.settings,activeInteractivePrompt:n.activeInteractivePrompt});for(const o of n.childSessions||[]){if(!(o!=null&&o.id))continue;const i=r.get(o.id)||{};r.set(o.id,{...i,...o})}}return r}function Fx(e){const t=[],r=new Map;for(const n of e)if(n.parentId){const a=r.get(n.parentId)||[];a.push(n),r.set(n.parentId,a)}else t.push(n);return{topLevel:t,childrenByParent:r}}function Ma(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function Ox(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function zx(e){Ox()&&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 Kn(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:o,timestamp:i}=t,c=i||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:m,childrenByParent:d}=Fx(u),p=Bx(o,n),h=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,b=m.filter(w=>w.kind==="workspace"&&w.transport==="cdp-page"),g=m.filter(w=>w.kind==="agent"&&w.transport==="pty"),f=m.filter(w=>w.kind==="agent"&&w.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:c,...e.version&&{version:e.version},...h&&{machine:h,platform:h.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},_sessionListAuthoritative:Array.isArray(e.sessions),cdpConnected:b.some(w=>!!w.cdpConnected)});for(const w of b){const j=p.get(w.id),y=hr(w,j),v=(d.get(w.id)||[]).map(N=>hr(N,p.get(N.id)));r.push({id:`${n}:ide:${w.id}`,sessionId:w.id,providerSessionId:w.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:y.parentId,sessionKind:y.kind,transport:y.transport,sessionCapabilities:y.capabilities,type:y.providerType,status:y.cdpConnected?"online":"detected",daemonId:n,instanceId:Ma(n,w.id),workspace:y.workspace,terminals:0,childSessions:v,agents:v.map(N=>({id:N.id,name:N.providerName||N.providerType,type:N.providerType,status:N.status})),activeChat:y.activeChat,...y.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:y.activeInteractivePrompt},chats:[],cdpConnected:y.cdpConnected,...y.lastMessagePreview!==void 0&&{lastMessagePreview:y.lastMessagePreview},...y.lastMessageRole!==void 0&&{lastMessageRole:y.lastMessageRole},...y.lastMessageAt!==void 0&&{lastMessageAt:y.lastMessageAt},...y.lastMessageHash!==void 0&&{lastMessageHash:y.lastMessageHash},lastUpdated:y.lastUpdated,unread:y.unread,lastSeenAt:y.lastSeenAt,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,seenCompletionMarker:y.seenCompletionMarker,surfaceHidden:y.surfaceHidden,...y.controlValues!==void 0&&{controlValues:y.controlValues},...y.providerControls!==void 0&&{providerControls:y.providerControls},...y.summaryMetadata!==void 0&&{summaryMetadata:y.summaryMetadata},...y.settings!==void 0&&{settings:y.settings},...y.messageInput!==void 0&&{messageInput:y.messageInput},timestamp:c})}for(const w of g){const j=p.get(w.id),y=hr(w,j);r.push({id:`${n}:cli:${w.id}`,sessionId:w.id,providerSessionId:w.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:y.parentId,sessionKind:y.kind,transport:y.transport,sessionCapabilities:y.capabilities,type:y.providerType,agentType:y.providerType,status:y.status||"running",daemonId:n,instanceId:Ma(n,w.id),cliName:y.providerName||y.providerType,mode:y.mode||(j==null?void 0:j.mode)||"terminal",workspace:y.workspace||"",activeChat:y.activeChat,...y.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:y.activeInteractivePrompt},...y.resume!==void 0&&{resume:y.resume},...y.runtimeKey!==void 0&&{runtimeKey:y.runtimeKey},...y.runtimeDisplayName!==void 0&&{runtimeDisplayName:y.runtimeDisplayName},...y.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:y.runtimeWorkspaceLabel},...y.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:y.runtimeWriteOwner},...y.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:y.runtimeAttachedClients},...y.lastMessagePreview!==void 0&&{lastMessagePreview:y.lastMessagePreview},...y.lastMessageRole!==void 0&&{lastMessageRole:y.lastMessageRole},...y.lastMessageAt!==void 0&&{lastMessageAt:y.lastMessageAt},...y.lastMessageHash!==void 0&&{lastMessageHash:y.lastMessageHash},lastUpdated:y.lastUpdated,unread:y.unread,lastSeenAt:y.lastSeenAt,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,seenCompletionMarker:y.seenCompletionMarker,surfaceHidden:y.surfaceHidden,...y.controlValues!==void 0&&{controlValues:y.controlValues},...y.providerControls!==void 0&&{providerControls:y.providerControls},...y.summaryMetadata!==void 0&&{summaryMetadata:y.summaryMetadata},...y.settings!==void 0&&{settings:y.settings},...y.messageInput!==void 0&&{messageInput:y.messageInput},timestamp:c,_isCli:!0})}for(const w of f){const j=p.get(w.id),y=hr(w,j);r.push({id:`${n}:acp:${w.id}`,sessionId:w.id,providerSessionId:w.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:y.parentId,sessionKind:y.kind,transport:y.transport,sessionCapabilities:y.capabilities,type:y.providerType,agentType:y.providerType,status:y.status||"running",daemonId:n,instanceId:Ma(n,w.id),cliName:y.providerName||y.providerType,mode:"chat",workspace:y.workspace||"",activeChat:y.activeChat,...y.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:y.activeInteractivePrompt},...y.runtimeKey!==void 0&&{runtimeKey:y.runtimeKey},...y.runtimeDisplayName!==void 0&&{runtimeDisplayName:y.runtimeDisplayName},...y.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:y.runtimeWorkspaceLabel},...y.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:y.runtimeWriteOwner},...y.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:y.runtimeAttachedClients},...y.lastMessagePreview!==void 0&&{lastMessagePreview:y.lastMessagePreview},...y.lastMessageRole!==void 0&&{lastMessageRole:y.lastMessageRole},...y.lastMessageAt!==void 0&&{lastMessageAt:y.lastMessageAt},...y.lastMessageHash!==void 0&&{lastMessageHash:y.lastMessageHash},lastUpdated:y.lastUpdated,unread:y.unread,lastSeenAt:y.lastSeenAt,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,seenCompletionMarker:y.seenCompletionMarker,surfaceHidden:y.surfaceHidden,...y.controlValues!==void 0&&{controlValues:y.controlValues},...y.providerControls!==void 0&&{providerControls:y.providerControls},...y.summaryMetadata!==void 0&&{summaryMetadata:y.summaryMetadata},...y.settings!==void 0&&{settings:y.settings},...y.messageInput!==void 0&&{messageInput:y.messageInput},timestamp:c,_isAcp:!0})}return zx(r),r}const Hx=15e3,Wx=15e3,Kx=6e4,Ux=1200,jl=12,Gx=8e3,Vx=4e3,Aa=new Map,Ta=new Map,ln=new Set,wr=new Map;function qx(e){if(!e||typeof e!="object")return null;const t=e,r=t.status;if(r&&typeof r=="object")return r;const n=t.result;if(n&&typeof n=="object"&&"status"in n){const a=n.status;if(a&&typeof a=="object")return a}return t}function kl(e,t){const r=wr.get(e);!r||r.size===0||(wr.delete(e),r.forEach(n=>n(t)))}function Yx(e,t){return new Promise(r=>{const n=wr.get(e)||new Set;wr.set(e,n);const a=i=>{clearTimeout(o),n.delete(a),n.size===0&&wr.delete(e),r(i)},o=setTimeout(()=>a(!1),t);n.add(a)})}function Or(){const{sendCommand:e,sendData:t}=lt(),{injectEntries:r,getIdes:n}=Mr();return l.useCallback(async(a,o)=>{if(!a)return;const i=(o==null?void 0:o.minFreshMs)??Kx,c=Ta.get(a)||0;if(!(o!=null&&o.force)&&ln.has(a)&&c>0||!(o!=null&&o.force)&&c>0&&Date.now()-c<i)return;const u=Aa.get(a);if(u)return u;const m=(async()=>{if(t&&!ln.has(a)){const f=qt.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},w=>{const j=n(),y=j.find(N=>N.id===a),v=Kn(w.status,{daemonId:a,existingDaemon:y,existingEntries:j,timestamp:w.timestamp});v.length>0&&r(v),Ta.set(a,Date.now()),kl(a,!0)});if(f.initialSendAccepted?ln.add(a):ln.delete(a),!(o!=null&&o.force)&&f.initialSendAccepted&&await Yx(a,Ux))return}const d=await e(a,"get_status_metadata"),p=qx(d);if(!p)return;const h=n(),b=h.find(f=>f.id===a),g=Kn(p,{daemonId:a,existingDaemon:b,existingEntries:h,timestamp:p.timestamp||Date.now()});g.length>0&&r(g,{authoritativeDaemonIds:[a]}),Ta.set(a,Date.now()),kl(a,!0)})().finally(()=>{Aa.delete(a)});return Aa.set(a,m),m},[n,r,e,t])}function Jx(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const Xx=60,Qx=50;function Kd(e={}){return e.isCliLike?Qx:Xx}function Zx(e={}){return Kd(e)}function kt(e){return(typeof e=="string"?e.trim():"")||void 0}function Xt(e,t){const r=kt(t);return r?`${e}:${r}`:void 0}function ns(e,t,r){const n=Xt(t,r),a=kt(r);n&&e.push(n),a&&e.push(a)}function Ds(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function Ud(e){return kt(e.providerSessionId)||kt(e.sessionId)||kt(e.tabKey)||kt(e.routeId)}function pa(e){return Ds([kt(e.historySessionId),kt(e.providerSessionId),kt(e.sessionId)])}function Zt(e){const t=[];return ns(t,"provider",e.providerSessionId),ns(t,"session",e.sessionId),ns(t,"tab",e.tabKey),ns(t,"route",e.routeId),Ds(t)}function eb(e){const t=[];return kt(e.providerSessionId)?(ns(t,"provider",e.providerSessionId),Ds(t)):kt(e.sessionId)?(ns(t,"session",e.sessionId),Ds(t)):kt(e.tabKey)?(ns(t,"tab",e.tabKey),Ds(t)):kt(e.routeId)?(ns(t,"route",e.routeId),Ds(t)):[]}function Tr(e){return Xt("provider",e.providerSessionId)||Xt("session",e.sessionId)||Xt("tab",e.tabKey)||Xt("route",e.routeId)||"unknown:"}function zr(e){return pa(e)[0]}function tb(e){const t=kt(e.providerSessionId),r=kt(e.sessionId),n=kt(e.tabKey),a=kt(e.routeId),o=[Xt("provider",t),Xt("session",r),Xt("tab",n),Xt("route",a)].filter(u=>typeof u=="string"),i=Zt({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),c=Tr({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:c,targetKey:c,targetValue:Ud({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:zr({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:i}}function Co(e,t){const r=tb(e);return eb(t).some(n=>r.lookupKeys.includes(n))}const Hr=60,sb=1e3,oi=12e4,rb=new Set(["generating","waiting_approval","starting","streaming","working"]),Io=new Map;function ii(e,t,r){return`${e}::${t}::${r||t}`}function Un(e=Hr){return{liveMessages:[],hasLiveSnapshot:!1,cursor:nb([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function nb(e,t=Hr){return{tailLimit:t}}function Nl(e,t){const r=e[e.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function Mo(e){if(typeof e=="string")return e;if(e==null)return"";if(Array.isArray(e))return e.map(Mo).join(`
41
+ `);if(typeof e=="object"){const t=e;return Mo(t.text??t.content??t.value??"")}return String(e)}function ab(e){return Mo(e.content).replace(/[─━═│┃┄┅┈┉┌┐└┘├┤┬┴┼╭╮╰╯╴╶╷╵\s]+/g,"").length===0}function ob(e){return e.length===0||e.every(ab)}function ib(e){const t=typeof e=="string"?e.toLowerCase():"";return t==="generating"||t==="long_generating"||t==="streaming"||t==="working"||t==="starting"}function Gd(e,t){return Math.max(Math.max(0,t),Array.isArray(e.liveMessages)?e.liveMessages.length:0)}function lb(e,t,r,n,a){if(!ib(n))return!1;const o=Gd(e,t);if(o<=0)return!1;if(ob(r))return!0;if(a&&typeof a=="object"){const i=a.selected,c=a.fallbackReason;if(i==="native-history"||typeof c=="string"&&c!==""&&!c.startsWith("native_history_"))return!1}return r.length<o}function cb(e,t,r,n){if(r.length!==0||Gd(e,t)<=0||e.hasLiveSnapshot&&e.liveMessages.length===0||!n||typeof n!="object")return!1;const o=n.selected,i=n.fallbackReason,c=n.nativeSource;return o==="native-history"?!1:c==="native-unavailable"?!0:typeof i=="string"&&i.startsWith("native_history_")}function db(e){if(Array.isArray(e.messages))return e.messages;const t=e.messagesTail;return Array.isArray(t)?t:[]}function Sl(e,t){const r=e[t];return typeof r=="string"?r:""}class ub{constructor(t){Ue(this,"manager");Ue(this,"sendData");Ue(this,"daemonId");Ue(this,"sessionId");Ue(this,"historySessionId");Ue(this,"subscriptionKey");Ue(this,"fallbackRecentCount");Ue(this,"snapshot");Ue(this,"transportSubscription",null);Ue(this,"listeners",new Set);Ue(this,"retainCount",0);Ue(this,"loadHistoryPromise",null);Ue(this,"pendingDisconnectTimer",null);this.manager=t.manager||qt,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount??0),this.snapshot=Un(Math.max(0,t.tailLimit??Hr))}updateOptions(t){const r=this.sendData,n=this.daemonId,a=this.sessionId;if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.fallbackRecentCount!==void 0&&(this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount)),t.tailLimit!==void 0){const o=Math.max(0,t.tailLimit);o!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:o}},this.transportSubscription&&(this.disconnect(),this.connect()))}this.retainCount>0&&(r!==this.sendData||n!==this.daemonId||a!==this.sessionId)&&(this.disconnect(),this.connect())}getSnapshot(){return this.snapshot}clearLiveSnapshot(){this.snapshot={...Un(this.snapshot.cursor.tailLimit),hasLiveSnapshot:!0},this.emit()}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=this.snapshot.hasLiveSnapshot,a=n?this.snapshot.liveMessages.length:Math.max(this.snapshot.liveMessages.length,this.fallbackRecentCount),o=await t({offset:this.snapshot.historyOffset,excludeRecentCount:a}),i=Array.isArray(o.messages)?o.messages:[],c=!n&&i.length===0&&o.hasMore!==!0&&this.fallbackRecentCount>0;this.snapshot={...this.snapshot,historyMessages:[...i,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+i.length,hasMoreHistory:c?!0:o.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}}}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),t=>{this.handleUpdate(t)},{retryIntervalMs:sb}))}disconnect(){var t;(t=this.transportSubscription)==null||t.call(this),this.transportSubscription=null}dispose(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(t=>t(this.snapshot))}handleUpdate(t){if(t.error)return;const r=Sl(t,"sessionId");if(r&&r!==this.sessionId)return;const n=Sl(t,"historySessionId");if(n&&this.historySessionId&&n!==this.historySessionId)return;const a=db(t),o=t.messageSource;if(lb(this.snapshot,this.fallbackRecentCount,a,t.status,o)||cb(this.snapshot,this.fallbackRecentCount,a,o))return;const i={tailLimit:this.snapshot.cursor.tailLimit};Nl(this.snapshot.liveMessages)===Nl(a)&&this.snapshot.cursor.tailLimit===i.tailLimit||(this.snapshot={...this.snapshot,liveMessages:a,hasLiveSnapshot:!0,cursor:i,messageSource:o},this.emit())}}function Vd(e){const t=ii(e.daemonId,e.sessionId,e.historySessionId),r=Io.get(t);if(r)return r.updateOptions(e),r;const n=new ub(e);return Io.set(t,n),n}function mb(e,t,r){if(!e||!t)return;const n=`${e}::${t}::`,a=ii(e,t,r);for(const[o,i]of Io.entries())(o===a||o.startsWith(n))&&i.clearLiveSnapshot()}function pb(e,t){return{...e,loadHistoryPage:t}}function hb(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function fb(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(rb.has(r)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const n=t.now??Date.now(),a=Math.max(0,Number(t.recentActivityMs??oi)),o=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return o>0?n-o<=a:Array.isArray(e.messages)&&e.messages.length>0}function xb(e=oi){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function bb(e,t={}){const r=new Set,n=[];for(const a of e){if(!fb(a,t))continue;const o=Fr(a),i=a.sessionId||"";if(!o||!i)continue;const c=zr(a),u=ii(o,i,c||i);r.has(u)||(r.add(u),n.push({daemonId:o,sessionId:i,historySessionId:c||i,subscriptionKey:`daemon:${o}:session:${i}`}))}return n.sort(hb),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function gb(e,t){const{sendData:r,sendCommand:n}=lt(),a=(t==null?void 0:t.enabled)!==!1,o=Fr(e),i=e.sessionId||"",c=zr(e)||i,u=`daemon:${o}:session:${i}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??Hr),d=l.useMemo(()=>!a||!o||!i?null:Vd({daemonId:o,sessionId:i,historySessionId:c,subscriptionKey:u,sendData:r,tailLimit:m,fallbackRecentCount:e.messages.length}),[e.messages.length,o,a,c,r,i,u,m]),[p,h]=l.useState(()=>(d==null?void 0:d.getSnapshot())||Un(m));l.useEffect(()=>{if(!d){h(Un(m));return}d.retain(),h(d.getSnapshot());const g=d.subscribe(f=>{h(f)});return()=>{g(),d.release()}},[d,m]);const b=l.useCallback(async()=>{!d||!o||!i||await d.loadHistoryPage(async({offset:g,excludeRecentCount:f})=>{const w=e.agentType,j=await n(o,"chat_history",{agentType:w,offset:g,limit:30,targetSessionId:i,historySessionId:c,excludeRecentCount:f}),y=j&&typeof j=="object"&&"result"in j?j.result||{}:j||{};return{messages:Array.isArray(y.messages)?y.messages:[],hasMore:y.hasMore===!0}})},[e.agentType,d,o,c,n,i]);return l.useMemo(()=>pb(p,b),[b,p])}function yb(e,t){const{sendData:r}=lt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??Hr),o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??oi)),i=xb(o),[c,u]=l.useState(0);l.useEffect(()=>{if(!n||e.length===0)return;const d=setInterval(()=>{u(p=>p+1)},i);return()=>{clearInterval(d)}},[e.length,n,i]);const m=l.useMemo(()=>bb(e,{recentActivityMs:o}),[e,o,c]);l.useEffect(()=>{if(!n||!r||m.descriptors.length===0)return;const d=m.descriptors.map(p=>Vd({...p,sendData:r,tailLimit:a}));return d.forEach(p=>{p.retain()}),()=>{d.forEach(p=>p.release())}},[m.signature,n,r,a])}function vb(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function Cl(e){const t=String(e.role||"").toLowerCase();if(t!=="user"&&t!=="assistant")return!1;const r=String(e.kind||"standard").toLowerCase();return r===""||r==="standard"}function wb(e,t){if(e.length===0)return[];if(t.some(Cl))return[];const r=[],n=new Set;for(let a=e.length-1;a>=0&&r.length<2;a-=1){const o=e[a];if(!o||!Cl(o))continue;const i=String(o.role||"").toLowerCase();n.has(i)||(n.add(i),r.unshift(o))}return r}function jb(e){const{historyMessages:t,liveMessages:r,visibleLiveCount:n}=e,a=Math.max(0,r.length-n),o=a>0?r.slice(0,a):[],i=a>0?r.slice(-n):r,c=wb(o,i),u=c.length>0?[...c,...i]:i;return t.length===0?u:[...t,...u]}function kb(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Nb(e){return kb(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Cn=new Map,Ao=new Set;function Il(e,t){!e||Cn.get(e)===t||(t?Cn.set(e,!0):Cn.delete(e),Ao.forEach(n=>n(e,t)))}function Sb(e){return e?Cn.get(e)===!0:!1}function Cb(e){return Ao.add(e),()=>{Ao.delete(e)}}function Ib(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function Mb(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function Ab(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function qd(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function Yd(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 Tb(e){return qd(e)?!1:e.inboxBucket==="task_complete"&&Yd(e).length>0}function Ml(e){return e.branch||"detached HEAD"}function _b(e){if(e.error)return`${Ml(e)} · Git error: ${e.error}`;const t=[Ml(e)];return e.changedFiles>0?t.push(Ib(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 Lb(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${_b(t)}`}function Pb(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function Rb(e,t={}){if(t.enabled===!1)return[];if(!Ab(e))return[];const r=qd(e)?"working":Tb(e)?"complete":null;if(!r)return[];const n=r==="complete"?Yd(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${Mb(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:Lb(r,e.git),timestamp:Pb(e,e.git),meta:{source:"git-system-bubble",phase:r,workspace:e.workspacePath,repoRoot:e.git.repoRoot,branch:e.git.branch,changedFiles:e.git.changedFiles,hasConflicts:e.git.hasConflicts}}]}const Db=60;function $b(e){return e.status==="long_generating"?"Agent has been generating for a long time. Send queues your message; Force sends it immediately.":e.status==="generating"||e.status==="streaming"?"Agent is generating. Send queues your message; Force sends it immediately.":e.status==="waiting_approval"&&(!e.modalButtons||e.modalButtons.length===0)?"Agent is waiting for approval. Approval controls will appear when available.":null}function To({activeConv:e,ideEntry:t,handleSendChat:r,handleForceSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:u,userName:m,scrollToBottomRequestNonce:d,isInputActive:p=!0,isVisible:h=!0}){var ae,ge,me,U,H,q,ne;const b=l.useRef(new Map),g=l.useRef(void 0),f=Or(),{sendCommand:w}=lt(),{isVisible:j}=Zo();Br("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:u.length,isSendingChat:a});const y=yt.useMemo(()=>Vs(e),[e.status,e.connectionState]);yt.useEffect(()=>{const E=e.sessionId;if(E)return Il(E,y.isGenerating),()=>{Il(E,!1)}},[e.sessionId,y.isGenerating]);const v=l.useMemo(()=>Ix(e,t),[e,t]),N=l.useMemo(()=>{var E;return si((E=v.targetEntry)==null?void 0:E.providerControls,{hostIdeType:e.hostIdeType,providerType:v.providerType})},[e.hostIdeType,v.providerType,(ae=v.targetEntry)==null?void 0:ae.providerControls]),k=Kd({isCliLike:v.isCli||v.isAcp}),x=Zx({isCliLike:v.isCli||v.isAcp}),I=gb(e,{enabled:h&&!!e.sessionId,tailLimit:x}),[C,M]=l.useState(k),[D,P]=l.useState(()=>Qi()),T=e.tabKey,R=I.historyMessages,O=I.hasMoreHistory,K=I.historyError,S=vb(e,I),A=pd(S).length;l.useEffect(()=>{M(k)},[k,T]);const B=Math.max(0,S.length-C),L=ri(e),$=Fr(e),F=Nb(e),z=ni(e),re=$b(e),J=o||z||re,Y=!!z,[se,fe]=l.useState(!1);l.useEffect(()=>{const E=v.targetEntry;$&&(!E||E.providerControls===void 0||E.controlValues===void 0)&&f($,{minFreshMs:3e4}).catch(()=>{})},[$,v.isAcp,(ge=v.targetEntry)==null?void 0:ge.providerControls,(me=v.targetEntry)==null?void 0:me.controlValues,f]);const be=l.useCallback(async()=>{if(!se){if(S.length>C){M(E=>Math.min(S.length,E+Db));return}fe(!0);try{await I.loadHistoryPage()}finally{fe(!1)}}},[I,se,S.length,C]),{allMessages:X,receivedAtMap:Q}=l.useMemo(()=>{const E=jb({historyMessages:R,liveMessages:S,visibleLiveCount:C}),W=Rb(e),_=W.length>0?[...E,...W]:E,ie={};return _.forEach((pe,ue)=>{const oe=`${e.tabKey}:${On(pe,ue)}`;let Pe=Jx(pe)||b.current.get(oe)||0;Pe||(Pe=Date.now(),b.current.set(oe,Pe)),ie[On(pe,ue)]=Pe}),{allMessages:_,receivedAtMap:ie}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,B,R,S,C]),we=l.useMemo(()=>u.filter(E=>E.routeId===e.tabKey).sort((E,W)=>E.timestamp-W.timestamp),[u,e.tabKey]),ve=l.useCallback(async()=>{var ue,oe;if(!$)return;const E=Od({activeConv:e,visibleMessages:X,actionLogs:u,controls:(ue=v.targetEntry)==null?void 0:ue.providerControls,controlValues:(oe=v.targetEntry)==null?void 0:oe.controlValues,visibleBarControlCount:N.length,chatTailState:{liveMessages:I.liveMessages,hasLiveSnapshot:I.hasLiveSnapshot,hasMoreHistory:O,historyError:K,historyMessages:R},ui:{controlsVisible:j,visibleLiveCount:C,activityVisible:D,activityCount:A,hiddenLiveCount:B,isInputActive:p,isVisible:h}}),W=await w($,"get_chat_debug_bundle",{agentType:v.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:E}),_=vr(W),ie=Wd(_),pe=await Hd(ie);pe==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),tt.showToast(zd(_,{locatorCopyStatus:pe}),pe==="failed"?"warning":"success")},[e,u,A,X,j,I.hasLiveSnapshot,I.liveMessages,v.providerType,(U=v.targetEntry)==null?void 0:U.controlValues,(H=v.targetEntry)==null?void 0:H.providerControls,$,O,B,R,p,h,K,w,D,N.length,C]);l.useEffect(()=>{const E=W=>{W.key===ud&&P(Qi())};return window.addEventListener("storage",E),()=>window.removeEventListener("storage",E)},[]);const xe=l.useCallback(()=>{const E=Rx(g.current);g.current=E.state,E.shouldCollect&&ve().catch(W=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",W),tt.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[ve]),Ne=l.useMemo(()=>{if(S.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((y.isGenerating||e.status==="streaming")&&fe(!1),e.status==="not_monitored"&&F)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(Hs,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Os,{size:14})," Open ",L," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&F)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(od,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Os,{size:14})," Open ",L," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!se)return!O&&R.length===0?s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"No messages yet"})]}):s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,F,i,O,R.length,c,se,S.length,L,y.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col relative",children:[s.jsx("div",{className:"chat-activity-toggle-bar",children:s.jsx("div",{className:"ml-auto flex items-center gap-1",children:s.jsx(yx,{sessionId:e.sessionId,daemonId:e.daemonId})})}),s.jsx(af,{messages:X,actionLogs:we,agentName:Ws(e)||L||"Agent",userName:m,isCliMode:v.isCli||v.isAcp,isWorking:y.isGenerating,contextKey:e.tabKey,receivedAtMap:Q,lastMessageHash:e.lastMessageHash,showActivityMessages:D,onLoadMore:be,isLoadingMore:se,hasMoreHistory:O,hiddenLiveCount:B,loadError:K??void 0,emptyState:Ne,scrollToBottomRequestNonce:d,isVisible:h}),s.jsx(px,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:v.providerType,displayLabel:v.displayLabel,controls:(q=v.targetEntry)==null?void 0:q.providerControls,controlValues:(ne=v.targetEntry)==null?void 0:ne.controlValues,isActive:p,isCliTerminal:v.isCliTerminal}),!v.isCliTerminal&&s.jsx(Ld,{contextKey:e.tabKey,panelLabel:L,isSending:a,isBusy:Y,statusMessage:J,onSend:r,onForceSend:n,canForceSend:!!n&&y.isGenerating&&!Y,isActive:p,showControlsToggle:N.length>0,onControlsToggle:xe,messageInput:e.messageInput})]})}let Jd=Yt;function Xd(){return Jd()}class Eb{constructor(){Ue(this,"listeners",new Map)}send(t){}isConnected(){return!1}on(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{var n;(n=this.listeners.get(t))==null||n.delete(r)}}emit(t,...r){var n;(n=this.listeners.get(t))==null||n.forEach(a=>a(...r))}}let Qd=new Eb;class Bb{sendPtyInput(t,r,n){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,r){return!1}get(t){}onScreenshot(t,r){return()=>{}}onRuntimeEvent(t,r,n){return()=>{}}requestRuntimeSnapshot(t,r,n){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let pt=new Bb;function Fb(e){e.dashboardWS&&(Qd=e.dashboardWS),e.connectionManager&&(pt=e.connectionManager),e.useDaemonsHook&&(Jd=e.useDaemonsHook)}const Ob=.5,zb=1.25;function it(e){return ri(e)}function Ss(e){return Ed(e).join(" · ")}function Hb(e){var a,o,i;const t=[],r=typeof((a=e.settings)==null?void 0:a.meshNodeFor)=="string"&&e.settings.meshNodeFor.trim().length>0,n=!!((o=e.coordinator)!=null&&o.meshId)||typeof((i=e.settings)==null?void 0:i.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.trim().length>0;return r&&t.push("메시 노드"),n&&t.push("코디네이터"),t}function Wb(e){var i,c,u;const t=[],r=typeof((i=e.settings)==null?void 0:i.meshNodeFor)=="string"?e.settings.meshNodeFor.trim():"",n=typeof((c=e.coordinator)==null?void 0:c.meshId)=="string"?e.coordinator.meshId.trim():"",a=typeof((u=e.settings)==null?void 0:u.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor.trim():"",o=n||a;if(r&&t.push(`메시 노드: ${r}`),o&&t.push(`코디네이터: ${o}`),e.meshQueueStats){const{pending:m,assigned:d,completed:p,failed:h}=e.meshQueueStats;t.push(`Queue: ${m} pending, ${d} assigned, ${p} completed, ${h} failed`)}return t.join(" · ")}function Zd(e){const t=$d(e);return t||(e.title?e.title:Ss(e)||"No messages yet")}function eu(e,t){const{isReconnecting:r,isConnecting:n}=Vs(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function Kb(e,t){const r=["Chat",...Ed(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function ys(e){return eu(e)||Ss(e)}function Ub(e){return`${it(e)} · ${Zd(e)}`}function Gb(e){const t=Wn(e),r=t?wt(t):Ws(e);return`${it(e)} — ${r||"Agent"}`}function Vb(e){return Ws(e)||"CLI"}function tu(e){return Dd(e)}function su(e){return e?`Remote · ${it(e)||e.workspaceName||"Session"}`:"Remote"}const Al=[{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:""}})}],qb=[{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 Yb(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 li({cond:e,path:t,sections:r,onChange:n,onRemove:a,onPreview:o,preview:i}){const c=Yb(e),u=i[t],m=d=>{const p=Al.find(h=>h.kind===d);p&&n(p.make(r))};return s.jsxs("div",{className:"border border-zinc-700/60 rounded bg-zinc-800/30 p-1.5 space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("select",{value:c,onChange:d=>m(d.target.value),className:"bg-zinc-900 text-zinc-200 text-[10px] font-mono rounded border border-zinc-700 px-1 py-0.5",children:Al.map(d=>s.jsx("option",{value:d.kind,children:d.label},d.kind))}),(c==="regex"||c==="stable"||c==="changed"||c==="elapsed")&&s.jsx("button",{type:"button",className:"text-[10px] text-sky-300 hover:text-sky-100 px-1.5 py-0.5 rounded border border-sky-700/40 hover:bg-sky-600/20",onClick:()=>o(t,e),children:"test"}),u&&u!=="loading"&&s.jsx("span",{className:`text-[10px] font-mono px-1.5 py-0.5 rounded ${u.result?"text-green-200 bg-green-600/25":"text-zinc-400 bg-zinc-700/40"}`,children:u.result?"match ✓":"no match"}),u==="loading"&&s.jsx("span",{className:"text-[10px] text-zinc-500",children:"testing…"}),a&&s.jsx("button",{type:"button",className:"ml-auto text-zinc-500 hover:text-red-300 text-xs px-1",onClick:a,children:"×"})]}),c==="regex"&&s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs("select",{value:e.section??"",onChange:d=>n({...e,section:d.target.value||void 0}),className:"bg-zinc-900 text-sky-300 text-[10px] font-mono rounded border border-zinc-700 px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(whole screen)"}),r.map(d=>s.jsx("option",{value:d,children:d},d))]}),s.jsx("input",{value:e.matches??"",onChange:d=>n({...e,matches:d.target.value}),placeholder:"regex",spellCheck:!1,className:"flex-1 bg-black/40 text-zinc-200 text-[10px] font-mono rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"})]}),c==="elapsed"&&s.jsx(as,{label:"elapsed_ms",value:e.elapsed_ms,onChange:d=>n({elapsed_ms:d})}),c==="stable"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(as,{label:"stable_ms",value:e.stable_ms,onChange:d=>n({...e,stable_ms:d})}),s.jsx(as,{label:"cursor_above",value:e.cursor_above??0,onChange:d=>n({...e,cursor_above:d||void 0})})]}),c==="changed"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(as,{label:"cursor_above",value:e.cursor_above,onChange:d=>n({...e,cursor_above:d})}),s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-zinc-400",children:[s.jsx("input",{type:"checkbox",checked:!!e.changed,onChange:d=>n({...e,changed:d.target.checked}),className:"accent-sky-500"}),"changed"]})]}),(c==="all"||c==="any")&&s.jsx(Jb,{kind:c,cond:e,path:t,sections:r,onChange:n,onPreview:o,preview:i}),c==="not"&&s.jsx("div",{className:"pl-2 border-l border-zinc-700",children:s.jsx(li,{cond:e.not,path:`${t}.not`,sections:r,onChange:d=>n({not:d}),onPreview:o,preview:i})})]})}function Jb({kind:e,cond:t,path:r,sections:n,onChange:a,onPreview:o,preview:i}){const c=(e==="all"?t.all:t.any)??[],u=m=>a(e==="all"?{all:m}:{any:m});return s.jsxs("div",{className:"pl-2 border-l border-zinc-700 space-y-1",children:[c.map((m,d)=>s.jsx(li,{cond:m,path:`${r}.${e}[${d}]`,sections:n,onChange:p=>u(c.map((h,b)=>b===d?p:h)),onRemove:()=>u(c.filter((p,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-zinc-300 hover:text-white px-1.5 py-0.5 rounded border border-zinc-700 hover:bg-zinc-700/40",onClick:()=>u([...c,{section:n[0],matches:""}]),children:"+ condition"}),qb.map(m=>s.jsxs("button",{type:"button",className:"text-[10px] text-sky-300/80 hover:text-sky-100 px-1.5 py-0.5 rounded border border-sky-700/30 hover:bg-sky-600/15",onClick:()=>u([...c,JSON.parse(JSON.stringify(m.cond))]),title:"insert verified pattern",children:["+ ",m.label]},m.label))]})]})}function as({label:e,value:t,onChange:r}){return s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-zinc-400 font-mono",children:[e,s.jsx("input",{type:"number",value:Number.isFinite(t)?t:0,onChange:n=>r(Number(n.target.value)),className:"w-20 bg-black/40 text-zinc-200 rounded border border-zinc-700 px-1 py-0.5 outline-none focus:border-sky-500/50"})]})}function Xb({sections:e,otherSectionIds:t,onChange:r,onTest:n,testResult:a}){const o=Object.keys(e),i=a&&a!=="loading"&&!("error"in a)?Object.fromEntries(a.sections.map(p=>[p.id,p])):{},c=(p,h)=>{if(!h||h===p||e[h])return;const b={};for(const[g,f]of Object.entries(e))b[g===p?h:g]=f;r(b)},u=(p,h)=>r({...e,[p]:h}),m=p=>{const h={...e};delete h[p],r(h)},d=()=>{let p="section",h=1;for(;e[p];)p=`section${h++}`;r({...e,[p]:{from_top:0}})};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-zinc-400 text-[10px] uppercase tracking-widest font-semibold",children:"Sections"}),s.jsx("span",{className:"text-zinc-600 text-[10px]",children:"— how the screen is split; conditions match against these"}),s.jsx("button",{type:"button",className:"ml-auto text-[10px] text-sky-300 hover:text-sky-100 px-1.5 py-0.5 rounded border border-sky-700/40 hover:bg-sky-600/20",onClick:n,title:"Resolve all sections against the live session screen",children:a==="loading"?"testing…":"test on live screen"}),s.jsx("button",{type:"button",className:"text-[10px] text-zinc-300 hover:text-white px-1.5 py-0.5 rounded border border-zinc-700 hover:bg-zinc-700/40",onClick:d,children:"+ section"})]}),a&&a!=="loading"&&"error"in a&&s.jsx("div",{className:"text-red-300 bg-red-900/30 border border-red-700/40 rounded p-1.5 text-[10px] mb-1",children:a.error}),s.jsx("div",{className:"space-y-1.5",children:o.map(p=>{var f;const h=e[p],b=h.anchor!=null?"anchor":"positional",g=w=>{w==="anchor"?u(p,{anchor:h.anchor??"^",anchor_last:h.anchor_last,until:h.until}):u(p,{from_top:h.from_top??0,until:h.until})};return s.jsxs("div",{className:"border border-zinc-700/60 rounded bg-zinc-800/30 p-2 space-y-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{value:p,onChange:w=>c(p,w.target.value.trim()),className:"w-28 bg-black/40 text-sky-300 font-mono text-[11px] rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"}),s.jsxs("div",{className:"inline-flex rounded border border-zinc-700 overflow-hidden text-[10px]",children:[s.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${b==="positional"?"bg-sky-600/30 text-sky-100":"text-zinc-400 hover:bg-zinc-700/40"}`,onClick:()=>g("positional"),children:"positional"}),s.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${b==="anchor"?"bg-sky-600/30 text-sky-100":"text-zinc-400 hover:bg-zinc-700/40"}`,onClick:()=>g("anchor"),children:"anchor"})]}),s.jsx("button",{type:"button",className:"ml-auto text-zinc-500 hover:text-red-300 text-sm px-1",onClick:()=>m(p),children:"×"})]}),b==="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:w=>u(p,{...h,from_top:w,from_bottom:void 0})}),s.jsx(as,{label:"from_bottom",value:typeof h.from_bottom=="number"?h.from_bottom:0,onChange:w=>u(p,{...h,from_bottom:w||void 0})}),s.jsx(Tl,{def:h,otherIds:t(p),onChange:w=>u(p,w)})]}):s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-[10px] text-zinc-500 w-16",children:"anchor"}),s.jsx("input",{value:h.anchor??"",onChange:w=>u(p,{...h,anchor:w.target.value}),placeholder:"^regex locating section start",spellCheck:!1,className:"flex-1 bg-black/40 text-zinc-200 text-[10px] font-mono rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"}),s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-zinc-400",children:[s.jsx("input",{type:"checkbox",checked:!!h.anchor_last,onChange:w=>u(p,{...h,anchor_last:w.target.checked||void 0}),className:"accent-sky-500"}),"last"]})]}),s.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:s.jsx(Tl,{def:h,otherIds:t(p),onChange:w=>u(p,w)})}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-[10px] text-zinc-500 w-16",children:"ctx next"}),s.jsx("input",{value:((f=h.anchor_context)==null?void 0:f.next)??"",onChange:w=>u(p,{...h,anchor_context:{...h.anchor_context,next:w.target.value||void 0}}),placeholder:"optional: line after anchor must match",spellCheck:!1,className:"flex-1 bg-black/40 text-zinc-300 text-[10px] font-mono rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"})]})]}),i[p]&&s.jsxs("div",{className:"border-t border-zinc-700/50 pt-1",children:[s.jsxs("div",{className:"text-[9px] text-zinc-500 mb-0.5",children:["captured lines ",i[p].fromLine,"–",i[p].toLine,i[p].text.trim()===""&&s.jsx("span",{className:"text-amber-400 ml-1",children:"(empty — check bounds)"})]}),s.jsx("pre",{className:"font-mono text-[10px] text-zinc-300 whitespace-pre-wrap break-all bg-black/40 rounded border border-zinc-700/50 px-2 py-1 max-h-28 overflow-y-auto",children:i[p].text||"(empty)"})]})]},p)})})]})}function Tl({def:e,otherIds:t,onChange:r}){const n=e.until??"",a=n.startsWith("^");return s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-zinc-400",children:["until",s.jsxs("select",{value:a?"__regex__":n,onChange:o=>{const i=o.target.value;r(i===""?{...e,until:void 0}:i==="__regex__"?{...e,until:n.startsWith("^")?n:"^"}:{...e,until:i})},className:"bg-zinc-900 text-sky-300 rounded border border-zinc-700 px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(none)"}),t.map(o=>s.jsx("option",{value:o,children:o},o)),s.jsx("option",{value:"__regex__",children:"regex…"})]}),a&&s.jsx("input",{value:n,onChange:o=>r({...e,until:o.target.value}),spellCheck:!1,className:"w-40 bg-black/40 text-zinc-200 font-mono rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"})]})}function Qb({model:e,onChange:t,onPreview:r,preview:n,onTestSections:a,sectionPreview:o}){const i=e.states.map(p=>p.id),c=Object.keys(e.sections??{}),u=l.useCallback(p=>t({...e,...p}),[e,t]),m=(p,h)=>u({states:e.states.map((b,g)=>g===p?{...b,...h}:b)}),d=(p,h)=>u({transitions:e.transitions.map((b,g)=>g===p?{...b,...h}:b)});return s.jsxs("div",{className:"space-y-3",children:[s.jsx(Xb,{sections:e.sections??{},otherSectionIds:p=>c.filter(h=>h!==p),onChange:p=>u({sections:p}),onTest:()=>a(e.sections??{}),testResult:o}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-zinc-400 text-[10px] uppercase tracking-widest font-semibold",children:"States"}),s.jsx("button",{type:"button",className:"text-[10px] text-zinc-300 hover:text-white px-1.5 py-0.5 rounded border border-zinc-700 hover:bg-zinc-700/40",onClick:()=>u({states:[...e.states,{id:`state${e.states.length}`,label:"New"}]}),children:"+ state"})]}),s.jsx("div",{className:"space-y-1.5",children:e.states.map((p,h)=>s.jsxs("div",{className:"border border-zinc-700/60 rounded bg-zinc-800/30 p-2 space-y-1",children:[s.jsxs("div",{className:"flex items-end gap-2 flex-wrap",children:[s.jsxs("label",{className:"flex flex-col gap-0.5",children:[s.jsx("span",{className:"text-[9px] text-zinc-500 uppercase tracking-wide",children:"id (used by transitions)"}),s.jsx("input",{value:p.id,onChange:b=>m(h,{id:b.target.value}),placeholder:"idle",className:"w-32 bg-black/40 text-sky-300 font-mono text-[11px] rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"})]}),s.jsxs("label",{className:"flex flex-col gap-0.5 flex-1",children:[s.jsx("span",{className:"text-[9px] text-zinc-500 uppercase tracking-wide",children:"label (shown in dashboard)"}),s.jsx("input",{value:p.label,onChange:b=>m(h,{label:b.target.value}),placeholder:"Ready",className:"w-full bg-black/40 text-zinc-200 text-[11px] rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"})]}),s.jsx("button",{type:"button",className:"text-zinc-500 hover:text-red-300 text-sm px-1 pb-0.5",onClick:()=>u({states:e.states.filter((b,g)=>g!==h)}),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-[10px] text-zinc-400 flex-wrap",children:[s.jsxs("label",{className:"flex items-center gap-1",children:[s.jsx("input",{type:"radio",name:"initial",checked:!!p.initial,onChange:()=>u({states:e.states.map((b,g)=>({...b,initial:g===h}))}),className:"accent-sky-500"}),"initial"]}),s.jsxs("label",{className:"flex items-center gap-1",children:[s.jsx("input",{type:"checkbox",checked:!!p.modal,onChange:b=>m(h,{modal:b.target.checked||void 0}),className:"accent-sky-500"}),"modal"]}),s.jsxs("label",{className:"flex items-center gap-1",children:["status",s.jsxs("select",{value:p.status??"",onChange:b=>m(h,{status:b.target.value||void 0}),className:"bg-zinc-900 text-zinc-200 rounded border border-zinc-700 px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(auto)"}),s.jsx("option",{value:"idle",children:"idle"}),s.jsx("option",{value:"generating",children:"generating"}),s.jsx("option",{value:"approval",children:"approval"})]})]})]})]},h))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-zinc-400 text-[10px] uppercase tracking-widest font-semibold",children:"Transitions"}),s.jsx("button",{type:"button",className:"text-[10px] text-zinc-300 hover:text-white px-1.5 py-0.5 rounded border border-zinc-700 hover:bg-zinc-700/40",onClick:()=>u({transitions:[...e.transitions,{from:i[0]??"",to:i[0]??""}]}),children:"+ transition"})]}),s.jsx("div",{className:"space-y-1.5",children:e.transitions.map((p,h)=>s.jsxs("div",{className:"border border-zinc-700/60 rounded bg-zinc-800/30 p-2 space-y-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"text-[10px] text-zinc-500",children:"from"}),s.jsx(Zb,{value:p.from,states:i,onChange:b=>d(h,{from:b})}),s.jsx("span",{className:"text-[10px] text-zinc-500",children:"→"}),s.jsx("select",{value:p.to,onChange:b=>d(h,{to:b.target.value}),className:"bg-zinc-900 text-green-200 font-mono text-[10px] rounded border border-zinc-700 px-1 py-0.5",children:i.map(b=>s.jsx("option",{value:b,children:b},b))}),s.jsx("span",{className:"text-[10px] text-zinc-500 ml-1",children:"label"}),s.jsx("input",{value:p.label??"",onChange:b=>d(h,{label:b.target.value||void 0}),placeholder:"debug name only (optional)",title:"Display name shown in the debug history/transition table. Does not affect behaviour.",className:"flex-1 min-w-[120px] bg-black/40 text-zinc-300 text-[10px] rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"}),s.jsx("button",{type:"button",className:"text-zinc-500 hover:text-red-300 text-sm px-1",onClick:()=>u({transitions:e.transitions.filter((b,g)=>g!==h)}),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(as,{label:"min_hold_ms",value:p.min_hold_ms??0,onChange:b=>d(h,{min_hold_ms:b||void 0})}),s.jsx(as,{label:"priority",value:p.priority??0,onChange:b=>d(h,{priority:b||void 0})})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-[10px] text-zinc-500",children:"when"}),!p.when&&s.jsx("button",{type:"button",className:"text-[10px] text-zinc-300 hover:text-white px-1.5 py-0.5 rounded border border-zinc-700 hover:bg-zinc-700/40",onClick:()=>d(h,{when:{section:c[0],matches:""}}),children:"+ guard condition"}),p.when&&s.jsx("button",{type:"button",className:"text-[10px] text-zinc-500 hover:text-red-300",onClick:()=>d(h,{when:void 0}),children:"remove guard"})]}),p.when&&s.jsx(li,{cond:p.when,path:`t${h}`,sections:c,onChange:b=>d(h,{when:b}),onPreview:r,preview:n})]})]},h))})]})]})}function Zb({value:e,states:t,onChange:r}){const n=new Set(Array.isArray(e)?e:e==="*"?t:[e]),a=e==="*",o=i=>{const c=new Set(n);c.has(i)?c.delete(i):c.add(i);const u=t.filter(m=>c.has(m));r(u.length===1?u[0]:u)};return s.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.map(i=>s.jsx("button",{type:"button",onClick:()=>o(i),className:`font-mono text-[10px] px-1 py-0.5 rounded border ${a||n.has(i)?"text-sky-200 bg-sky-600/25 border-sky-500/40":"text-zinc-500 border-zinc-700 hover:border-zinc-500"}`,children:i},i))})}function or(e){const t=Date.now()-e;if(t<0)return"just now";if(t<2e3)return`${t}ms ago`;if(t<6e4)return`${(t/1e3).toFixed(1)}s ago`;const r=Math.floor(t/6e4);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}function _l(e){return e<=0?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}const eg={busy_hold_expired:"text-amber-200 bg-amber-500/20 border border-amber-500/30",idle_hold_committed:"text-green-200 bg-green-500/20 border border-green-500/30",completion_idle_after:"text-sky-200 bg-sky-500/20 border border-sky-500/30",forced_completion:"text-orange-200 bg-orange-500/20 border border-orange-500/30",forceEmit:"text-purple-200 bg-purple-500/20 border border-purple-500/30",spec_reload:"text-purple-200 bg-purple-500/20 border border-purple-500/30",eval_match:"text-zinc-300 bg-zinc-500/15 border border-zinc-500/20"},tg={idle:"text-green-100 bg-green-600/30 border border-green-500/40",busy:"text-yellow-100 bg-yellow-600/30 border border-yellow-500/40",generating:"text-yellow-100 bg-yellow-600/30 border border-yellow-500/40",approval:"text-orange-100 bg-orange-600/30 border border-orange-500/40",waiting_approval:"text-orange-100 bg-orange-600/30 border border-orange-500/40",picker:"text-sky-100 bg-sky-600/30 border border-sky-500/40",signing_in:"text-sky-100 bg-sky-600/30 border border-sky-500/40"};function _a(e){return tg[e]??"text-zinc-200 bg-zinc-600/20 border border-zinc-500/30"}function cn({children:e}){return s.jsx("div",{className:"text-zinc-400 text-[10px] uppercase tracking-widest font-semibold mb-1.5 mt-0.5",children:e})}function dn(){return s.jsx("div",{className:"border-t border-white/8 my-2"})}function ru({node:e,depth:t=0}){var a;const r=e.result?"text-green-300":"text-zinc-500",n=e.result?"●":"○";return s.jsxs("div",{style:{marginLeft:t*10},className:"font-mono text-[10px] leading-relaxed",children:[s.jsxs("span",{className:r,children:[n," "]}),s.jsx("span",{className:"text-zinc-400",children:e.kind}),s.jsxs("span",{className:"text-zinc-500",children:[" ",e.detail]}),e.remainingMs!=null&&e.remainingMs>0&&s.jsxs("span",{className:"text-amber-300",children:[" (",e.remainingMs,"ms left)"]}),(a=e.children)==null?void 0:a.map((o,i)=>s.jsx(ru,{node:o,depth:t+1},i))]})}function sg({t:e}){const[t,r]=l.useState(!1),n=e.fires?"text-green-200 bg-green-600/25 border-green-500/40":e.holdSatisfied?"text-zinc-400 bg-zinc-700/30 border-zinc-600/30":"text-amber-200 bg-amber-600/20 border-amber-500/30";return s.jsxs("div",{className:"border border-zinc-700/50 rounded bg-zinc-800/30 overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2 py-1 hover:bg-zinc-700/30 text-left",onClick:()=>r(a=>!a),children:[s.jsx("span",{className:"text-[10px] text-zinc-500 w-3",children:e.cond?t?"▾":"▸":" "}),s.jsxs("span",{className:`font-mono text-[11px] px-1.5 py-0.5 rounded border ${n}`,children:["→ ",e.to]}),s.jsx("span",{className:"text-zinc-400 font-mono text-[10px] truncate",children:e.label}),s.jsxs("span",{className:"ml-auto flex items-center gap-1.5 shrink-0",children:[e.fires&&s.jsx("span",{className:"text-green-300 text-[10px] font-mono",children:"FIRES"}),!e.holdSatisfied&&s.jsxs("span",{className:"text-amber-300 text-[10px] font-mono",children:["hold ",e.holdRemainingMs,"ms"]}),s.jsx("span",{className:`text-[10px] font-mono ${e.condResult?"text-green-400":"text-zinc-600"}`,children:e.condResult?"cond✓":"cond✗"})]})]}),t&&e.cond&&s.jsx("div",{className:"px-3 pb-1.5 pt-0.5 bg-black/30 border-t border-zinc-700/50",children:s.jsx(ru,{node:e.cond})})]})}function rg({activeConv:e,onClose:t}){var xe,Ne,ae,ge,me;const{sendCommand:r}=lt(),[n,a]=l.useState(!0),[o,i]=l.useState(null),[c,u]=l.useState(null),[m,d]=l.useState(!1),[p,h]=l.useState(new Set(["footer"])),[b,g]=l.useState("Snapshot"),[f,w]=l.useState(!1),[j,y]=l.useState(null),[v,N]=l.useState(!1),[k,x]=l.useState(""),[I,C]=l.useState(!1),[M,D]=l.useState("idle"),[P,T]=l.useState(null),[R,O]=l.useState([]),[K,S]=l.useState({}),[A,B]=l.useState(null),[L,$]=l.useState(!1),F=e.daemonId||((xe=e.routeId)==null?void 0:xe.split(":")[0])||e.routeId||"",z=e.sessionId||"",re=l.useCallback(async()=>{a(!0),u(null);try{const U=await r(F,"get_spec_debug",{targetSessionId:z}),H=U&&typeof U=="object"?U:{},q=H.result&&typeof H.result=="object"?H.result:H;q!=null&&q.success?i(q):(u((q==null?void 0:q.error)||"Failed to load spec debug"),i(null))}catch(U){u((U==null?void 0:U.message)||String(U)),i(null)}finally{a(!1)}},[r,F,z]);l.useEffect(()=>{re()},[re]),l.useEffect(()=>{if(!L)return;const U=setInterval(()=>{re()},1e3);return()=>clearInterval(U)},[L,re]),l.useEffect(()=>{const U=H=>{H.key==="Escape"&&!f&&t()};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[t,f]);const J=l.useCallback(async U=>{try{const H=await r(F,"validate_spec",{content:JSON.stringify(U)}),q=H&&typeof H=="object"?H:{},ne=q.result&&typeof q.result=="object"?q.result:q;O(ne!=null&&ne.valid?[]:(ne==null?void 0:ne.errors)??["validation failed"])}catch(H){O([(H==null?void 0:H.message)||String(H)])}},[r,F]),Y=l.useCallback(async()=>{T(null),D("idle"),S({});try{const U=await r(F,"get_spec_source",{targetSessionId:z}),H=U&&typeof U=="object"?U:{},q=H.result&&typeof H.result=="object"?H.result:H;if(!(q!=null&&q.success)||typeof q.content!="string"){T((q==null?void 0:q.error)||"Failed to load spec source");return}x(q.content);let ne=null;try{ne=JSON.parse(q.content)}catch{}ne&&ne.$schema==="adhdev:cli/spec@4"?(y(ne),N(!1),J(ne)):(y(null),N(!0)),C(!1),w(!0)}catch(U){T((U==null?void 0:U.message)||String(U))}},[r,F,z,J]),se=l.useCallback(U=>{y(U),x(JSON.stringify(U,null,2)),C(!0),D("idle"),J(U)},[J]),fe=l.useCallback(async(U,H)=>{S(q=>({...q,[U]:"loading"}));try{const q=await r(F,"eval_condition_preview",{targetSessionId:z,condition:H}),ne=q&&typeof q=="object"?q:{},E=ne.result&&typeof ne.result=="object"?ne.result:ne;!(E!=null&&E.success)||!E.result?S(W=>({...W,[U]:{result:!1,detail:E==null?void 0:E.error}})):S(W=>({...W,[U]:{result:E.result.result,detail:E.result.detail}}))}catch(q){S(ne=>({...ne,[U]:{result:!1,detail:q==null?void 0:q.message}}))}},[r,F,z]),be=l.useCallback(async U=>{B("loading");try{const H=await r(F,"resolve_section_preview",{targetSessionId:z,sections:U}),q=H&&typeof H=="object"?H:{},ne=q.result&&typeof q.result=="object"?q.result:q;!(ne!=null&&ne.success)||!Array.isArray(ne.sections)?B({error:(ne==null?void 0:ne.error)||"resolve failed"}):B({sections:ne.sections,screenLineCount:ne.screenLineCount??0})}catch(H){B({error:(H==null?void 0:H.message)||String(H)})}},[r,F,z]),X=l.useCallback(async()=>{var q,ne;const U=(q=o==null?void 0:o.snapshot)==null?void 0:q.specPath;if(!U){T("No spec path on this session");return}if(!v&&R.length>0){T("Fix validation errors before saving");return}const H=!v&&j?JSON.stringify(j,null,2):k;D("saving"),T(null);try{const E=await r(F,"write_spec_source",{specPath:U,content:H}),W=E&&typeof E=="object"?E:{},_=W.result&&typeof W.result=="object"?W.result:W;if(!(_!=null&&_.success)){D("error"),T(((ne=_==null?void 0:_.validationErrors)==null?void 0:ne.join(`
42
+ `))||(_==null?void 0:_.error)||"Save failed");return}D("saved"),C(!1),setTimeout(()=>{re()},400),setTimeout(()=>D("idle"),1500)}catch(E){D("error"),T((E==null?void 0:E.message)||String(E))}},[r,F,(Ne=o==null?void 0:o.snapshot)==null?void 0:Ne.specPath,k,j,v,R,re]),Q=o==null?void 0:o.snapshot,we=async()=>{var _,ie,pe;let U=o;U||(await re(),U=o);const H=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: ${(H==null?void 0:H.spec_id)??""} (${(H==null?void 0:H.specPath)??""})`),q.push(`Provider: ${(H==null?void 0:H.name)??""} (${(H==null?void 0:H.cliType)??""})`),q.push(`Working dir: ${(H==null?void 0:H.workingDir)??""}`),q.push(`Spawned: ${H!=null&&H.spawnedAtMs?new Date(H.spawnedAtMs).toISOString():""}`),q.push(""),q.push("## Current State"),q.push(`State: ${((_=H==null?void 0:H.current_state)==null?void 0:_.id)??"none"} (${((ie=H==null?void 0:H.current_state)==null?void 0:ie.label)??""})`),q.push(`Status: ${(H==null?void 0:H.status)??""}`),q.push(`Idle hold pending: ${(H==null?void 0:H.idleHoldPending)??!1}`),q.push(`Exited: ${(H==null?void 0:H.exited)??!1}`),q.push(`Last busy: ${H!=null&&H.lastBusyAt?or(H.lastBusyAt):""}`),q.push(`Cursor: ${(H==null?void 0:H.cursorPosition)!=null?`(${H.cursorPosition.row},${H.cursorPosition.col})`:"n/a"}`),(pe=H==null?void 0:H.completionIdleDebounce)!=null&&pe.active){const ue=H.completionIdleDebounce;q.push(`completion_idle_after: age=${ue.ageMs}ms hold=${ue.holdMs}ms force=${ue.forceAfterMs}ms remaining=${Math.max(0,ue.holdMs-ue.ageMs)}ms`)}if(q.push(""),q.push("## Modal"),H!=null&&H.current_modal){const ue=H.current_modal.buttons.map(oe=>oe.label).join(" / ");q.push(`${H.current_modal.title??""} [${ue}]`)}else q.push("none");q.push(""),q.push("## State History (last 20)");const ne=H!=null&&H.stateHistory?[...H.stateHistory].reverse().slice(0,20):[];for(const ue of ne){const oe=ue.reason!=null?typeof ue.reason=="string"?ue.reason:JSON.stringify(ue.reason):"",Pe=ue.debounceKind!=null?typeof ue.debounceKind=="string"?ue.debounceKind:JSON.stringify(ue.debounceKind):"",Ee=ue.matchedStateId!=null?String(ue.matchedStateId):"",$e=(ue.matchedRules??[]).map(He=>typeof He=="string"?He:JSON.stringify(He)).join(", ");q.push(`- ${ue.stateId} @ ${new Date(ue.at).toISOString()} held ${ue.durationMs}ms | reason: ${oe} | debounce: ${Pe} | eval→${Ee} | rules: ${$e}`)}if(q.push(""),q.push("## Sections"),H!=null&&H.sections)for(const[ue,oe]of Object.entries(H.sections)){const Pe=oe.split(`
43
+ `).slice(0,3).join(`
44
+ `);q.push(`${ue}: ${Pe}`)}q.push(""),q.push("## Last Assistant Message");const W=[...(H==null?void 0:H.messages)??(H==null?void 0:H.committedMessages)??[]].reverse().find(ue=>ue.role==="assistant");q.push(W?W.content.slice(0,400):""),q.push(""),q.push("## Screen (first 50 lines)"),q.push(H!=null&&H.screen?H.screen.split(`
45
+ `).slice(0,50).join(`
46
+ `):"");try{await navigator.clipboard.writeText(q.join(`
47
+ `)),g("Copied!"),setTimeout(()=>g("Snapshot"),1500)}catch(ue){console.error("[SpecDebugPanel] clipboard write failed",ue)}},ve=U=>{h(H=>{const q=new Set(H);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-50 flex items-end justify-center bg-black/60 p-0 sm:items-center sm:p-4",onClick:t,style:{pointerEvents:"auto"},children:s.jsxs("div",{className:"bg-zinc-900 text-zinc-100 border border-zinc-700 rounded-t-xl sm:rounded-lg shadow-2xl max-w-2xl w-full max-h-[92vh] sm:max-h-[88vh] flex flex-col",onClick:U=>U.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-zinc-700 px-4 py-2.5 shrink-0 gap-2 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 overflow-hidden",children:[s.jsx("span",{className:"text-sm font-semibold text-zinc-100 shrink-0",children:"Spec Debug"}),Q&&s.jsx("span",{className:"text-[11px] text-zinc-400 font-mono bg-zinc-800 px-1.5 py-0.5 rounded truncate",children:Q.spec_id})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[(Q==null?void 0:Q.specPath)&&s.jsx("button",{type:"button",className:`text-[11px] transition-colors px-2 py-1 rounded border ${f?"text-sky-200 bg-sky-600/25 border-sky-500/40":"text-zinc-300 hover:text-white hover:bg-zinc-700 border-transparent hover:border-zinc-600"}`,onClick:()=>{f?w(!1):Y()},disabled:n,children:f?"Close Editor":"Edit Spec"}),s.jsx("button",{type:"button",className:"text-[11px] text-zinc-300 hover:text-white transition-colors px-2 py-1 rounded hover:bg-zinc-700 border border-transparent hover:border-zinc-600",onClick:()=>{we()},disabled:n,children:b}),s.jsx("button",{type:"button",className:"text-[11px] text-zinc-300 hover:text-white transition-colors px-2 py-1 rounded hover:bg-zinc-700 border border-transparent hover:border-zinc-600",onClick:()=>{re()},disabled:n,children:n?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"text-zinc-400 hover:text-zinc-100 transition-colors text-xl leading-none w-7 h-7 flex items-center justify-center rounded hover:bg-zinc-700",onClick:t,"aria-label":"Close",children:"×"})]})]}),f&&s.jsxs("div",{className:"flex-1 flex flex-col min-h-0 px-4 py-3 gap-2",children:[s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsxs("div",{className:"inline-flex rounded border border-zinc-700 overflow-hidden text-[10px]",children:[s.jsx("button",{type:"button",className:`px-2 py-0.5 ${v?"text-zinc-400 hover:bg-zinc-700/40":"bg-sky-600/30 text-sky-100"}`,onClick:()=>{if(v)try{const U=JSON.parse(k);y(U),J(U)}catch{return}N(!1)},disabled:!j&&v,children:"Form"}),s.jsx("button",{type:"button",className:`px-2 py-0.5 ${v?"bg-sky-600/30 text-sky-100":"text-zinc-400 hover:bg-zinc-700/40"}`,onClick:()=>{j&&x(JSON.stringify(j,null,2)),N(!0)},children:"JSON"})]}),s.jsx("span",{className:"text-[10px] text-zinc-500 font-mono truncate flex-1",title:Q==null?void 0:Q.specPath,children:((Q==null?void 0:Q.specPath)??"").split("/").slice(-3).join("/")}),I&&s.jsx("span",{className:"text-amber-300 text-[10px]",children:"unsaved"}),!v&&R.length>0&&s.jsxs("span",{className:"text-red-300 text-[10px]",children:[R.length," error",R.length>1?"s":""]}),s.jsx("button",{type:"button",className:`text-[11px] px-2.5 py-1 rounded border transition-colors ${M==="saving"||!v&&R.length>0?"text-zinc-600 border-zinc-700 cursor-not-allowed":"text-green-200 bg-green-600/25 border-green-500/40 hover:bg-green-600/40"}`,onClick:()=>{X()},disabled:M==="saving"||!v&&R.length>0,children:M==="saving"?"Saving…":M==="saved"?"Saved ✓ (reloading)":"Save & Apply"})]}),P&&s.jsx("pre",{className:"text-red-300 bg-red-900/40 border border-red-700/50 rounded p-2 text-[10px] whitespace-pre-wrap shrink-0 max-h-28 overflow-y-auto",children:P}),!v&&R.length>0&&s.jsx("div",{className:"text-red-300 bg-red-900/30 border border-red-700/40 rounded p-1.5 text-[10px] shrink-0 max-h-24 overflow-y-auto space-y-0.5",children:R.map((U,H)=>s.jsx("div",{className:"font-mono",children:U},H))}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:v||!j?s.jsx("textarea",{value:k,onChange:U=>{x(U.target.value),C(!0),D("idle")},spellCheck:!1,className:"w-full h-full min-h-[300px] font-mono text-[11px] leading-relaxed bg-black/40 text-zinc-200 border border-zinc-700 rounded p-3 resize-none outline-none focus:border-sky-500/50"}):s.jsx(Qb,{model:j,onChange:se,onPreview:fe,preview:K,onTestSections:be,sectionPreview:A})}),s.jsx("div",{className:"text-[10px] text-zinc-500 shrink-0",children:v?"Raw JSON — validated on save.":'Build the FSM; from/to are constrained to existing states. "test" evaluates a condition against the live screen. Save hot-reloads the session.'})]}),!f&&s.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3 space-y-3 text-[12px]",children:[c&&s.jsx("div",{className:"text-red-300 bg-red-900/40 border border-red-700/50 rounded p-2",children:c}),n&&!o&&s.jsx("div",{className:"text-zinc-500 text-center py-6",children:"Loading…"}),o&&!o.isSpecProvider&&s.jsxs("div",{className:"text-zinc-500 text-center py-6",children:["Not a spec-driven provider (",o.providerType||"unknown",")."]}),Q&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-[11px] bg-zinc-800/60 rounded-md px-3 py-2 border border-zinc-700/50",children:[Q.name&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-zinc-500",children:"Provider"}),s.jsxs("span",{className:"font-mono text-zinc-200",children:[Q.name," ",s.jsxs("span",{className:"text-zinc-500",children:["(",Q.cliType,")"]})]})]}),Q.workingDir&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-zinc-500",children:"Dir"}),s.jsx("span",{className:"font-mono text-zinc-300 truncate",title:Q.workingDir,children:Q.workingDir})]}),Q.spawnedAtMs?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-zinc-500",children:"Spawned"}),s.jsx("span",{className:"text-zinc-400",children:or(Q.spawnedAtMs)})]}):null,Q.providerSessionId&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-zinc-500",children:"Session"}),s.jsx("span",{className:"font-mono text-zinc-500 text-[10px] truncate",title:Q.providerSessionId,children:Q.providerSessionId})]})]}),s.jsxs("div",{className:"flex items-center gap-2 flex-wrap bg-zinc-800/40 rounded-md px-3 py-2 border border-zinc-700/50",children:[s.jsx("span",{className:`font-semibold font-mono text-[12px] px-2 py-0.5 rounded ${Q.current_state?_a(Q.current_state.id):"text-zinc-500"}`,children:Q.current_state?Q.current_state.id:"none"}),((ae=Q.current_state)==null?void 0:ae.label)&&Q.current_state.label!==Q.current_state.id&&s.jsx("span",{className:"text-zinc-400 text-[11px]",children:Q.current_state.label}),Q.status&&Q.status!==((ge=Q.current_state)==null?void 0:ge.id)&&s.jsxs("span",{className:"text-zinc-500 text-[11px]",children:["engine: ",s.jsx("span",{className:`font-mono ${_a(Q.status)} px-1 py-0.5 rounded text-[10px]`,children:Q.status})]}),Q.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"}),Q.exited&&s.jsx("span",{className:"text-red-200 text-[10px] bg-red-600/25 border border-red-500/35 px-1.5 py-0.5 rounded font-mono",children:"exited"}),Q.cursorPosition!=null&&s.jsxs("span",{className:"text-zinc-500 text-[11px] font-mono",children:["cursor: ",s.jsxs("span",{className:"text-zinc-300",children:[Q.cursorPosition.row,",",Q.cursorPosition.col]})]}),Q.lastBusyAt>0&&s.jsxs("span",{className:"text-zinc-500 text-[11px] ml-auto",children:["last busy: ",s.jsx("span",{className:"text-zinc-400",children:or(Q.lastBusyAt)})]})]}),((me=Q.completionIdleDebounce)==null?void 0:me.active)&&s.jsxs("div",{className:"flex items-center gap-2 text-[11px] bg-sky-900/20 border border-sky-700/30 rounded-md px-3 py-1.5 font-mono",children:[s.jsx("span",{className:"text-sky-400",children:"completion_idle_after"}),s.jsxs("span",{className:"text-zinc-400",children:["age: ",s.jsxs("span",{className:"text-sky-200",children:[Q.completionIdleDebounce.ageMs,"ms"]})]}),s.jsx("span",{className:"text-zinc-500",children:"/"}),s.jsxs("span",{className:"text-zinc-400",children:["hold: ",s.jsxs("span",{className:"text-zinc-300",children:[Q.completionIdleDebounce.holdMs,"ms"]})]}),s.jsxs("span",{className:"text-zinc-400",children:["force: ",s.jsxs("span",{className:"text-zinc-300",children:[Q.completionIdleDebounce.forceAfterMs,"ms"]})]}),s.jsx("span",{className:"text-zinc-500 ml-auto",children:Q.completionIdleDebounce.ageMs<Q.completionIdleDebounce.holdMs?s.jsxs("span",{className:"text-amber-300",children:["hold remaining: ",Q.completionIdleDebounce.holdMs-Q.completionIdleDebounce.ageMs,"ms"]}):Q.completionIdleDebounce.ageMs<Q.completionIdleDebounce.forceAfterMs?s.jsxs("span",{className:"text-orange-300",children:["force in: ",Q.completionIdleDebounce.forceAfterMs-Q.completionIdleDebounce.ageMs,"ms"]}):s.jsx("span",{className:"text-red-300",children:"overdue"})})]}),Q.current_modal&&s.jsxs("div",{className:"bg-orange-900/30 border border-orange-600/40 rounded-md p-2.5",children:[s.jsx("span",{className:"text-orange-200 font-semibold",children:"Modal: "}),s.jsx("span",{className:"text-zinc-300",children:Q.current_modal.title||""}),Q.current_modal.buttons.length>0&&s.jsxs("span",{className:"text-zinc-400 ml-2",children:["[",Q.current_modal.buttons.map(U=>U.label).join(" / "),"]"]})]}),Q.fsm&&s.jsxs(s.Fragment,{children:[s.jsx(dn,{}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsxs(cn,{children:["FSM — outgoing from ",s.jsx("span",{className:"text-sky-300 font-mono normal-case",children:Q.fsm.currentState})," (held ",_l(Q.fsm.stateAgeMs),")"]}),s.jsxs("label",{className:"ml-auto flex items-center gap-1 text-[10px] text-zinc-500 cursor-pointer select-none mb-1.5",children:[s.jsx("input",{type:"checkbox",checked:L,onChange:U=>$(U.target.checked),className:"accent-sky-500"}),"live"]})]}),s.jsxs("div",{className:"space-y-1",children:[Q.fsm.transitions.length===0&&s.jsx("div",{className:"text-zinc-600 text-[11px] italic px-1",children:"no outgoing transitions (terminal state)"}),Q.fsm.transitions.map((U,H)=>s.jsx(sg,{t:U},H))]})]})]}),s.jsx(dn,{}),Q.sections&&Object.keys(Q.sections).length>0&&s.jsxs("div",{children:[s.jsx(cn,{children:"Sections"}),s.jsx("div",{className:"space-y-1",children:Object.entries(Q.sections).map(([U,H])=>{var W;const q=p.has(U),ne=H.split(`
48
+ `),E=((W=ne[0])==null?void 0:W.slice(0,80))||"(empty)";return s.jsxs("div",{className:"border border-zinc-700 rounded overflow-hidden bg-zinc-800/30",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2.5 py-1.5 hover:bg-zinc-700/40 transition-colors text-left",onClick:()=>ve(U),children:[s.jsx("span",{className:"text-[10px] text-zinc-500 w-3",children:q?"▾":"▸"}),s.jsx("span",{className:"font-mono text-sky-300 w-20 shrink-0 text-[11px]",children:U}),!q&&s.jsx("span",{className:"text-zinc-400 truncate font-mono text-[11px]",children:E}),s.jsxs("span",{className:"ml-auto text-zinc-600 text-[10px] shrink-0",children:[ne.length,"L"]})]}),q&&s.jsx("pre",{className:"px-3 pb-2.5 pt-1 font-mono text-[11px] text-zinc-300 whitespace-pre-wrap break-all bg-black/30 max-h-40 overflow-y-auto border-t border-zinc-700/50",children:H||"(empty)"})]},U)})})]}),s.jsx(dn,{}),Q.stateHistory&&Q.stateHistory.length>0&&s.jsxs("div",{children:[s.jsxs(cn,{children:["State History (",Q.stateHistory.length,")"]}),s.jsx("div",{className:"space-y-px",children:[...Q.stateHistory].reverse().slice(0,20).map((U,H)=>s.jsxs("div",{className:"rounded px-2 py-1 hover:bg-zinc-800/60 transition-colors",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:`font-mono text-[11px] font-semibold px-1.5 py-0.5 rounded shrink-0 ${_a(U.stateId)}`,children:U.stateId}),s.jsx("span",{className:"text-zinc-400 text-[11px] shrink-0 tabular-nums",children:or(U.at)}),U.durationMs>0&&s.jsxs("span",{className:"text-zinc-500 text-[11px]",children:["held ",s.jsx("span",{className:"text-zinc-400",children:_l(U.durationMs)})]}),U.reason&&s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-mono shrink-0 ${eg[String(U.reason)]??"text-zinc-400 bg-zinc-700/50 border border-zinc-600/30"}`,children:String(U.reason)}),U.debounceKind&&String(U.debounceKind)!=="none"&&s.jsxs("span",{className:"text-zinc-500 text-[10px] font-mono",children:["debounce:",String(U.debounceKind)]}),U.matchedStateId&&String(U.matchedStateId)!==U.stateId&&s.jsxs("span",{className:"text-zinc-500 text-[10px] font-mono",children:["eval→",s.jsx("span",{className:"text-zinc-300",children:String(U.matchedStateId)})]})]}),U.matchedRules&&U.matchedRules.length>0&&s.jsxs("div",{className:"flex items-start gap-1 flex-wrap mt-0.5 ml-1 pl-1 border-l border-zinc-700",children:[U.matchedRules.slice(0,3).map((q,ne)=>s.jsx("span",{className:"font-mono text-[10px] text-sky-200 bg-sky-900/40 border border-sky-700/40 px-1.5 py-0.5 rounded break-all",children:typeof q=="string"?q:JSON.stringify(q)},ne)),U.matchedRules.length>3&&s.jsxs("span",{className:"text-[10px] text-zinc-500",children:["+",U.matchedRules.length-3," more"]})]})]},H))})]}),s.jsx(dn,{}),(()=>{const U=Q.messages??Q.committedMessages??[];if(U.length===0)return null;const H=U.filter(E=>E.role==="user").length,q=U.filter(E=>E.role==="assistant").length,ne=[...U].reverse().find(E=>E.role==="assistant");return s.jsxs("div",{children:[s.jsxs(cn,{children:["Transcript (",U.length," — ",H,"u / ",q,"a)"]}),ne&&s.jsxs("div",{className:"bg-zinc-800/50 border border-zinc-700 rounded-md p-2.5 text-[11px]",children:[s.jsxs("div",{className:"text-zinc-500 mb-1 text-[10px]",children:["Last assistant ",ne.receivedAt?or(ne.receivedAt):""]}),s.jsxs("div",{className:"text-zinc-300 font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[ne.content.slice(0,400),ne.content.length>400?"…":""]})]})]})})(),Q.specPath&&s.jsx("div",{className:"text-[10px] text-zinc-600 font-mono truncate border-t border-zinc-800 pt-2 mt-1",title:Q.specPath,children:Q.specPath}),s.jsxs("div",{children:[s.jsxs("button",{type:"button",className:"text-[11px] text-zinc-400 hover:text-zinc-200 transition-colors flex items-center gap-1.5",onClick:()=>d(U=>!U),children:[s.jsx("span",{className:"text-zinc-600",children:m?"▾":"▸"}),s.jsxs("span",{children:["Raw screen (",Q.screen?Q.screen.split(`
49
+ `).length:0," lines)"]})]}),m&&s.jsx("pre",{className:"mt-1.5 px-3 py-2 font-mono text-[11px] text-zinc-300 whitespace-pre bg-black/40 rounded-md border border-zinc-700 max-h-64 overflow-auto",children:Q.screen||"(empty)"})]})]})]})]})})}function ng({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:i=!0,isInputActive:c=!0}){var je;Yt();const{sendPtyInput:u}=lt(),[m,d]=l.useState(!1),p=l.useRef(!1);p.current=m;const[h,b]=l.useState("Runtime terminal unavailable"),[g,f]=l.useState(!1),[w,j]=l.useState(null),[y,v]=l.useState(!1),[N,k]=l.useState(!1),[x,I]=l.useState(1),[C,M]=l.useState(!1),[D,P]=l.useState(!1),[T,R]=l.useState({width:0,height:0}),[O,K]=l.useState({width:0,height:0}),[S,A]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[B,L]=l.useState(null),$=l.useRef(null),F=l.useRef(null),z=l.useRef(!1),re=l.useRef(!1),J=l.useRef(i),Y=l.useRef(0),se=l.useRef(!1),fe=l.useRef(""),be=l.useRef(null),X=l.useRef(!1),Q=l.useRef(!1),we=l.useRef(null),ve=l.useRef(null),xe=l.useRef(null),Ne=32*1024,ae=()=>{var Z,ee,he,Ce;return((ee=(Z=$.current)==null?void 0:Z.ownerDocument)==null?void 0:ee.defaultView)||((Ce=(he=F.current)==null?void 0:he.ownerDocument)==null?void 0:Ce.defaultView)||window},ge=Z=>{const ee=ae();return{ownerWindow:ee,frameId:ee.requestAnimationFrame(Z)}},me=()=>{const Z=we.current;if(Z){try{Z.ownerWindow.cancelAnimationFrame(Z.frameId)}catch{}we.current=null}},U=()=>{const Z=ve.current;if(Z){try{Z.ownerWindow.clearTimeout(Z.timeoutId)}catch{}ve.current=null}},H=()=>{const Z=xe.current;if(Z){try{Z.ownerWindow.clearTimeout(Z.timeoutId)}catch{}xe.current=null}},q=()=>{i&&we.current===null&&(we.current=ge(()=>{st()}))},ne=e.tabKey,E=e.sessionId||"",W=e.daemonId||((je=e.routeId)==null?void 0:je.split(":")[0])||e.routeId||"",_=ni(e),ie=m?o||_:h,pe=Ob,ue=zb,oe=.05,Pe=()=>{const Z=O.width,ee=O.height;if(!Number.isFinite(T.width)||T.width<=0||!Number.isFinite(T.height)||T.height<=0||!Number.isFinite(Z)||Z<=0||!Number.isFinite(ee)||ee<=0)return 1;const he=T.width/Z,Ce=T.height/ee;return Number(Math.min(ue,Math.max(pe,Math.min(he,Ce))).toFixed(2))},Ee=Pe(),$e=z.current&&x>Ee,He=Number.isFinite(O.width)&&O.width>0?Math.max(T.width,Math.round(O.width*x)):T.width,Xe=Number.isFinite(O.height)&&O.height>0?Math.max(T.height,Math.round(O.height*x)):T.height,Je=()=>{ge(()=>{const Z=F.current;Z&&(Z.scrollLeft=0,Z.scrollTop=Z.scrollHeight-Z.clientHeight)})},nt=()=>{var Z,ee;Y.current=0,se.current=!1,fe.current="",be.current=null,X.current=!1,Q.current=!1,z.current||(re.current=!1,I(1)),we.current!==null&&me(),d(!1),b("Runtime terminal unavailable"),H(),U(),j(null),L(null),M(!1),f(!1),v(!1),k(!1),(ee=(Z=r.current)==null?void 0:Z.reset)==null||ee.call(Z)},et=()=>{var Z,ee;Y.current=0,se.current=!1,fe.current="",be.current=null,X.current=!1,Q.current=!1,we.current!==null&&me(),d(!0),b(""),H(),U(),j(null),L(null),M(!1),f(!1),v(!1),k(!1),(ee=(Z=r.current)==null?void 0:Z.reset)==null||ee.call(Z)},ct=()=>{Q.current&&(Q.current=!1,ge(()=>{var Z,ee;(ee=(Z=r.current)==null?void 0:Z.scrollToTop)==null||ee.call(Z)}))},st=()=>{if(we.current=null,!i)return;const Z=fe.current;if(!Z)return;const ee=Z.slice(0,Ne);fe.current=Z.slice(ee.length);const he=r.current;if(!he){fe.current=ee+fe.current,q();return}he.write(ee,()=>{if(fe.current.length>0){q();return}ct()})},ft=Z=>{Z&&(fe.current+=Z,q())},Me=(Z,ee=0,he,Ce,Te={})=>{var Le,Be,Ae,We;const Ie=!!Te.force;!Ie&&ee>0&&Y.current>=ee||!Ie&&ee===0&&se.current||(Y.current=ee,ee>0&&v(!0),d(!0),b(""),typeof he=="number"&&typeof Ce=="number"&&he>0&&Ce>0&&((Be=(Le=r.current)==null?void 0:Le.resize)==null||Be.call(Le,he,Ce)),fe.current="",(We=(Ae=r.current)==null?void 0:Ae.reset)==null||We.call(Ae),Z?ft(Z):ct())};l.useEffect(()=>{nt()},[E]),l.useEffect(()=>{var ee;if(!E)return;const Z=((ee=pt.onRuntimeEvent)==null?void 0:ee.call(pt,E,he=>{if(!(!he||he.sessionId!==E)){if(he.type==="runtime_snapshot"){if(!i){be.current={text:he.text||"",seq:he.seq||0,cols:he.cols,rows:he.rows,force:!!he.force};return}Me(he.text||"",he.seq||0,he.cols,he.rows,{force:!!he.force});return}if(he.type==="session_output"){se.current=!0,typeof he.seq=="number"&&(Y.current=Math.max(Y.current,he.seq),he.seq>0&&v(!0)),p.current||d(!0),p.current||b(""),typeof he.data=="string"&&ft(he.data);return}if(he.type==="session_cleared"){if(!i){X.current=!0,fe.current="",be.current=null;return}et();return}if(he.type==="session_io_error"){const Ce=typeof he.error=="string"&&he.error?he.error:typeof he.reason=="string"&&he.reason?he.reason:"unknown error";d(!1),b(`Runtime input failed: ${Ce}`);return}}},W))||(()=>{});return()=>{Z()}},[W,E,r,i]);const Se=async(Z={})=>{var ee;if(!W||!E)return{success:!1,error:"daemonId and sessionId are required"};Z.preserveStatus||b(Z.loadingMessage||"Loading runtime terminal...");try{const he=await((ee=pt.requestRuntimeSnapshot)==null?void 0:ee.call(pt,W,E,{sinceSeq:Z.sinceSeq,force:Z.force}));return he&&he.success===!1?(Z.preserveStatus||(d(!1),b(`Runtime terminal unavailable: ${he.error}`)),he):he||{success:!0}}catch(he){const Ce=(he==null?void 0:he.message)||String(he);return Z.preserveStatus||(d(!1),b(`Runtime terminal unavailable: ${Ce}`)),{success:!1,error:Ce}}},Qe=async Z=>{var Ie,Le;const ee=((Ie=$.current)==null?void 0:Ie.ownerDocument)||document,he=ee.defaultView||window,Ce=(Le=he.navigator)==null?void 0:Le.clipboard;if(Ce!=null&&Ce.writeText&&he.isSecureContext)try{return await Ce.writeText(Z),!0}catch{}let Te=null;try{return Te=ee.createElement("textarea"),Te.value=Z,Te.setAttribute("readonly","true"),Te.style.position="fixed",Te.style.left="-9999px",Te.style.top="0",ee.body.appendChild(Te),Te.focus(),Te.select(),ee.execCommand("copy")}catch{return!1}finally{Te==null||Te.remove()}},Ge=Z=>{U(),L(Z);const ee=ae();ve.current={ownerWindow:ee,timeoutId:ee.setTimeout(()=>{ve.current=null,L(he=>he===Z?null:he)},2200)}},bt=Z=>{H(),j(Z);const ee=ae();xe.current={ownerWindow:ee,timeoutId:ee.setTimeout(()=>{xe.current=null,j(he=>he===Z?null:he)},2200)}},V=async()=>{var Te,Ie,Le,Be;const Z=((Ie=(Te=r.current)==null?void 0:Te.getSelection)==null?void 0:Ie.call(Te))||"",ee=((Be=(Le=r.current)==null?void 0:Le.getVisibleText)==null?void 0:Be.call(Le))||"",he=Z.trimEnd()||ee.trimEnd();if(!he){Ge("Nothing to copy");return}if(!await Qe(he)){Ge("Copy failed");return}Ge(Z.trimEnd()?"Copied selection":"Copied visible terminal")},G=Z=>{if(!m||!i)return;((u==null?void 0:u(W,E,Z))??!1)||Ge("Terminal input failed")},te=async()=>{if(g)return;f(!0),j("Loading older terminal output..."),Q.current=!0;const Z=await Se({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(f(!1),(Z==null?void 0:Z.success)===!1){Q.current=!1,j(`Older terminal output unavailable: ${Z.error}`);return}k(!0),bt("Older terminal output loaded"),ge(()=>{var ee;(ee=r.current)==null||ee.bumpResize()})};l.useEffect(()=>{var ee,he;if(!E)return;W&&((ee=pt.getState)==null?void 0:ee.call(pt,W))==="connected"&&Se();const Z=(he=pt.onStateChange)==null?void 0:he.call(pt,(Ce,Te)=>{Ce!==W||Te!=="connected"||Se()});return()=>{Z==null||Z()}},[W,E,r]),l.useEffect(()=>{t&&nt()},[t,ne,r]),l.useEffect(()=>{var Ce,Te;const Z=$.current,ee=(Te=(Ce=Z==null?void 0:Z.ownerDocument)==null?void 0:Ce.defaultView)==null?void 0:Te.ResizeObserver;if(!Z||!ee)return;const he=new ee(Ie=>{const Le=Ie[0];if(!Le)return;const{width:Be,height:Ae}=Le.contentRect;R(We=>{const qe=Math.round(Be),mt=Math.round(Ae);return We.width===qe&&We.height===mt?We:{width:qe,height:mt}})});return he.observe(Z),()=>he.disconnect()},[]),l.useEffect(()=>{if(z.current)return;const Z=Pe();!Number.isFinite(Z)||Z<=0||I(ee=>re.current?Z<ee-oe?Z:ee:(re.current=!0,Z))},[O.height,O.width,T.height,T.width]),l.useEffect(()=>{$e&&Je()},[$e,Xe,He]),l.useEffect(()=>{var he;const Z=J.current;if(J.current=i,!i)return;Z||k(!1),X.current&&(X.current=!1,et());const ee=be.current;ee&&(be.current=null,Me(ee.text,ee.seq,ee.cols,ee.rows,{force:!!ee.force})),W&&E&&((he=pt.getState)==null?void 0:he.call(pt,W))==="connected"&&Se(),fe.current&&we.current===null&&q(),ge(()=>{var Ce;(Ce=r.current)==null||Ce.bumpResize()})},[W,i,E]),l.useEffect(()=>()=>{we.current!==null&&me(),U(),H()},[]),l.useEffect(()=>{const Z=Ce=>{var Ie;const Te=Ce.detail;Te!=null&&Te.sessionId&&Te.sessionId!==E||m&&((Ie=r.current)==null||Ie.bumpResize())},ee=ae(),he=ee===window?[window]:[window,ee];for(const Ce of he)Ce.addEventListener("adhdev:fit-cli-terminal",Z);return()=>{for(const Ce of he)Ce.removeEventListener("adhdev:fit-cli-terminal",Z)}},[m,E,r]);const ye=m&&y&&!N&&(S.atTop||!S.canScroll)||g||!!w;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:$,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[ye&&s.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{te()},disabled:!E||g,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:g?"Loading older...":"Load older terminal output"}),w&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:w})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[B&&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:B}),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:()=>P(Z=>!Z),title:"Spec debug — inspect current state, sections, and transition history",children:"Debug"}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{V()},disabled:!m,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:"Copy"}),s.jsxs("div",{className:"relative",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>M(Z=>!Z),disabled:!m,"aria-label":"Open terminal control keys","aria-expanded":C,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),C&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":"Terminal control keys",className:"absolute right-0 top-10 w-56 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),s.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>M(!1),"aria-label":"Close terminal control keys",children:"×"})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>G("\x1B"),children:"Esc"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>G(" "),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:()=>G("\r"),children:"Enter"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>G("\x1B[A"),"aria-label":"Arrow up",children:"↑"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>G("\x1B[D"),"aria-label":"Arrow left",children:"←"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>G("\x1B[B"),"aria-label":"Arrow down",children:"↓"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>G("\x1B[C"),"aria-label":"Arrow right",children:"→"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>G(""),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:()=>G(""),children:"Ctrl-D"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>G(""),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:()=>{z.current=!0,I(Z=>{const ee=Math.max(Ee,Number((Z-.1).toFixed(2)));return ee>Ee&&Je(),ee})},title:"Shrink terminal viewport",children:"-"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{z.current=!0,I(Z=>{const ee=Math.min(ue,Number((Z+.1).toFixed(2)));return ee>Ee&&Je(),ee})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:F,className:$e?"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:He>0?`${He}px`:"100%",height:Xe>0?`${Xe}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:O.width>0?`${O.width}px`:"100%",height:O.height>0?`${O.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:x},children:s.jsx(gd,{ref:r,readOnly:!m||!i,sizingMode:"measured",onViewportMetrics:K,onScrollMetrics:A,onInput:Z=>{!m||(u==null||u(W,E,Z))}})})})}),!m&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:h})]}),s.jsx(Ld,{contextKey:e.tabKey,panelLabel:it(e),isSending:a,isBusy:!!_,statusMessage:ie,onSend:async Z=>_?!1:n(Z),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),D&&s.jsx(rg,{activeConv:e,onClose:()=>P(!1)})]})}const ag=5e3,og=12e3;function ig(e){return e==="disconnected"||e==="reconnecting"}function lg({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=ag,reconnectActionDelayMs:o=og}){const i=ig(e),[c,u]=l.useState(()=>!i||a<=0),[m,d]=l.useState(()=>!i||o<=0),p=l.useRef(!1);l.useEffect(()=>{if(!i){u(!1);return}if(p.current=!1,a<=0){p.current=!0,u(!0);return}u(!1);const k=setTimeout(()=>{p.current=!0,u(!0)},a);return()=>clearTimeout(k)},[a,i]),l.useEffect(()=>{if(!i){d(!1);return}if(o<=0){d(!0);return}d(!1);const k=setTimeout(()=>{d(!0)},o);return()=>clearTimeout(k)},[o,i]);const h=i?c:e==="offline"||e==="auth_failed",b=!!(n&&e!=="auth_failed"&&(!i||m)),g=l.useMemo(()=>!t||e!=="connected"?!1:a<=0||p.current,[a,t,e]),f=e==="auth_failed"?"red":e==="offline"?"orange":"accent",w={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},j={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},y={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},v="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",N={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[h&&s.jsx("div",{className:v,style:N,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:w[f],border:j[f],color:y[f]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&"Network offline",e==="disconnected"&&"Reconnecting",e==="reconnecting"&&"Reconnecting",e==="auth_failed"&&(r?s.jsxs(s.Fragment,{children:["Session expired."," ",s.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — refresh the page or try again shortly.")]}),b&&s.jsx("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>n==null?void 0:n(),disabled:e==="offline",children:"Reconnect now"})]})}),g&&s.jsx("div",{className:v,style:N,children:s.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})})]})}function nu({mode:e,onChange:t,compact:r=!1}){const n=r?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:e==="chat"?"Switch to Terminal view":"Switch to Chat view",children:e==="chat"?s.jsx(Yo,{size:n}):s.jsx(Is,{size:n})})}const Ut="New session",au="A connected machine is ready. Start a new session with any installed provider — CLI, ACP, or IDE.";function cg(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 dg(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 ug(e){switch(e){case"conflict":return"border-red-500/25 bg-red-500/[0.08] text-red-400";case"error":return"border-yellow-500/25 bg-yellow-500/[0.08] text-yellow-500";case"dirty":return"border-orange-500/25 bg-orange-500/[0.08] text-orange-400";case"quiet":default:return"border-emerald-500/15 bg-emerald-500/[0.06] text-emerald-500"}}function Gn({git:e,className:t="",compact:r=!1}){const n=cg(e),a=dg(e);if(!n||!a)return null;const o=[e!=null&&e.branch?`Branch: ${e.branch}`:null,e!=null&&e.changedFiles?`Changed files: ${e.changedFiles}`:null,e!=null&&e.ahead?`Ahead: ${e.ahead}`:null,e!=null&&e.behind?`Behind: ${e.behind}`:null,e!=null&&e.hasConflicts?"Conflicts detected":null,e!=null&&e.error?`Git error: ${e.error}`:null].filter(Boolean);return s.jsxs("span",{className:`inline-flex min-w-0 max-w-[12rem] items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none ${ug(a)} ${t}`.trim(),title:o.join(" · ")||n,"data-git-tone":a,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:n})]})}function mg({wsStatus:e,isConnected:t,daemonCount:r,p2pStates:n={}}){if(e!=="connected")return{tone:"disconnected",title:"Disconnected",subtitle:null};const a=Object.values(n),o=a.filter(c=>c==="connected").length,i=a.filter(c=>c==="connecting"||c==="new"||c==="checking").length;return r>0&&i>0&&o===0?{tone:"limited",title:"Connected to dashboard",subtitle:"Connecting to machine..."}:t?{tone:"connected",title:"Connected",subtitle:null}:{tone:"limited",title:"Connected to dashboard",subtitle:null}}function Ll({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Pl({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const i=ca(e.updatedAt),c=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${c?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",i].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[c?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),n()},children:"Mark read"}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),a()},children:"Mark unread"}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),o()},children:"Delete"})]})]})}function pg({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:u,onHideConversation:m,hiddenConversations:d=[],onShowConversation:p,onShowAllHidden:h,onResetPanelsToMain:b,inboxOpen:g,onInboxOpenChange:f,hiddenOpen:w,onHiddenOpenChange:j,onOpenNewSession:y,onOpenDashboardGuide:v,guideNudgeVisible:N=!1,actionShortcuts:k,notifications:x,notificationUnreadCount:I,onOpenNotification:C,onMarkNotificationRead:M,onMarkNotificationUnread:D,onDeleteNotification:P,onOpenGitDialog:T,onOpenMeshGraph:R}){var Ne;const{ides:O,p2pStates:K={}}=Yt(),S=!!e&&Ze(e)&&!Ye(e),A=!!e&&Ye(e),B=!!(e!=null&&e.daemonId)&&!!((Ne=e==null?void 0:e.coordinator)!=null&&Ne.meshId),L=c||(e?Pd(e)?"terminal":"chat":null),[$,F]=l.useState(!1),z=l.useRef(null),re=l.useRef(null),J=O.filter(ae=>ae.type==="adhdev-daemon"),Y=mg({wsStatus:t,isConnected:r,daemonCount:J.length,p2pStates:K}),se=Y.subtitle,fe=Y.tone==="connected"?"#22c55e":Y.tone==="limited"?"#eab308":"#ef4444",be=Y.tone==="connected"?"0 0 4px #22c55e80":Y.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",X=l.useMemo(()=>x.filter(ae=>!ae.readAt),[x]),Q=l.useMemo(()=>x.filter(ae=>!!ae.readAt),[x]),we=l.useMemo(()=>X.slice(0,9),[X]),ve=I;l.useEffect(()=>{if(!g)return;const ae=ge=>{var me;(me=z.current)!=null&&me.contains(ge.target)||f(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[g,f]),l.useEffect(()=>{if(!w)return;const ae=ge=>{var me;(me=re.current)!=null&&me.contains(ge.target)||j(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[w,j]),l.useEffect(()=>{if(!w&&!g)return;const ae=ge=>{if(!ge.altKey)return;const me=ge.code.match(/^Digit([1-9])$/);if(!me)return;const U=Number(me[1])-1,H=w?d[U]:void 0,q=g?we[U]:void 0;if(!(!H&&!q)){if(ge.preventDefault(),ge.stopPropagation(),H){p==null||p(H),j(!1);return}q&&(C(q),f(!1))}};return window.addEventListener("keydown",ae,!0),()=>window.removeEventListener("keydown",ae,!0)},[d,w,g,we,j,f,C,p]);const xe=ae=>{if(!ae)return;const ge=n.find(me=>me.tabKey===ae);ge&&(m==null||m(ge))};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(Is,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?it(e):"Dashboard"}),s.jsx("span",{title:Y.title,"aria-label":Y.title,className:"header-title-status-dot",style:{background:fe,boxShadow:be}}),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:fe,boxShadow:be}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[se&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",se]}),y&&s.jsx("button",{type:"button",onClick:y,className:"btn btn-secondary btn-sm ml-2",title:`${Ut}${k!=null&&k.openNewSession?` (${k.openNewSession})`:""}`,"aria-label":Ut,children:s.jsx(cd,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[v&&s.jsxs("button",{type:"button",onClick:v,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:"Dashboard guide","aria-label":"Open dashboard guide",children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),N&&s.jsx("span",{children:"Guide"})]}),e&&(S||A||!Ye(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:Ss(e)||it(e),children:it(e)}),T&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:()=>T(e.daemonId,e.workspacePath),children:s.jsx(Gn,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Gn,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),B&&R&&s.jsxs("button",{type:"button",onClick:()=>R(e),className:"btn btn-secondary btn-sm dashboard-header-mesh-button",title:"Open live repo mesh graph",children:[s.jsx(Qt,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:"Mesh graph"})]}),(S||A)&&i&&s.jsxs(s.Fragment,{children:[S&&u&&L&&s.jsx(nu,{mode:L,onChange:u,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:A?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(vt,{size:14})})]}),!Ye(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(Vo,{size:14})}),!S&&!Ye(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(Ot,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:z,children:[s.jsxs("div",{className:`dashboard-header-hidden${$?" is-drop-target":""}`,ref:re,onDragEnter:ae=>{ae.dataTransfer.types.includes("text/tab-key")&&(ae.preventDefault(),F(!0))},onDragOver:ae=>{ae.dataTransfer.types.includes("text/tab-key")&&(ae.preventDefault(),ae.dataTransfer.dropEffect="move",F(!0))},onDragLeave:ae=>{ae.currentTarget.contains(ae.relatedTarget)||F(!1)},onDrop:ae=>{const ge=ae.dataTransfer.getData("text/tab-key");ae.preventDefault(),F(!1),xe(ge)},children:[s.jsxs("button",{type:"button",onClick:()=>j(!w),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${k!=null&&k.toggleHiddenTabs?` (${k.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(qo,{size:16}),d.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:d.length})]}),w&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),s.jsx(Ll,{value:k==null?void 0:k.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[b&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:b,children:"Reset panels"}),d.length>0&&h&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{h(),j(!1)},children:"Restore all"})]})]}),e&&m&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>m(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),s.jsx(Ll,{value:k==null?void 0:k.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:it(e)})]}),d.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:d.map(ae=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{p==null||p(ae),j(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:it(ae)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(ae)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(ae)+1]}):null,Ss(ae)]})]},ae.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>f(!g),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(Er,{size:16}),ve>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:ve})]}),g&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[X.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),X.map(ae=>s.jsx(Pl,{notification:ae,shortcutIndex:we.indexOf(ae)>=0?we.indexOf(ae)+1:void 0,onOpen:()=>C(ae),onMarkRead:()=>M(ae.id),onMarkUnread:()=>D(ae.id),onDelete:()=>P(ae.id)},ae.id))]}),Q.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),Q.map(ae=>s.jsx(Pl,{notification:ae,onOpen:()=>C(ae),onMarkRead:()=>M(ae.id),onMarkUnread:()=>D(ae.id),onDelete:()=>P(ae.id)},ae.id))]}),x.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function Ct(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function hg(e,t){return String(e||"")!==String(t||"")}function fg(e,t={}){const r=String(t.textQuery||"").trim().toLowerCase(),n=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),o=!!t.resumableOnly;return!r&&!n&&!a&&!o?e:e.filter(i=>!(o&&!i.canResume||r&&![i.title,i.preview].map(u=>String(u||"").toLowerCase()).join(`
50
+ `).includes(r)||n&&!String(i.workspace||"").toLowerCase().includes(n)||a&&!Cd(i.summaryMetadata).map(u=>u.toLowerCase()).join(`
51
+ `).includes(a)))}function xg(e,t="recent"){const r=e.slice();return r.sort((n,a)=>{if(t==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="messages"){const o=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(o!==0)return o}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function ou(e,t={}){return xg(fg(e,t),t.sortMode||"recent")}function Vn(e){return e?"Resume saved history":"Start fresh"}function ci(e){return e?"Resuming saved history…":"Starting fresh…"}function bg(){return"Start fresh"}function gg(e,t=!1){return e==="cli"?Vn(t):e==="ide"?"Start IDE":"Start ACP session"}function yg(e,t=!1){return e==="cli"?ci(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function vg(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function wg(){return"Open saved history"}function jg(){return"Saved History"}function di(){return"Use saved history when you want continuity in the same provider conversation."}function kg(){return"No saved history found yet."}function Ng(){return"Refresh saved history"}function Sg(){return"Refreshing saved history…"}function qn(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function Yn(e){return e==="start-fresh"?"Review the provider and target folder before starting fresh.":e==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Jn(e){return e==="start-fresh"?"Start fresh":"Restart"}function Xn(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function iu(e){return`Resume saved history with ${e}?`}function lu(){return"Review or change the target workspace before resuming saved history."}function Cg(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 cu({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:u,onSavedHistoryFiltersChange:m,onClose:d,onNewChat:p,onSwitchSession:h,onRefreshHistory:b,onResumeSavedSession:g}){var P;const f=t.find(T=>T.id===e.routeId),w=(f==null?void 0:f.chats)||[],j=(P=f==null?void 0:f.activeChat)==null?void 0:P.id,y=Ze(e)&&!Ye(e),[v,N]=l.useState(()=>Ct()),k=c||v,x=String(u||"").trim(),I=T=>{if(m){m(T);return}N(T)},C=l.useMemo(()=>a.map(T=>{const R=String(T.workspace||"").trim();return T.canResume||R||!x?T:{...T,workspace:x,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[x,a]),M=l.useMemo(()=>ou(C,{textQuery:k.textQuery,workspaceQuery:k.workspaceQuery,modelQuery:k.modelQuery,resumableOnly:k.resumableOnly,sortMode:k.sortMode}),[C,k.modelQuery,k.resumableOnly,k.sortMode,k.textQuery,k.workspaceQuery]),D=s.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick: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:y?jg():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Gb(e)}),y&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:di()})]}),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(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!y&&s.jsx("button",{onClick:p,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),y?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:k.textQuery,onChange:T=>I({...k,textQuery:T.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:k.workspaceQuery,onChange:T=>I({...k,workspaceQuery:T.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:k.modelQuery,onChange:T=>I({...k,modelQuery:T.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:k.sortMode,onChange:T=>I({...k,sortMode:T.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:k.resumableOnly,onChange:T=>I({...k,resumableOnly:T.target.checked})}),"Resume-ready only"]})]}),M.map(T=>{const R=e.providerSessionId===T.providerSessionId,O=R||!T.canResume||!!i,K=T.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{O||!g||g(T)},disabled:O,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${R?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${O?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${R?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:T.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:T.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Cg(T.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:T.preview||"No saved preview yet"}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[T.workspace||"Workspace unknown",K?" · selected workspace":"",Ns(T.summaryMetadata)?` · ${Ns(T.summaryMetadata)}`:"",T.messageCount>0?` · ${T.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:R?"ACTIVE":T.canResume?K?"RESUME IN SELECTED WORKSPACE":i===T.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},T.id)})]}):w.map(T=>s.jsxs("div",{onClick:()=>{h(e.routeId,T.id),d()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${j===T.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${j===T.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:T.title||"Untitled Session"}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[T.id.substring(0,12),"..."]}),j===T.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},T.id)),(y&&!o&&M.length===0||!y&&w.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Sh,{size:32})}),s.jsx("div",{className:"text-[13px]",children:y?a.length>0?"No saved history matches these filters.":kg():"No recent chat sessions found."})]}),y&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Sg()})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:b,disabled:n||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||o?"⌛ Refreshing...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(la,{size:13})," ",y?Ng():"Refresh History"]})})})]})]});return typeof document>"u"?D:Ir.createPortal(D,document.body)}const Rl={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Done"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Attention"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Update"}};function du({toasts:e,onDismiss:t,onClickToast:r}){return s.jsx("div",{className:"fixed right-4 z-[9999] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(n=>{const a=Rl[n.type]||Rl.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var o;(o=n.actions)!=null&&o.length||r&&r(n)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:o=>{o.stopPropagation(),t(n.id)},"aria-label":"Dismiss",children:s.jsx(vt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:a.label})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((o,i)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${o.variant==="primary"||o.variant==="danger",""}`,style:o.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:o.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:c=>{c.stopPropagation(),o.onClick(),t(n.id)},children:o.label},i))})]})]},n.id)})})}const Ig=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Mg(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function Ag(e){return e.sessionId||e.instanceId||e.agentType}function La(e,t){return t||e||"unknown"}function uu(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Pt(r,{fallbackId:r.id}));return t}function mu(e,t={}){var n,a;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((a=t.machineNames)==null?void 0:a[e.daemonId])||void 0,connectionState:t.connectionStates?t.connectionStates[r]||t.defaultConnectionState||"new":t.defaultConnectionState}}function ui(e,t={}){return Tg(e,mu(e,t))}function Tg(e,t={}){var p,h,b,g,f,w,j,y,v;const r=[],n=t.machineName,a=t.connectionState,o=Mg(e),i=e.workspace||"",c=_f(e.type,{agentName:e.cliName}),u=Ze(e)||Ye(e)?c:wt(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(N=>{var k,x,I;return{sessionId:N.id,instanceId:N.id,providerSessionId:N.providerSessionId,activeChatId:(k=N.activeChat)==null?void 0:k.id,transport:N.transport,sessionCapabilities:N.capabilities,agentType:N.providerType,agentName:N.providerName||wt(N.providerType),status:N.status,title:N.title,lastMessagePreview:N.lastMessagePreview,lastMessageRole:N.lastMessageRole,lastMessageAt:N.lastMessageAt,lastMessageHash:N.lastMessageHash,messages:((x=N.activeChat)==null?void 0:x.messages)||[],activeModal:((I=N.activeChat)==null?void 0:I.activeModal)||void 0,unread:N.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,inboxBucket:N.inboxBucket,completionMarker:N.completionMarker,surfaceHidden:N.surfaceHidden,git:N.git,settings:N.settings,coordinator:N.coordinator,messageInput:N.messageInput}}):[],d=Ig(e);if(d){const N=e.sessionId||e.instanceId,k=(p=e.settings)==null?void 0:p.meshCoordinatorFor,x=((h=e.settings)==null?void 0:h.meshNodeFor)||!((b=e.settings)!=null&&b.meshCoordinatorFor)&&((g=e.settings)==null?void 0:g.launchedByCoordinator),I=k?" (Coordinator)":x?" (Mesh Node)":"",C=c+I,M=(f=e.activeChat)==null?void 0:f.activeModal,D=M&&Array.isArray(M.buttons)&&M.buttons.length>0,P=Lf(e.activeChat,[{status:e.status,activeModal:(w=e.activeChat)==null?void 0:w.activeModal}],e.agents||[]),T=e.activeChat||{title:"",messages:[]};let R=T.title&&String(T.title).trim()?String(T.title).trim():"";const O=(j=e.activeChat)==null?void 0:j.id,K=e.chats;if(O&&Array.isArray(K)&&K.length>0){const re=K.find(J=>J.id===O||J.id&&String(J.id)===String(O));re!=null&&re.title&&String(re.title).trim()&&(R=String(re.title).trim())}const S=(Ze(e)||Ye(e),e.type),A=(Ze(e)||Ye(e))&&cl(R,C,S)?"":R,B=T.messages||[],L=typeof O=="string"?O.trim():"",$=(Ze(e)||Ye(e))&&L===String(e.type||"").trim(),F=L&&!$?L:e.providerSessionId,z=e.coordinator||(typeof((y=e.settings)==null?void 0:y.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);r.push({routeId:e.id,sessionId:N,providerSessionId:e.providerSessionId,historySessionId:F,nativeSessionId:N,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:Ze(e)?e.mode||"terminal":"chat",agentName:C,agentType:S,status:P,title:A,messages:B,resume:e.resume,hostIdeType:!Ze(e)&&!Ye(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:A||o||(Ze(e)?e.mode==="chat"?C:`Terminal${I}`:C),displaySecondary:Ze(e)&&o?C:u,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:D?M.buttons:void 0,modalMessage:D?M.message:void 0,streamSource:"native",tabKey:La(N,e.id),machineName:n,connectionState:a,settings:e.settings,coordinator:z,messageInput:e.messageInput})}if(d&&(Ze(e)||Ye(e)))return r;for(const N of m){const k=N.activeModal&&Array.isArray(N.activeModal.buttons)&&N.activeModal.buttons.length>0,x=Pf(N),I=Ag(N),C=`${e.id}:${I}`,M=N.title&&String(N.title).trim()||"",D=cl(M,N.agentName,N.agentType)?"":M,P=N.messages||[];if(!(N.transport==="cdp-webview"||!!N.sessionId||!!N.providerSessionId||P.length>0||k||!!D||!["idle","panel_hidden","disconnected","not_monitored"].includes(x)))continue;const R=N.coordinator||(typeof((v=N.settings)==null?void 0:v.meshCoordinatorFor)=="string"&&N.settings.meshCoordinatorFor?{meshId:N.settings.meshCoordinatorFor,role:"coordinator"}:void 0);r.push({routeId:e.id,sessionId:N.sessionId||N.instanceId,providerSessionId:N.providerSessionId,historySessionId:N.activeChatId||N.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:N.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:N.sessionCapabilities,mode:"chat",agentName:N.agentName,agentType:N.agentType,status:x,title:D,messages:P,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:N.git||e.git,displayPrimary:D||o||N.agentName||u,displaySecondary:`${u} · ${N.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:N.lastMessagePreview,lastMessageRole:N.lastMessageRole,lastMessageAt:N.lastMessageAt,lastMessageHash:N.lastMessageHash,lastUpdated:N.lastUpdated||e.lastUpdated,inboxBucket:N.inboxBucket,completionMarker:N.completionMarker,modalButtons:k?N.activeModal.buttons:void 0,modalMessage:k?N.activeModal.message:void 0,streamSource:"agent-stream",tabKey:La(N.sessionId||N.instanceId,C),machineName:n,connectionState:a,settings:N.settings,coordinator:R,messageInput:N.messageInput})}return r.length===0&&r.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||u,displaySecondary:u,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:La(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),r}function pu(e){return String(e.type||e.id||"").trim()}function _g(e){var t;return e.category!=="cli"||!pu(e)||e.enabled===!1?!1:e.machineStatus?e.machineStatus==="detected":((t=e.lastDetection)==null?void 0:t.ok)===!0||e.installed===!0||!!e.detectedPath}function _r(e){var n;const t=new Set,r=[];for(const a of e||[]){if(!_g(a))continue;const o=pu(a);if(!o||t.has(o))continue;t.add(o);const i=String(a.displayName||a.name||o),c=a.detectedPath||((n=a.lastDetection)==null?void 0:n.path)||null;r.push({type:o,label:i,icon:a.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c})}return r}function Wr(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],r=new Set,n=[];for(const a of t){const o=typeof a=="string"?a.trim():"";!o||r.has(o)||(r.add(o),n.push(o))}return n}function In(e,t){const r=new Set(t.map(n=>n.type));return Wr(e).filter(n=>r.has(n))}function Lr(e){return e.map(t=>t.type)}function Lg(e,t){const r=Wr(e),n=t.trim();return!n||r.includes(n)?r:[...r,n]}function Pg(e,t){return Wr(e).filter(r=>r!==t)}function Dl(e,t,r){const n=Wr(e),a=n.indexOf(t);if(a<0)return n;const o=n.filter(c=>c!==t);if(r==="top")return[t,...o];if(r==="bottom")return[...o,t];const i=r==="up"?Math.max(0,a-1):Math.min(o.length,a+1);return o.splice(i,0,t),o}function $l({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 El({value:e,availableProviders:t,onChange:r,disabled:n=!1,saveButton:a}){const[o,i]=l.useState(""),c=l.useMemo(()=>new Map(t.map(h=>[h.type,h])),[t]),u=l.useMemo(()=>In(e,t),[e,t]),m=e.length-u.length,d=t.filter(h=>!u.includes(h.type)),p=()=>{o&&(r(Lg(u,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:u.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."}):u.map((h,b)=>{const g=c.get(h);return s.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border-subtle bg-bg-primary px-3 py-2 sm:flex-row sm:items-center sm:justify-between",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",b+1]}),(g==null?void 0:g.icon)&&s.jsx("span",{"aria-hidden":"true",children:g.icon}),s.jsx("span",{className:"font-mono text-[12px] text-text-primary",children:h}),s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:"available"})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:g?`${g.label} · ${g.statusLabel}`:h})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:n||b===0,title:"Move up",onClick:()=>r(Dl(u,h,"up")),children:s.jsx($l,{direction:"up"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move down",disabled:n||b===u.length-1,title:"Move down",onClick:()=>r(Dl(u,h,"down")),children:s.jsx($l,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>r(Pg(u,h)),children:"Remove"})]})]},h)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:"Add available CLI provider"}),s.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:o,onChange:h=>i(h.target.value),disabled:n||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:n||!o,onClick:p,children:"Add provider"}),a]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Inventory is filtered to CLI providers detected on this machine. New launches use this order; existing running sessions may need restart.",m>0?` ${m} provider${m===1?"":"s"} from the saved policy are not detected now and will be omitted when saved.`:""]})]})}function Rg(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 hu(e,t){const r=Rg(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const fu=[{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:"🏄"}],xu=[{id:"aider-cli",name:"Aider",icon:"🛠️"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"gemini-cli",name:"Gemini CLI",icon:"✨"},{id:"github-copilot-cli",name:"GitHub Copilot CLI",icon:"🤖"},{id:"goose-cli",name:"Goose",icon:"🪿"},{id:"opencode-cli",name:"OpenCode CLI",icon:"🧩"}],bu=[{id:"cline",name:"Cline",icon:"🧠"},{id:"codex",name:"Codex",icon:"📦"},{id:"roo-code",name:"Roo Code",icon:"🦘"},{id:"claude-code-vscode",name:"Claude Code (VS Code)",icon:"🟠"}],Dg=fu,$g=xu,Eg=bu;function es(...e){return wp(jp(e))}function Bg({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:es("dashboard-header",o),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,n&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function Kr({icon:e,title:t,subtitle:r,badge:n,actions:a,widthClassName:o="max-w-6xl",contentClassName:i,children:c}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(Bg,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:es("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const _o="adhdev:themechange";function Fg(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Ls(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Ps(e){return e==="system"?Fg():e}function gu(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Mn(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(_o,{detail:{preference:e,theme:t}}))}function Og(){const e=Ls(),t=Ps(e);gu(t),Mn(e,t)}function Ys(){const[e,t]=l.useState(Ls),[r,n]=l.useState(()=>Ps(Ls()));l.useEffect(()=>{gu(r)},[r]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=u=>{if(e==="system"){const m=u.matches?"light":"dark";n(m),Mn("system",m)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=u=>{const m=u.detail||{},d=m.preference,p=m.theme;t(d==="dark"||d==="light"||d==="system"?d:Ls()),n(p==="dark"||p==="light"?p:Ps(Ls()))},c=u=>{if(u.key!=="theme")return;const m=Ls(),d=Ps(m);t(m),n(d)};return window.addEventListener(_o,i),window.addEventListener("storage",c),()=>{window.removeEventListener(_o,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{const c=Ps(i);t(i),n(c);try{localStorage.setItem("theme",i)}catch{}Mn(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",u=Ps(c);n(u);try{localStorage.setItem("theme",c)}catch{}return Mn(c,u),c})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const Bl={dark:"Dark",light:"Light",system:"System"};function zg({collapsed:e}){const{preference:t,cycleTheme:r}=Ys(),n=t==="dark"?s.jsx(Ih,{size:16}):t==="light"?s.jsx(Ch,{size:16}):s.jsx(Mh,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Bl[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:Bl[t]})]})}function Pa(e,t){return e?typeof e=="function"?e(t):e:null}function Hg({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:u="sidebar-collapsed"}){const[m,d]=l.useState(!1),[p,h]=l.useState(()=>{try{return localStorage.getItem(u)==="1"}catch{return!1}}),b=()=>d(!0),g=()=>d(!1),f=()=>{h(v=>{const N=!v;try{localStorage.setItem(u,N?"1":"0")}catch{}return N})},w=l.useMemo(()=>({collapsed:p,mobileMenuOpen:m,openMobileMenu:b,closeMobileMenu:g,toggleCollapsed:f}),[p,m]),j=v=>`nav-item${v.active?" active":""} cursor-pointer ${p?"justify-center py-2.5 px-0":""}${v.className?` ${v.className}`:""}`,y=v=>s.jsxs("div",{className:j(v),id:`nav-${v.id}`,onClick:()=>{v.onSelect(),g()},title:p?v.title??(typeof v.label=="string"?v.label:void 0):v.title,children:[s.jsx("span",{className:"nav-icon",children:v.icon}),!p&&v.label]},v.id);return s.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${p?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:b,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),m&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:g,onKeyDown:v=>v.key==="Escape"&&g()}),s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${p?"justify-center gap-0":""}`,children:Pa(t,w)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:g,children:s.jsx(vt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(y)}),n.map(v=>s.jsxs("div",{className:v.className??"border-t border-border-subtle pt-2 mt-2",children:[!p&&v.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:v.title}):null,v.items.map(y)]},v.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(y),Pa(o,w),s.jsx(zg,{collapsed:p}),Pa(i,w)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function ut({title:e,icon:t,description:r,accentColor:n,className:a,children:o}){return s.jsxs("div",{className:es("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&s.jsxs("div",{className:"mb-4",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[t&&s.jsx("span",{className:"mr-1.5",children:t}),e]}),r&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),o]})}function ha({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:es("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const Wg={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"},Kg={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function os({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:es("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Wg[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Kg[e]}),s.jsx("span",{children:t})]}),r&&s.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function jt({label:e,hint:t,children:r,className:n}){return s.jsxs("div",{className:es("mb-5",n),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),r,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function jr(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:es("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 Ug={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"},Gg={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Vg({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:es("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Ug[e],r),children:[s.jsx("span",{className:es("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Gg[e])}),n]})}function fs({label:e,description:t,checked:r,disabled:n,onChange:a,extra:o}){return s.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[o,s.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>a(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function qg({onPrefChange:e}){const[t,r]=Wf(),[n,a]=l.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);l.useEffect(()=>{const i=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return i(),window.addEventListener("focus",i),document.addEventListener("visibilitychange",i),()=>{window.removeEventListener("focus",i),document.removeEventListener("visibilitychange",i)}},[]);const o=(i,c)=>{r({[i]:c}),e==null||e(i,c)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Er,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:i=>o("globalEnabled",i)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ot,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:i=>o("browserNotifications",i)}),t.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),n==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[s.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),s.jsx("button",{onClick:()=>{Ad().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),t.globalEnabled&&t.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(dd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:i=>o("completionAlert",i)}),s.jsx(fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ah,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:i=>o("approvalAlert",i)}),s.jsx(fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Hs,{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 Qn(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Yg(e,t){const r=Qn(e),n=Qn(t);if(!r||!n)return e.localeCompare(t);for(let a=0;a<3;a+=1){if(r[a]<n[a])return-1;if(r[a]>n[a])return 1}return 0}function mi(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function kr(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||Yg(r,t)>=0)return!1;const n=Qn(r),a=Qn(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Jg(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Ra(e,t){return e instanceof Error?e.message:t}function Xg({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const o=e.filter(i=>i.type==="adhdev-daemon");return o.length===0?s.jsx(ha,{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(Zg,{ide:i,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},i.id))})}function Fl({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:o}){const i=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return Ir.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:o,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:c=>c.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:o,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${i}`,style:n==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:r})]})]})}),document.body)}function Qg(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Dg,...$g,...Eg].find(a=>a.id===t||t.includes(a.id)||a.id.includes(t));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function Zg({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var O,K;const[o,i]=l.useState("idle"),[c,u]=l.useState(""),[m,d]=l.useState(null),[p,h]=l.useState("idle"),[b,g]=l.useState(""),f=e.version||null,w=((O=e.machine)==null?void 0:O.platform)||((K=e.system)==null?void 0:K.platform)||"",j=Pt(e,{fallbackId:e.id}),y=w==="win32"?"🪟":w==="darwin"?"🍎":"🐧",v=t.filter(S=>S.daemonId===e.id&&S.transport==="cdp-page"),N=t.filter(S=>S.daemonId===e.id&&S.transport==="pty"),k=t.filter(S=>S.daemonId===e.id&&S.transport==="acp"),x=e.p2p,I=async()=>{if(r){i("upgrading"),u("Starting upgrade...");try{const S=Jg(await r(e.id,"daemon_upgrade",{}));S.alreadyLatest?(i("done"),u(`Already on v${S.version||"latest"}.`)):S.upgraded||S.success?(i("done"),u(`Upgrade to v${S.version||"latest"} started. Daemon is restarting...`)):(i("error"),u(S.error||"Upgrade failed"))}catch(S){i("error"),u(Ra(S,"Connection lost during upgrade"))}}},C=async()=>{if(d(null),!!n){h("loading");try{await n(e.id),h("done"),g("Machine disconnected.")}catch(S){h("error"),g(Ra(S,"Failed to disconnect"))}}},M=async()=>{if(d(null),!!a){h("loading");try{await a(e.id),h("done"),g("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(S){h("error"),g(Ra(S,"Failed to revoke token"))}}},D="0.9.82",P=mi(e,D),T=kr(e,D),R=v.length+N.length+k.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:y}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:j}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),f&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${P?"":"bg-bg-secondary"}`,style:P?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",f,!P&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&P&&s.jsx("button",{onClick:I,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${D}`,children:o==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${T?"↑ Update now":`↑ Update${` to v${D}`}`}`}),n&&s.jsx("button",{onClick:()=>d("disconnect"),disabled:p==="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:p==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(Vg,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[x&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${x.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${x.state==="connecting"||x.state==="new"?"animate-pulse":""}`,style:x.state==="connecting"||x.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",x.state==="connected"?"connected":x.state==="connecting"||x.state==="new"?"connecting...":x.state||"off"]}),x.peers!==void 0&&x.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",x.peers," peer",x.peers!==1?"s":"",")"]})]}),x&&R>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),R>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[v.map(S=>{const A=Qg(S.type),B=S.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:A.icon}),s.jsx("span",{children:A.name}),B!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${B?"bg-green-400":"animate-pulse"}`,style:B?void 0:{background:"var(--status-warning)"},title:B?"CDP connected":"CDP connecting..."})]},S.id)}),N.map(S=>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:S.cliName||"CLI"})]},S.id)),k.map(S=>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:S.cliName||"ACP"})]},S.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(c||b)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||p==="error"?"text-red-400":o==="done"||p==="done"?"text-green-400":"text-text-muted"}`,children:b||c})]}),m==="disconnect"&&s.jsx(Fl,{title:"🔌 Disconnect Machine",message:`Disconnect "${j}" from ADHDev?
52
+
53
+ This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
54
+
55
+ Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:C,onCancel:()=>d(null)}),m==="revoke"&&s.jsx(Fl,{title:"⚠️ Remove Machine",message:`Remove "${j}" from your dashboard?
56
+
57
+ This will:
58
+ • Immediately disconnect the machine
59
+ • Delete the machine registration
60
+ • Require restarting ADHDev on that machine
61
+
62
+ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:M,onCancel:()=>d(null)})]})}const e0=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function t0({daemonId:e,knownCliTypes:t=e0}){const{sendCommand:r}=lt(),[n,a]=l.useState({}),[o,i]=l.useState({}),[c,u]=l.useState(!0),[m,d]=l.useState(null),[p,h]=l.useState(null),[b,g]=l.useState(""),f=l.useCallback(async()=>{if(e){u(!0),h(null);try{const y=await r(e,"list_coordinator_prompts",{}),v=y!=null&&y.result&&typeof y.result=="object"?y.result:y;if(!(v!=null&&v.success)){h((v==null?void 0:v.error)||"Failed to load");return}const N=v.entries||{};g(v.dir||"");const k={};for(const x of t)k[x]=N[x]||{override:"",append:""};for(const x of Object.keys(N))k[x]||(k[x]=N[x]);a(k),i(JSON.parse(JSON.stringify(k)))}catch(y){h((y==null?void 0:y.message)||String(y))}finally{u(!1)}}},[r,e,t]);l.useEffect(()=>{f()},[f]);const w=l.useCallback(async(y,v)=>{var N;if(e){d(`${y}:${v}`),h(null);try{const k=((N=n[y])==null?void 0:N[v])||"",x=await r(e,"write_coordinator_prompt",{key:y,kind:v,content:k}),I=x!=null&&x.result&&typeof x.result=="object"?x.result:x;if(!(I!=null&&I.success)){h((I==null?void 0:I.error)||"Save failed");return}i(C=>({...C,[y]:{...C[y]||{override:"",append:""},[v]:k}}))}catch(k){h((k==null?void 0:k.message)||String(k))}finally{d(null)}}},[r,e,n]),j=l.useMemo(()=>(y,v)=>{var N,k;return(((N=n[y])==null?void 0:N[v])||"")!==(((k=o[y])==null?void 0:k[v])||"")},[n,o]);return e?s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{className:"text-[12px] text-text-muted",children:[s.jsxs("p",{children:["Customize the coordinator prompt this daemon's mesh coordinator sessions get. ",s.jsx("span",{className:"font-mono text-[11px]",children:b||"~/.adhdev/coordinator-prompts/"})]}),s.jsxs("p",{className:"mt-1",children:[s.jsx("strong",{children:"Override"})," replaces the daemon's built-in base prompt for that CLI."," ",s.jsx("strong",{children:"Append"})," stacks after whichever base wins. Leave a field empty + Save to remove it (reset to default). Supports placeholders: ","{{meshName}}",", ","{{repo}}",", ","{{nodes}}",", ","{{rules}}",", etc."]})]}),p&&s.jsx("div",{className:"text-[12px] text-red-400 bg-red-500/10 border border-red-500/20 rounded px-3 py-2",children:p}),c&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Loading…"}),s.jsx("div",{className:"flex flex-col gap-6",children:Object.entries(n).map(([y,v])=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-2",children:y}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:"Override"}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:4,value:v.override,onChange:N=>a(k=>({...k,[y]:{...k[y],override:N.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:m===`${y}:override`}),s.jsx("div",{className:"mt-1 mb-3 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void w(y,"override"),disabled:m===`${y}:override`||!j(y,"override"),children:m===`${y}:override`?"Saving…":j(y,"override")?"Save override":"Saved"})}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:"Append"}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:3,value:v.append,onChange:N=>a(k=>({...k,[y]:{...k[y],append:N.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:m===`${y}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void w(y,"append"),disabled:m===`${y}:append`||!j(y,"append"),children:m===`${y}:append`?"Saving…":j(y,"append")?"Save append":"Saved"})})]},y))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const s0=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function r0(){const{preference:e,setPreference:t}=Ys();return s.jsx("div",{className:"flex gap-2",children:s0.map(r=>s.jsxs("button",{onClick:()=>t(r.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===r.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===r.id?{color:"var(--accent-on-primary)"}:void 0,children:[s.jsx("span",{children:r.icon}),r.label]},r.id))})}function n0(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 a0(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Da(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Ol(e){const{r:t,g:r,b:n}=a0(e);return .2126*Da(t)+.7152*Da(r)+.0722*Da(n)}function zl(e,t){const r=Ol(e),n=Ol(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function yu(e){const t=n0(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return zl(t,r)>=zl(t,n)?r:n}const Lo={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},Po={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},o0=[{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"}}}],vu="adhdev-chat-theme",wu="adhdev-chat-theme-custom";function An(){if(typeof window>"u")return"ember";try{return localStorage.getItem(vu)||"ember"}catch{return"ember"}}function Bt(e){try{const t=localStorage.getItem(wu);if(t){const r=JSON.parse(t);return{...e==="dark"?Lo:Po,...r[e]}}}catch{}return e==="dark"?Lo:Po}function un(e,t){try{localStorage.setItem(wu,JSON.stringify({dark:e,light:t}))}catch{}}function Tt(e,t){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${a}, ${t})`}function Zn(e,t){const r=Math.min(255,parseInt(e.slice(1,3),16)+t),n=Math.min(255,parseInt(e.slice(3,5),16)+t),a=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const i0={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Nr(e,t){var a;const r=(a=i0[e])==null?void 0:a[t];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",Zn(r,24)),n.style.setProperty("--accent-on-primary",yu(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Zn(r,18)})`),n.style.setProperty("--border-accent",Tt(r,.35)),n.style.setProperty("--nav-active-bg",Tt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Tt(r,.06)}`)}function vs(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Tt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Tt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Tt(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",Tt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Tt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Zn(e.accentColor,30)),t.style.setProperty("--accent-on-primary",yu(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Zn(e.accentColor,40)})`),t.style.setProperty("--border-accent",Tt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Tt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Tt(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 ${Tt(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 pi(){const e=document.documentElement;["--bg-primary","--bg-secondary","--bg-card","--surface-primary","--surface-secondary","--bg-glass","--bg-glass-hover","--text-primary","--text-secondary","--text-muted","--border-subtle","--border-default","--accent-primary","--accent-primary-light","--accent-on-primary","--accent-gradient","--border-accent","--nav-active-bg","--nav-active-shadow","--chat-user-bg","--chat-user-color","--chat-user-radius","--chat-assistant-bg","--chat-assistant-color","--chat-assistant-radius","--chat-assistant-border","--chat-container-bg","--dashboard-pane-bg","--chat-thought-accent","--chat-tool-accent","--chat-action-color","--chat-send-bg","--chat-input-border"].forEach(r=>e.style.removeProperty(r))}function l0(e){try{localStorage.setItem(vu,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ws()?"dark":"light";vs(Bt(t))}else pi(),Nr(e,ws()?"dark":"light")}function c0(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=An();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ws()?"dark":"light";vs(Bt(t))}else pi(),Nr(e,ws()?"dark":"light")}function ws(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Nt({label:e,value:t,onChange:r}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function ir({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 d0({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=l.useState(()=>Bt(r));l.useEffect(()=>{a(Bt(r))},[r]);const o=l.useCallback((i,c)=>{a(u=>{const m={...u,[i]:c},p=Bt(r==="dark"?"light":"dark");return r==="dark"?un(m,p):un(p,m),vs(m),t(m),m})},[r,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",s.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(ir,{title:"App Background",children:[s.jsx(Nt,{label:"Background",value:n.bgPrimary,onChange:i=>o("bgPrimary",i)}),s.jsx(Nt,{label:"Surface",value:n.bgSecondary,onChange:i=>o("bgSecondary",i)}),s.jsx(Nt,{label:"Card",value:n.surfacePrimary,onChange:i=>o("surfacePrimary",i)})]}),s.jsxs(ir,{title:"App Text",children:[s.jsx(Nt,{label:"Primary",value:n.textPrimary,onChange:i=>o("textPrimary",i)}),s.jsx(Nt,{label:"Secondary",value:n.textSecondary,onChange:i=>o("textSecondary",i)}),s.jsx(Nt,{label:"Muted",value:n.textMuted,onChange:i=>o("textMuted",i)})]}),s.jsxs(ir,{title:"Borders & Accent",children:[s.jsx(Nt,{label:"Border subtle",value:n.borderSubtle,onChange:i=>o("borderSubtle",i)}),s.jsx(Nt,{label:"Border default",value:n.borderDefault,onChange:i=>o("borderDefault",i)}),s.jsx(Nt,{label:"Accent",value:n.accentColor,onChange:i=>o("accentColor",i)})]})]}),s.jsxs("div",{children:[s.jsxs(ir,{title:"Chat Bubbles",children:[s.jsx(Nt,{label:"User bubble",value:n.userBubble,onChange:i=>o("userBubble",i)}),s.jsx(Nt,{label:"User text",value:n.userText,onChange:i=>o("userText",i)}),s.jsx(Nt,{label:"Agent bubble",value:n.assistantBubble,onChange:i=>o("assistantBubble",i)}),s.jsx(Nt,{label:"Agent text",value:n.assistantText,onChange:i=>o("assistantText",i)})]}),s.jsxs(ir,{title:"Chat Layout",children:[s.jsx(Nt,{label:"Chat BG",value:n.containerBg,onChange:i=>o("containerBg",i)}),s.jsx(Nt,{label:"Send button",value:n.sendButton,onChange:i=>o("sendButton",i)}),s.jsx(Nt,{label:"Input border",value:n.inputBorder,onChange:i=>o("inputBorder",i)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:i=>o("bubbleRadius",Number(i.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const i=e?Lo:Po,u=Bt(e?"light":"dark");e?un(i,u):un(u,i),a(i),vs(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 u0(){const[e,t]=l.useState(An),[r,n]=l.useState(!0),[a,o]=l.useState(()=>Bt("dark"));l.useEffect(()=>{n(ws());const u=new MutationObserver(()=>{const p=ws();n(p);const h=An();h==="custom"?vs(Bt(p?"dark":"light")):Nr(h,p?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{const p=ws();n(p);const h=An();h==="custom"?vs(Bt(p?"dark":"light")):Nr(h,p?"dark":"light")};return m.addEventListener("change",d),()=>{u.disconnect(),m.removeEventListener("change",d)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?vs(Bt(r?"dark":"light")):(pi(),Nr(e,r?"dark":"light"))},[e,r]),l.useEffect(()=>{o(Bt(r?"dark":"light"))},[r]);const i=u=>{t(u),l0(u)},c=[...o0,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:c.map(u=>{const m=e===u.id,d=r?u.preview.dark:u.preview.light,p=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>i(u.id),className:"text-left rounded-xl p-3 transition-all",style:{background:m?"var(--bg-glass-hover)":"var(--bg-glass)",border:m?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:m?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background: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:p},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:[m&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:u.id==="custom"?"🎨 Custom":u.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:u.description})]})]})]},u.id)})}),e==="custom"&&s.jsx(d0,{dark:r,onColorsChange:u=>o(u)})]})}const hi="adhdev_mobileDashboardMode_v1",Ro="adhdev:mobile-dashboard-mode-change";function fi(){try{return localStorage.getItem(hi)==="workspace"?"workspace":"chat"}catch{return"chat"}}function m0(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??fi())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==hi||t()};return window.addEventListener(Ro,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Ro,r),window.removeEventListener("storage",n)}}function p0(e){try{localStorage.setItem(hi,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ro,{detail:e}))}function h0(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(fi()==="chat")},[]),s.jsx(fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Is,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:r=>{t(r),p0(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const $a=new Map,Hl=new Map;function f0(e){if(!e||typeof e!="object")return null;const t=e,r=t.result&&typeof t.result=="object"?t.result:t,n=r.machine;return!n||typeof n!="object"?null:{machine:n,timestamp:typeof r.timestamp=="number"?r.timestamp:void 0}}function x0(e,t,r,n){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:n,platform:r.platform,machine:r}}function ju(){const{sendCommand:e}=lt(),{injectEntries:t,getIdes:r}=Mr();return l.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??Wx,i=Hl.get(n)||0;if(!(a!=null&&a.force)&&i>0&&Date.now()-i<o)return;const c=$a.get(n);if(c)return c;const u=(async()=>{const m=await e(n,"get_machine_runtime_stats"),d=f0(m);if(!d)return;const p=r().find(b=>b.id===n),h=x0(p,n,d.machine,d.timestamp||Date.now());t([h]),Hl.set(n,Date.now())})().finally(()=>{$a.delete(n)});return $a.set(n,u),u},[r,t,e])}function b0(e,t,r){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:r.timestamp,platform:r.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...r.machine}}}function g0(e,t){const{sendData:r}=lt(),{injectEntries:n,getIdes:a}=Mr(),o=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const i=o?o.split("|"):[];if(i.length===0)return;const c=i.map(u=>qt.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:t==null?void 0:t.intervalMs}},d=>{const p=a().find(b=>b.id===u),h=b0(p,u,d);n([h])}));return()=>{c.forEach(u=>u())}},[o,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function y0(e,t){const{sendData:r}=lt(),[n,a]=l.useState(null),[o,i]=l.useState(!1);return l.useEffect(()=>{if(!e){a(null),i(!1);return}if(!(t!=null&&t.enabled)||!r){i(!1);return}a(null),i(!0);let c=null;const u=qt.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},m=>{c&&(clearTimeout(c),c=null),a(m.diagnostics),i(!1)});return u.initialSendAccepted?c=setTimeout(()=>{i(!1)},Vx):i(!1),()=>{c&&clearTimeout(c),u()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,r]),{diagnostics:n,loading:o,applyDiagnostics:a}}function v0(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function ku(e){const{sendData:t}=lt(),[r,n]=l.useState({});return l.useEffect(()=>{const a=v0(e);if(!a||!e.sessionId||!t){n({});return}const o=qt.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},i=>{n({status:i.status,modalMessage:i.modalMessage,modalButtons:i.modalButtons}),Bs.record({interactionId:i.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:i.status,modalButtonCount:Array.isArray(i.modalButtons)?i.modalButtons.length:0}})});return o.initialSendAccepted||n({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const Nu="adhdev_hiddenTabs",Su="adhdev_autoHiddenMeshTabs";function w0(){try{const e=localStorage.getItem(Nu);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ps(e){try{localStorage.setItem(Nu,JSON.stringify([...e]))}catch{}}function j0(){try{const e=localStorage.getItem(Su);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function Wl(e){try{localStorage.setItem(Su,JSON.stringify([...e]))}catch{}}function xr(e){return Tr(e)}function fa(e,t){return Zt(t).some(r=>e.has(r))}function Cu(e){var t,r,n;return((t=e.settings)==null?void 0:t.launchedByCoordinator)===!0&&typeof((r=e.settings)==null?void 0:r.meshNodeFor)=="string"&&e.settings.meshNodeFor.trim().length>0&&((n=e.settings)==null?void 0:n.spawnedSessionVisibility)==="hidden"}function k0(e,t,r=new Set){return e.filter(n=>{if(!Cu(n))return!1;const a=xr(n);return r.has(a)?!1:!fa(t,n)})}function N0(){const[e,t]=l.useState(w0),[r,n]=l.useState(j0),a=l.useCallback(h=>{const b=xr(h);t(g=>{const f=new Set(g);return f.has(b)?f.delete(b):f.add(b),ps(f),f})},[]),o=l.useCallback(h=>{const b=xr(h);t(g=>{if(g.has(b))return g;const f=new Set(g);return f.add(b),ps(f),f})},[]),i=l.useCallback(h=>{const b=xr(h);t(g=>{if(g.has(b))return g;const f=new Set(g);return f.add(b),ps(f),f}),n(g=>{if(g.has(b))return g;const f=new Set(g);return f.add(b),Wl(f),f})},[]),c=l.useCallback(h=>{const b=xr(h);t(g=>{if(!g.has(b))return g;const f=new Set(g);return f.delete(b),ps(f),f}),n(g=>{if(g.has(b))return g;const f=new Set(g);return f.add(b),Wl(f),f})},[]),u=l.useCallback(()=>{t(h=>{if(h.size===0)return h;const b=new Set;return ps(b),b})},[]),m=l.useCallback((h,b)=>{t(g=>{const f=new Set(g);for(const w of b)f.add(w);return ps(f),f})},[]),d=l.useCallback((h,b)=>{t(g=>{const f=new Set(g);for(const w of b)f.delete(w);return ps(f),f})},[]),p=l.useCallback(h=>fa(e,h),[e]);return{hiddenTabs:e,autoHiddenTabs:r,toggleTarget:a,hideTarget:o,autoHideTarget:i,showTarget:c,showAllTabs:u,hideAllForDaemon:m,showAllForDaemon:d,isHidden:p}}const mn="adhdev_mutedConversations",Ea="adhdev_autoMutedMeshConversations";function Kl(e){try{const t=localStorage.getItem(e);if(t)return new Set(JSON.parse(t))}catch{}return new Set}function lr(e,t){try{localStorage.setItem(e,JSON.stringify([...t]))}catch{}}function S0(e,t){return Zt(t).some(r=>e.has(r))}function C0(){const[e,t]=l.useState(()=>Kl(mn)),[r,n]=l.useState(()=>Kl(Ea)),a=l.useCallback(m=>{const d=Tr(m);t(p=>{if(p.has(d))return p;const h=new Set(p);return h.add(d),lr(mn,h),h})},[]),o=l.useCallback(m=>{const d=Zt(m);t(p=>{let h=!1;const b=new Set(p);for(const g of d)b.delete(g)&&(h=!0);return h?(lr(mn,b),b):p}),n(p=>{let h=!1;const b=new Set(p);for(const g of d)b.delete(g)&&(h=!0);return h?(lr(Ea,b),b):p})},[]),i=l.useCallback(m=>{Zt(m).some(h=>e.has(h))?o(m):a(m)},[e,a,o]),c=l.useCallback(m=>{if(!Cu(m))return;const d=Tr(m);r.has(d)||(n(p=>{if(p.has(d))return p;const h=new Set(p);return h.add(d),lr(Ea,h),h}),t(p=>{if(p.has(d))return p;const h=new Set(p);return h.add(d),lr(mn,h),h}))},[r]),u=l.useCallback(m=>S0(e,m),[e]);return{mutedTargets:e,autoMutedTargets:r,muteTarget:a,unmuteTarget:o,toggleTarget:i,autoMuteIfCoordinator:c,isMuted:u}}function I0(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function M0(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 A0(e,t,r){const n=await r(`/api/v1/sessions/${encodeURIComponent(e)}/interactive-prompt/resolve`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!n.ok){let a=`HTTP ${n.status}`;try{const o=await n.json();typeof(o==null?void 0:o.error)=="string"&&(a=o.error)}catch{}throw new Error(a)}}async function T0({promptSession:e,response:t,useP2PCommand:r,sendCommand:n,fetchImpl:a=fetch}){if(r){const o=await n(e.routeId,"interactive_prompt_response",{targetSessionId:e.sessionId,sessionId:e.sessionId,response:t});if(!I0(o))throw new Error(M0(o));return}await A0(e.sessionId,t,a)}function Iu(e){const{ides:t,isP2PActive:r,p2pStates:n}=Yt(),{sendCommand:a}=lt(),[o,i]=l.useState(null),[c,u]=l.useState(!1),[m,d]=l.useState(null),p=l.useMemo(()=>bf(t,e),[t,e]),h=!!p,b=l.useMemo(()=>p?p.prompt.promptId===o?null:p:null,[o,p]),g=l.useCallback(async j=>{if(!b)return;const y=vd(b.prompt,j);u(!0),d(null);try{const v=(n==null?void 0:n[b.daemonId])==="connected"||r===!0;await T0({promptSession:b,response:y,useP2PCommand:v,sendCommand:a}),i(b.prompt.promptId)}catch(v){throw d(v instanceof Error?v.message:String(v)),v}finally{u(!1)}},[r,n,b,a]),f=l.useCallback(()=>{b&&i(b.prompt.promptId)},[b]),w=l.useCallback(()=>{i(null),d(null)},[]);return{promptSession:b,hasActivePrompt:h,responseError:m,isSubmitting:c,submit:g,cancel:f,reopen:w}}function Mu(e){return e instanceof Error?e.message:String(e||"")}function _0(e){const t=Mu(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 L0(e){const t=Mu(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Au({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!Ze(e)||Ye(e))return;const o=qs(e);if(o===t)return;const i=e.sessionId;i&&a(c=>({...c,[i]:t}));try{await n(Ms(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Vt(e),mode:t})}catch(c){const u=L0(c);i&&!u&&a(m=>{const d={...m};return o===Tu(r,i)?delete d[i]:d[i]=o,d}),_0(c)?console.warn(u?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",c instanceof Error?c.message:String(c)):console.error("Failed to switch CLI view mode:",c)}}function Ul(e,t){const r=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!r||e.transport!=="pty")return e;const n=t[r];return!n||e.mode===n?e:{...e,mode:n}}function P0(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let r=!1;const n=e.map(a=>{const o=Ul(a,t),i=Array.isArray(a.childSessions)?a.childSessions.map(u=>Ul(u,t)):a.childSessions,c=i!==a.childSessions;return o!==a||c?(r=!0,{...o,...c?{childSessions:i}:{}}):a});return r?n:e}function Tu(e,t){if(!t)return null;for(const r of e){if(r.sessionId===t&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function R0(e,t){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,o]of Object.entries(e))Tu(t,a)===o&&(delete n[a],r=!0);return r?n:e}function D0({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){l.useEffect(()=>{Ad()},[]);const a=l.useMemo(()=>e.map(o=>({id:o.tabKey,name:tu(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return Vf(a),l.useEffect(()=>{if(Object.keys(t).length===0)return;const i=setTimeout(()=>{r(c=>{const u=Date.now(),m={};for(const[d,p]of Object.entries(c))u-p<5e3&&(m[d]=p);return Object.keys(m).length===Object.keys(c).length?c:m})},5500);return()=>clearTimeout(i)},[t,r]),l.useEffect(()=>{const o=setInterval(()=>{const i=Date.now()-3e5;n(c=>{const u=c.filter(m=>m.timestamp>i).slice(-100);return u.length===c.length?c:u})},6e4);return()=>clearInterval(o)},[n]),null}function Gl(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 js(e){const t=[...e.messages].reverse().find(a=>!(a!=null&&a._localId))||e.messages[e.messages.length-1],r=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,n=Gl(t==null?void 0:t.receivedAt)||Gl(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function Do(e,t=0){return js(e)||e.lastUpdated||t||0}function _u(e){return js(e)||e.lastUpdated||0}function Lu(e,t,r=_u){const n=r(t)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const o=e.displayPrimary.localeCompare(t.displayPrimary);if(o!==0)return o;const i=e.displaySecondary.localeCompare(t.displaySecondary);return i!==0?i:e.tabKey.localeCompare(t.tabKey)}function $o(e){var r;const t=Lt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function $0(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!$o(e)&&!e.title.trim()}function E0(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number($o(r))-Number($o(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:Lu(t,r)})[0]||null}function Ft(e,t){const r=e.filter(i=>i.routeId===t);if(r.length===0)return null;const n=r.find(i=>i.streamSource==="native")||null,a=r.filter(i=>i.streamSource==="agent-stream"),o=E0(a);return n?o&&$0(n)?o:n:o||r[0]||null}function B0(e){const t=String(e.daemonId||"").trim(),r=String(e.id||"").trim();return!t||r.startsWith(`${t}:`)?r:`${t}:${r}`}function F0(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=B0(n),o=r.get(a);if(!o){r.set(a,n);continue}const i=(o.workspace?1:0)+(o.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(o.timestamp||0))&&r.set(a,n)}return Array.from(r.values())}function Ba(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function O0(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function Vl(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?O0(Fs(r.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((r==null?void 0:r.id)||""),String((r==null?void 0:r.index)??""),String((r==null?void 0:r.receivedAt)??(r==null?void 0:r.timestamp)??""),n].join(":")}function z0(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||""),Vl(e.activeChat),...t.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastMessageAt||""),r.lastMessagePreview||"",r.lastMessageRole||"",String(r.lastUpdated||""),Vl(r.activeChat)].join(":"))].join("|")}function H0(e,t){const r=Date.now();return e.map(n=>{const a=t[n.tabKey];return a&&r-a<5e3?{...n,messages:[],title:""}:n})}function W0(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const o of Zt({routeId:n.routeId}))r.set(o,a);for(const o of Zt({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of Zt({tabKey:n.tabKey}))r.set(o,n)}return r}function K0(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function U0(e){const t=K0(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const r=String(t.role||""),n=Fs(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function G0({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=l.useMemo(()=>F0(e),[e]),o=l.useMemo(()=>uu(e),[e]),i=l.useRef([]),c=l.useRef([]),u=l.useRef([]),m=l.useRef(new Map),d=l.useRef(new Map),p=l.useMemo(()=>{const N=new Map,k=[];for(const M of a){const{connectionState:D="new",machineName:P}=mu(M,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),T=z0(M),R=m.current.get(M.id);if(R&&R.ide===M&&R.sourceSignature===T&&R.connectionState===D&&R.machineName===P){N.set(M.id,R),k.push(...R.conversations);continue}const O=ui(M,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),K={ide:M,sourceSignature:T,connectionState:D,machineName:P,conversations:O};N.set(M.id,K),k.push(...O)}m.current=N;const x=new Map,I=M=>{const D=U0(M),P=d.current.get(M.tabKey);if(P&&P.signature===D)return x.set(M.tabKey,P),P.timestamp;const T={signature:D,timestamp:_u(M)||(P==null?void 0:P.timestamp)||0};return x.set(M.tabKey,T),T.timestamp},C=[...k].sort((M,D)=>Lu(M,D,I));return d.current=x,C},[a,t,o]),h=l.useMemo(()=>{const N=H0(p,r);return Ba(i.current,N)?i.current:(i.current=N,N)},[p,r]),b=l.useMemo(()=>{const N=new Map,k=Array.from(new Set(h.map(x=>x.routeId)));for(const x of k){const I=Ft(h,x);I&&N.set(x,I)}return N},[h]),g=l.useMemo(()=>{const N=new Map;for(const k of h){const x=b.get(k.routeId),I=k.streamSource==="native"&&x?x:k;for(const C of Zt({providerSessionId:k.providerSessionId,sessionId:k.sessionId,tabKey:k.tabKey}))N.set(C,I)}return N},[h,b]),f=l.useMemo(()=>W0(h,b),[h,b]),w=l.useCallback(N=>{if(N)return g.get(N)},[g]),j=l.useCallback(N=>{if(N)return f.get(N)},[f]),y=l.useMemo(()=>{const N=h.filter(k=>!fa(n,k));return Ba(c.current,N)?c.current:(c.current=N,N)},[h,n]),v=l.useMemo(()=>{const N=y.map(k=>k.tabKey);return Ba(u.current,N)?u.current:(u.current=N,N)},[y]);return{chatIdes:a,conversations:h,visibleConversations:y,visibleTabKeys:v,resolveConversationBySessionId:w,resolveConversationByTarget:j}}function V0({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=l.useMemo(()=>{var c;return e||!t?null:((c=r(t))==null?void 0:c.tabKey)??null},[e,r,t]),o=l.useMemo(()=>{var c;return!e||!t?null:((c=r(t))==null?void 0:c.tabKey)??null},[e,r,t]),i=l.useCallback(()=>{t&&n(c=>{const u=new URLSearchParams(c);return u.delete("activeTab"),u},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function q0({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){l.useEffect(()=>{tt.setIdes(e)},[e]),l.useEffect(()=>{tt.setResolveAction((a,o,i)=>{t(a,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const a=tt.onToast(o=>{r(c=>c.some(m=>m.message===o.message&&o.timestamp-m.timestamp<3e3)?c:[...c.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const i=o.duration||5e3;setTimeout(()=>r(c=>c.filter(u=>u.id!==o.id)),i)});return()=>{a()}},[r]),l.useEffect(()=>{const a=Qd.on("status_event",o=>{tt.handleRawEvent(o,"ws")});return()=>{a()}},[]),l.useEffect(()=>{var o;const a=i=>{var f;const c=i.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const u=c.targetSessionId||c.targetKey||c.daemonId,m=n(u),d=(m==null?void 0:m.routeId)||c.daemonId;if(!d)return;const p=Number(c.buttonIndex),h=c.button||((f=m==null?void 0:m.modalButtons)==null?void 0:f[p])||"Approve",b=String(h).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),g=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(b);t(d,"resolve_action",{action:g?"approve":"reject",button:h,...Number.isFinite(p)&&{buttonIndex:p},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(w=>console.error("[SW Action] approval failed:",w))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",a)}},[n,t])}const Y0="adhdev_dashboardLayout_v1",J0="adhdev_dashboardDockview_v1",X0="adhdev_dashboardDockviewHiddenRestore_v1",cr={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function xi(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Q0(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Pu(e){return`${Y0}:${e}`}function Z0(e){const t=Pu(e);return xi(t,null)}function ey(e,t){try{const r=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,n=Pu(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Ru(e){return`${J0}:${e}`}function ty(e){const t=Ru(e);return xi(t,null)}function sy(e,t){try{const r=Ru(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Du(e){return`${X0}:${e}`}function ry(e){const t=Du(e);return xi(t,{})}function ny(e,t){try{const r=Du(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function ay(){return{groupAssignments:[...cr.groupAssignments],focusedGroup:cr.focusedGroup,groupActiveTabIds:{...cr.groupActiveTabIds},groupTabOrders:{...cr.groupTabOrders},groupSizes:[...cr.groupSizes]}}function oy(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function iy(){const[e]=l.useState(()=>Q0(typeof window<"u"?window.innerWidth:1280)),[t,r]=l.useState(()=>new Map),[n,a]=l.useState(0),[o,i]=l.useState({}),[c,u]=l.useState({}),[m,d]=l.useState([]),[p,h]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[b,g]=l.useState(!1),f=l.useCallback(()=>{if(b)return;const M=Z0(e)??ay();r(new Map(M.groupAssignments)),a(M.focusedGroup),i(M.groupActiveTabIds),u(M.groupTabOrders),d(M.groupSizes),g(!0)},[b,e]);l.useEffect(()=>{b&&ey(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:c,groupSizes:m})},[b,e,t,n,o,c,m]),l.useEffect(()=>{const M=window.matchMedia("(max-width: 767px)"),D=P=>h(P.matches);return M.addEventListener("change",D),()=>M.removeEventListener("change",D)},[]);const w=l.useCallback(M=>{r(M)},[]),j=l.useCallback(M=>{a(M)},[]),y=l.useCallback(M=>{i(M)},[]),v=l.useCallback(M=>{u(M)},[]),N=l.useCallback(M=>{d(M)},[]),k=l.useCallback(M=>{j(M)},[j]),x=l.useCallback((M,D)=>{i(P=>(P[M]??null)===(D??null)?P:{...P,[M]:D})},[]),I=l.useCallback((M,D)=>{u(P=>{const T=P[M];return oy(T,D)?P:{...P,[M]:D}})},[]),C=l.useCallback((M,D)=>{const P=D.get(M)??0;return x(P,M),k(P),P},[k,x]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:w,focusedGroup:n,updateFocusedGroup:j,focusGroup:k,groupActiveTabIds:o,updateGroupActiveTabIds:y,setGroupActiveTab:x,groupTabOrders:c,updateGroupTabOrders:v,setGroupTabOrder:I,groupSizes:m,updateGroupSizes:N,isMobile:p,hasHydratedStoredLayout:b,hydrateStoredLayout:f,focusConversationTab:C}}function ly(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=pa(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function cy({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:u,activeConv:m,isRefreshingHistory:d,ides:p,handleRefreshHistory:h}){const b=l.useRef(!1),g=l.useRef(!1),f=l.useRef(null),w=l.useRef(!1);l.useEffect(()=>{if(!e||b.current||t.length===0)return;if(!a){o();return}const j=r(e);j&&(i(j.tabKey,n),b.current=!0,g.current=!0,f.current!=null&&(window.clearTimeout(f.current),f.current=null),c(y=>{const v=new URLSearchParams(y);return v.delete("activeTab"),v},{replace:!0}))},[e,t,r,n,a,o,i,c]),l.useEffect(()=>{if(!(g.current||a)&&t.length!==0){if(!e){o(),g.current=!0;return}if(b.current){g.current=!0;return}if(f.current==null)return f.current=window.setTimeout(()=>{f.current=null,!(g.current||a)&&(o(),g.current=!0)},1500),()=>{f.current!=null&&(window.clearTimeout(f.current),f.current=null)}}},[e,t.length,a,o]),l.useEffect(()=>{if(!u){w.current=!1;return}if(!m||w.current||d)return;const j=p.find(y=>y.id===m.routeId);j&&(!j.chats||j.chats.length===0||ly(j.chats,m))&&(w.current=!0,h())},[u,m,d,p,h])}function Fa(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=pa(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function $u({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[i,c]=l.useState(!1),[u,m]=l.useState(!1),d=l.useCallback(async g=>{try{await e("standalone","launch_ide",{ideType:g,enableCdp:!0})}catch(f){console.error("Launch failed",f)}},[e]),p=l.useCallback(async(g,f)=>{try{const w=g||(t==null?void 0:t.daemonId)||"",j=await e(w,"switch_chat",{id:f,sessionId:f,...bs(t)}),y=j==null?void 0:j.result;if((j==null?void 0:j.success)===!0||y==="switched"||y==="switched-by-title")return;y===!1||y==="not_found"?nr(a,"⚠️ Session tab not found — try refreshing history"):typeof y=="string"&&y.startsWith("error:")?nr(a,`⚠️ Switch error: ${y}`):nr(a,"⚠️ Session switch failed")}catch(w){console.error("Switch failed",w),nr(a,`❌ Switch failed: ${w.message||"connection error"}`)}},[t,e,a]),h=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const g=gs(t);await e(g,"new_chat",{...bs(t)}),mb(g,t.sessionId,pa(t)[0]),o(f=>({...f,[t.tabKey]:Date.now()}))}catch(g){console.error("New chat failed",g)}finally{c(!1)}}},[t,i,e,o]),b=l.useCallback(async()=>{var g,f;if(!(!t||u)){m(!0);try{const w=gs(t),j=async()=>e(w,"list_chats",{forceExpand:!0,...bs(t)});let y=await j(),v=(y==null?void 0:y.chats)||((g=y==null?void 0:y.result)==null?void 0:g.chats);Fa(v,t)&&(await new Promise(N=>setTimeout(N,450)),y=await j(),v=(y==null?void 0:y.chats)||((f=y==null?void 0:y.result)==null?void 0:f.chats)),y!=null&&y.success&&Array.isArray(v)&&(n(t.routeId,v),Fa(v,t)&&!Fa(r,t)&&nr(a,"⚠️ History dialog did not fully open — try once more"))}catch(w){console.error("Refresh history failed",w)}finally{m(!1)}}},[t,r,u,e,n,a]);return{isCreatingChat:i,isRefreshingHistory:u,handleLaunchIde:d,handleSwitchSession:p,handleNewChat:h,handleRefreshHistory:b}}function dy(e,t){if(e.size!==t.size)return!1;for(const[r,n]of e)if(t.get(r)!==n)return!1;return!0}function uy(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function ql(e,t){const r=Object.keys(e),n=Object.keys(t);return r.length!==n.length?!1:r.every(a=>t[Number(a)]===e[Number(a)])}function pn(e,t){const r=new Set(t),n=t.length>0?[0]:[];for(const[i,c]of e)!r.has(i)||c<=0||n.includes(c)||n.push(c);n.sort((i,c)=>i-c);const a={};n.forEach((i,c)=>{a[i]=c}),n.length===0&&(a[0]=0);const o=new Map;for(const[i,c]of e){if(!r.has(i)||c<=0)continue;const u=a[c];typeof u=="number"&&u>0&&o.set(i,u)}return{assignments:o,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function Yl(e,t){const r={};for(const[n,a]of Object.entries(e)){const o=t[Number(n)];typeof o=="number"&&(r[o]=a)}return r}function my(e,t,r){if(t.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...t].reverse().find(a=>a<e)??t[0];return r[n]??0}function py(e,t,r){if(t.length<=1)return[];const n=t.map(i=>e[i]).filter(i=>Number.isFinite(i)),a=n.length===t.length?n:Array(r).fill(100/r),o=a.reduce((i,c)=>i+c,0);return o>0?a.map(i=>i/o*100):Array(r).fill(100/r)}function Jl(e,t){const r={};for(const[n,a]of Object.entries(e)){const o=Number(n);r[o>=t?o+1:o]=a}return r}function Xl(e){return Array(e).fill(100/e)}function hy({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:u,visibleTabKeys:m}){const d=l.useRef(null),p=l.useMemo(()=>pn(e,m),[e,m]),h=p.assignments,b=l.useMemo(()=>c?1:p.groupCount,[p.groupCount,c]),g=b>1,f=l.useCallback((k,x)=>{t(I=>{const C=new Map(pn(I,m).assignments);return x===0?C.delete(k):C.set(k,x),C}),n(I=>({...I,[x]:k})),r(x)},[t,m,n,r]),w=l.useCallback(k=>{t(x=>{const I=pn(x,m).assignments,C=new Map;for(const[M,D]of I)D!==k&&(D>k?C.set(M,D-1):C.set(M,D));return C}),i(x=>{if(x.length<=1)return[];const I=[...x];I.splice(k,1);const C=I.reduce((M,D)=>M+D,0);return C>0?I.map(M=>M/C*100):[]}),r(0)},[t,m,i,r]),j=l.useCallback((k,x)=>{x.preventDefault();const I=d.current;if(!I)return;const C=x.clientX,M=I.offsetWidth,D=o.length===b?[...o]:Xl(b),P=R=>{const K=(R.clientX-C)/M*100,S=[...D];S[k]=Math.max(15,D[k]+K),S[k+1]=Math.max(15,D[k+1]-K),i(S)},T=()=>{document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",T),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",P),document.addEventListener("mouseup",T)},[o,b,i]),y=l.useCallback((k,x,I)=>{if(b>=4)return;const C=I==="left"?x:x+1;t(M=>{const D=pn(M,m).assignments,P=new Map;for(const T of u){const R=D.get(T.tabKey)??0,O=R>=C?R+1:R;O>0&&P.set(T.tabKey,O)}return C>0&&P.set(k,C),P}),i(M=>{const D=M.length===b?[...M]:Xl(b),P=D[x]??100/b,T=Math.max(15,P/2),R=Math.max(15,P/2),O=[...D];O[x]=T,O.splice(C,0,R);const K=O.reduce((S,A)=>S+A,0);return O.map(S=>S/K*100)}),n(M=>{const D=Jl(M,C);return D[C]=k,D}),a(M=>{const D=Jl(M,C);return D[C]=[k],D}),r(C)},[b,t,m,u,i,n,a,r]);l.useEffect(()=>{dy(e,h)||t(h)},[e,h,t]),l.useEffect(()=>{const{mapping:k,usedGroups:x}=p;n(I=>{const C=Yl(I,k);return ql(I,C)?I:C}),a(I=>{const C=Yl(I,k);return ql(I,C)?I:C}),r(I=>{const C=c?0:my(I,x,k);return I===C?I:C}),i(I=>{const C=c?[]:py(I,x,p.groupCount);return uy(I,C)?I:C})},[p,c,n,a,r,i]);const v=l.useMemo(()=>{const k=Array.from({length:b},()=>[]);for(const x of u){const I=h.get(x.tabKey)??0,C=Math.min(I,b-1);k[C].push(x)}return k},[u,h,b]),N=l.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:d,normalizedGroupAssignments:h,numGroups:b,isSplitMode:g,groupedConvs:v,moveTabToGroup:f,closeGroup:w,handleResizeStart:j,splitTabRelative:y,clearAllSplits:N}}function Oa(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="stable"||t==="latest"?"stable":t==="preview"||t==="next"?"preview":null}function fy(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="latest"||t==="stable"?"latest":t==="next"||t==="preview"?"next":null}function hn(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function bi(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=Oa(t.channel)||Oa(e.updateChannel)||Oa(e.releaseChannel)||void 0,n=fy(t.npmTag)||(r==="preview"?"next":r==="stable"?"latest":void 0),a=hn(t.targetVersion)||hn(e.serverVersion)||void 0,o=hn(t.minVersion)||void 0,i=hn(t.updateCommand)||(r?`adhdev update --channel ${r}`:void 0);return{...r?{channel:r}:{},...n?{npmTag:n}:{},...a?{targetVersion:a}:{},...o?{minVersion:o}:{},...i?{updateCommand:i}:{}}}function Rs(e,t=null){return bi(e).targetVersion||t}function Eu(e){return bi(e).channel||null}function Bu(e){const t=bi(e);return{...t.channel?{channel:t.channel}:{},...t.npmTag?{npmTag:t.npmTag}:{},...t.targetVersion?{targetVersion:t.targetVersion}:{},...Object.keys(t).length>0?{updatePolicy:t}:{}}}function xy({ides:e,sendDaemonCommand:t}){const r="0.9.82",n=l.useMemo(()=>e.filter(p=>p.type!=="adhdev-daemon"?!1:mi(p,Rs(p,r))).sort((p,h)=>Number(kr(h,Rs(h,r)))-Number(kr(p,Rs(p,r)))),[r,e]),a=l.useMemo(()=>n.some(p=>kr(p,Rs(p,r))),[r,n]),o=l.useMemo(()=>n.map(p=>Rs(p,r)).find(p=>typeof p=="string"&&p.trim().length>0)||r,[r,n]),[i,c]=l.useState(!1),[u,m]=l.useState({}),d=l.useCallback(async p=>{var b,g;const h=e.find(f=>f.id===p);if(h){m(f=>({...f,[p]:"upgrading"}));try{const f=await t(p,"daemon_upgrade",Bu(h));(b=f==null?void 0:f.result)!=null&&b.upgraded||(g=f==null?void 0:f.result)!=null&&g.success?m(w=>({...w,[p]:"done"})):m(w=>({...w,[p]:"error"}))}catch{m(f=>({...f,[p]:"error"}))}}},[e,t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:u,handleBannerUpgrade:d}}const Fu=80;function Tn(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function by(e){return{...e,createdAt:Tn(e.createdAt),updatedAt:Tn(e.updatedAt,e.createdAt),lastEventAt:Tn(e.lastEventAt,e.updatedAt||e.createdAt)}}function gy(e){const t=Tr(e);return t==="unknown:"?e.id:t}function yy(e){return[e.type,Ud(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function vy(e,t=Fu){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=gy(n),o=r.get(a);if(!o){r.set(a,n);continue}(n.updatedAt>o.updatedAt||n.updatedAt===o.updatedAt&&n.createdAt>o.createdAt)&&r.set(a,n)}return Array.from(r.values()).sort((n,a)=>{const o=a.updatedAt-n.updatedAt;return o!==0?o:a.createdAt-n.createdAt}).slice(0,Math.max(0,t))}function wy(e,t){const r=Date.now(),n=[];for(const a of e){const o=a.sessionId?t.get(a.sessionId):void 0;if(o!=null&&o.surfaceHidden)continue;const i=da(a,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const u=Tn(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),m=yy({type:c,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(o==null?void 0:o.lastUpdated)||a.lastUpdated});n.push(by({id:m,dedupKey:m,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Dd(a),preview:kx(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return vy(n)}function jy(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function ky(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=Fu}=e,a=l.useMemo(()=>wy(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=l.useMemo(()=>jy(a),[a]);return{notifications:a,unreadCount:o}}function Ny({notifications:e,sendDaemonCommand:t}){const r=l.useCallback(o=>{const i=e.find(u=>u.id===o),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),n=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),a=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}const Sy=l.createContext(null);function Ou(){return l.useContext(Sy)}function gi(...e){const t=new Set,r=[],n=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const i=o.toLowerCase();t.has(i)||(t.add(i),r.push(o))};for(const a of e){if(Array.isArray(a)){for(const o of a)n(o);continue}n(a)}return r}function Cy(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const r=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function yi(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=Cy(r);if(n)return n}return"C:\\"}for(const r of t){const n=typeof r=="string"?r.trim():"";if(n)return n}return"~"}function Iy(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const r=t.includes("\\")?"\\":"/",n=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(n[0]||"")?n.length<=2?`${n[0]}\\`:n.slice(0,-1).join("\\"):n.length<=2?r:n.slice(0,-1).join(r)||r}function My(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function vi(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=My(n);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(n==null?void 0:n.error)||"Could not browse folder");const o=typeof(a==null?void 0:a.path)=="string"?a.path:r,i=o.includes("\\")?"\\":"/",c=(m,d)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${d}`:m==="/"||m==="\\"?`${i}${d}`:`${m.replace(/[\\/]+$/,"")}${i}${d}`,u=Array.isArray(a==null?void 0:a.files)?a.files.filter(m=>(m==null?void 0:m.type)==="directory"&&typeof(m==null?void 0:m.name)=="string").map(m=>({name:m.name,path:typeof(m==null?void 0:m.path)=="string"&&m.path.trim()?m.path:c(o,m.name)})).sort((m,d)=>m.name.localeCompare(d.name)):[];return{path:o,directories:u}}function Ay(e,t){const r=t.meshId||"",n={meshId:r,workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp",adhdevMcpArgs:t.adhdevMcpArgs||`mcp --mode ipc --repo-mesh ${r}`};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand|adhdevMcpArgs)\s*\}\}/g,(a,o)=>n[o]||"")}function zu(e,t={}){const r=e==null?void 0:e.mcpConfig;return(r==null?void 0:r.mode)!=="manual"?null:{serverName:r.serverName||"adhdev-mesh",configFormat:r.format,configPathCommand:r.configPathCommand,requiresRestart:r.requiresRestart===!0,instructions:r.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:Ay(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function Ty(e){if(!e||typeof e!="object")return null;const t=e,r=typeof t.instructions=="string"?t.instructions:"",n=typeof t.template=="string"?t.template:"";return!r&&!n?null:{serverName:typeof t.serverName=="string"?t.serverName:void 0,configFormat:typeof t.configFormat=="string"?t.configFormat:void 0,configPathCommand:typeof t.configPathCommand=="string"?t.configPathCommand:void 0,requiresRestart:t.requiresRestart===!0,instructions:r||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:n}}function Pr(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Hu(e){return zr(e)||e.tabKey||e.routeId||null}function Wu(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",a=e.conversations.find(o=>{if(n&&o.routeId!==n)return!1;const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(t&&i.includes(t)||r&&i.includes(r)||n&&o.routeId===n)});if(a!=null&&a.tabKey)return a.tabKey;if(n){const o=Ft(e.conversations,n)||e.conversations.find(i=>i.routeId===n);if(o!=null&&o.tabKey)return o.tabKey}return t||r||n||null}function rs(e){return String(e||"").trim()}function Ku(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ea(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function _y(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Ly(e,t){const r=rs(e.providerSessionId),n=rs(e.targetSessionId),a=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(rs).filter(Boolean);return!!(r&&i.includes(r)||n&&i.includes(n))});return a?a.tabKey:n||r||null}function Py(e,t,r){if(t.event!=="agent:generating_completed")return null;const n=Ku(t.daemonId);if(n&&n!==e.machineId)return null;const a=rs(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=rs(e.resumeSessionId),i=rs(e.launchedSessionId),c=rs(t.providerSessionId),u=rs(t.targetSessionId);if(o&&o!==c&&o!==u||i&&i!==c&&i!==u)return null;const m=ea(e.workspacePath);if(m){const d=ea(t.workspaceName);if(d&&!_y(d,m))return null}return Ly(t,r)}function Ql(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Ry({ides:e,conversations:t,onOpenSession:r}){const[n,a]=l.useState(null),o=l.useRef(null),i=l.useCallback(()=>{o.current=null,a(null)},[]),c=l.useCallback(u=>{o.current=u,a(u)},[]);return l.useEffect(()=>{if(!n)return;const u=ea(n.workspacePath),m=e.find(p=>{var w,j,y,v;if(!p||p.type==="adhdev-daemon"||Ku(p.daemonId||p.id)!==n.machineId||(Ar(p)?"cli":$s(p)?"acp":"ide")!==n.kind)return!1;const g=String(p.agentType||p.type||"");if(n.providerType&&g!==n.providerType)return!1;if(n.resumeSessionId)return String(p.providerSessionId||"")===n.resumeSessionId;if(n.launchedSessionId){const N=String(n.launchedSessionId||"");return[p.providerSessionId,p.sessionId,p.instanceId,p.id].map(x=>String(x||"")).filter(Boolean).includes(N)}if(u){const N=ea(p.workspace||p.runtimeWorkspaceLabel);return N?N===u:!1}return Number(p.lastUpdated||p._lastUpdate||p.timestamp||((v=(y=(j=(w=p.activeChat)==null?void 0:w.messages)==null?void 0:j.at)==null?void 0:y.call(j,-1))==null?void 0:v.timestamp)||0)>=n.startedAt-5e3});if(!m)return;const d=Wu({entrySessionId:m.sessionId,entryInstanceId:m.instanceId,entryRouteId:m.id,conversations:t});d&&(i(),r(d))},[i,t,e,r,n]),l.useEffect(()=>tt.onStatusEvent(u=>{const m=o.current;if(!m)return;const d=Py(m,u,t);d&&(i(),r(d))}),[i,t,r]),l.useEffect(()=>{if(!n)return;const u=window.setTimeout(()=>{a(m=>!m||m.startedAt!==n.startedAt?m:(o.current=null,null))},45e3);return()=>window.clearTimeout(u)},[n]),{trackPendingLaunch:c}}function Dy({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const i=Ou(),{launchCli:c}=oa(),u=l.useCallback(async(w,j)=>vi(e,w,j),[e]),m=l.useCallback(async(w,j)=>{if(!j.trim())return{ok:!1,error:"Choose a workspace path first."};try{const y=await e(w,"workspace_add",{path:j.trim()});return y!=null&&y.success?{ok:!0}:{ok:!1,error:(y==null?void 0:y.error)||"Could not save workspace"}}catch(y){return{ok:!1,error:y instanceof Error?y.message:"Could not save workspace"}}},[e]),d=l.useCallback(async(w,j,y)=>{var v;try{const N={ideType:j,enableCdp:!0};(v=y==null?void 0:y.workspacePath)!=null&&v.trim()&&(N.workspace=y.workspacePath.trim());const k=await e(w,"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:w,kind:"ide",providerType:j,workspacePath:(y==null?void 0:y.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(N){return{ok:!1,error:N instanceof Error?N.message:"Could not launch IDE"}}},[e,t]),p=l.useCallback(async(w,j,y,v)=>{var k,x,I;const N=Date.now();try{const C={cliType:y};(k=v==null?void 0:v.workspacePath)!=null&&k.trim()?C.dir=v.workspacePath.trim():v!=null&&v.workspaceId&&(C.workspaceId=v.workspaceId),(x=v==null?void 0:v.resumeSessionId)!=null&&x.trim()&&(C.resumeSessionId=v.resumeSessionId.trim()),Array.isArray(v==null?void 0:v.cliArgs)&&v.cliArgs.length>0&&(C.cliArgs=v.cliArgs),(I=v==null?void 0:v.initialModel)!=null&&I.trim()&&(C.initialModel=v.initialModel.trim());const M=await c(w,C),D=(M==null?void 0:M.result)||M,P=(D==null?void 0:D.sessionId)||(D==null?void 0:D.id);return M!=null&&M.success&&P?(t({machineId:w,kind:j,providerType:y,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,launchedSessionId:P,startedAt:N}),{ok:!0}):M!=null&&M.success?(t({machineId:w,kind:j,providerType:y,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,startedAt:N}),{ok:!0}):{ok:!1,error:(M==null?void 0:M.error)||(D==null?void 0:D.error)||`Could not launch ${j.toUpperCase()} session`}}catch(C){return Ql(C)?(t({machineId:w,kind:j,providerType:y,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,startedAt:N}),{ok:!0}):{ok:!1,error:C instanceof Error?C.message:`Could not launch ${j.toUpperCase()} session`}}},[c,e,t]),h=l.useCallback(async w=>{var j;if(i!=null&&i.listMeshes)return i.listMeshes(w);if(!w)return[];try{const y=await e(w,"list_meshes",{}),v=(y==null?void 0:y.result)??y;if((v==null?void 0:v.success)===!1)throw new Error((v==null?void 0:v.error)||"Could not load meshes");return(Array.isArray(v==null?void 0:v.meshes)?v.meshes:Array.isArray((j=v==null?void 0:v.result)==null?void 0:j.meshes)?v.result.meshes:[]).map(k=>{var x;return{id:String((k==null?void 0:k.id)||""),name:String((k==null?void 0:k.name)||(k==null?void 0:k.id)||"Untitled mesh"),repoIdentity:(k==null?void 0:k.repoIdentity)||(k==null?void 0:k.repo_identity)||null,workspace:Array.isArray(k==null?void 0:k.nodes)&&k.nodes.length>0?String(((x=k.nodes[0])==null?void 0:x.workspace)||""):null,nodesCount:Array.isArray(k==null?void 0:k.nodes)?k.nodes.length:void 0,status:(k==null?void 0:k.status)||null}}).filter(k=>k.id)}catch(y){throw console.error("List meshes failed",y),y}},[i,e]),b=l.useCallback(async(w,j,y)=>{if(!j.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(w,j,y);const v=Date.now();try{const N={meshId:j.trim()};y.trim()&&(N.cliType=y.trim());const k=await e(w,"launch_mesh_coordinator",N),x=(k==null?void 0:k.result)??k;if((x==null?void 0:x.success)===!1||(k==null?void 0:k.success)===!1){const C=String((x==null?void 0:x.code)||(k==null?void 0:k.code)||""),M=Ty((x==null?void 0:x.meshCoordinatorSetup)||(x==null?void 0:x.manualSetup)||(k==null?void 0:k.meshCoordinatorSetup)||(k==null?void 0:k.manualSetup));return{ok:!1,error:(x==null?void 0:x.error)||(k==null?void 0:k.error)||"Could not launch mesh coordinator",code:C||void 0,manualSetup:M}}const I=(x==null?void 0:x.sessionId)||(x==null?void 0:x.id);return I?r(I):t({machineId:w,kind:"cli",providerType:(x==null?void 0:x.cliType)||y.trim()||void 0,workspacePath:(x==null?void 0:x.workspace)||null,startedAt:v}),{ok:!0}}catch(N){return Ql(N)?(t({machineId:w,kind:"cli",providerType:y.trim()||void 0,startedAt:v}),{ok:!0}):{ok:!1,error:N instanceof Error?N.message:"Could not launch mesh coordinator"}}},[i,r,e,t]),g=l.useCallback(async(w,j)=>{if(!w||!j)return[];try{const y=await e(w,"list_saved_sessions",{providerType:j,kind:"cli",limit:30}),v=(y==null?void 0:y.result)??y;return Array.isArray(v==null?void 0:v.sessions)?v.sessions:[]}catch(y){return console.error("List saved sessions failed",y),[]}},[e]),f=l.useCallback(async w=>{await Au({conversation:n,mode:w,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:u,handleSaveMachineWorkspace:m,handleLaunchMachineIde:d,handleLaunchMachineProvider:p,handleListMachineMeshes:h,handleLaunchMeshCoordinator:b,handleListMachineSavedSessions:g,setActiveCliViewMode:f}}function $y(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 Ey(e,t,r=Date.now()){return!e||!$y(t)?null:{tabKey:e,nonce:r}}function By({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:i}){const[c,u]=l.useState(null),[m,d]=l.useState(null),p=l.useMemo(()=>{var w,j;if(!e){if(c){const y=t.find(v=>v.tabKey===c);if(y)return y}return r[0]}const f=n[a];if(f){const y=t.find(v=>v.tabKey===f);if(y)return y}return((w=o[a])==null?void 0:w[0])||((j=o[0])==null?void 0:j[0])},[t,c,a,n,o,e,r]),h=l.useCallback(f=>{u(f)},[]),b=l.useCallback(f=>{u(f.tabKey),i(w=>{const j=new URLSearchParams(w),y=Sx(f);return y?j.set("activeTab",y):j.delete("activeTab"),j},{replace:!0})},[i]),g=l.useCallback((f,w)=>{const j=Ey(f,w);j&&d(j)},[]);return{activeConv:p,openDesktopConversation:b,requestScrollToBottom:g,scrollToBottomRequest:m,setDesktopActiveTab:h}}function Fy(e){const t=e.completedKey||null,r=e.pendingKey||null;return e.shouldMarkSeen?t===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:r===e.autoReadKey?r:null}:r===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:r}:{shouldSchedule:!0,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!r,nextPendingKey:null}}function Oy(e){const t=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",t,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&(!t||t!==r)),autoReadKey:o,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function zy({activeConv:e,isMobile:t,liveSessionInboxState:r,sendDaemonCommand:n}){const a=l.useRef(null),o=l.useRef(null),i=l.useRef(null),c=l.useRef(null),u=l.useRef(null);l.useEffect(()=>{const m=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null),o.current=null};if(t){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const d=zn(e,r),p=Oy({tabKey:e.tabKey,historySessionId:zr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:js(e),liveState:d}),h=p.autoReadKey,b=Fy({autoReadKey:h,shouldMarkSeen:p.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!p.shouldMarkSeen){b.shouldCancelPending&&m(),a.current=h;return}if(!b.shouldSchedule)return;b.shouldCancelPending&&m();const g=()=>{if(document.visibilityState!=="visible"||a.current===h)return;a.current=h,o.current=null,i.current=null,c.current=null,u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null);const w=p.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:w,completionMarker:p.completionMarker}).catch(()=>{})};if(o.current=b.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(g,1500);const w=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};u.current=w,document.addEventListener("visibilitychange",w);return}const f=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(g,800),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null))};u.current=f,document.addEventListener("visibilitychange",f)},[e,t,r,n]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),u.current&&document.removeEventListener("visibilitychange",u.current)},[])}function za(e){if(!e)return"";const t=String(e.workspacePath||"").trim();if(t)return t;const r=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(r)?r:""}function Hy({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:u}){var B;const{launchCli:m}=oa(),[d,p]=l.useState(!1),[h,b]=l.useState([]),[g,f]=l.useState(()=>Ct()),[w,j]=l.useState(!1),[y,v]=l.useState(null),N=l.useRef(null),k=l.useMemo(()=>r||t||e,[e,r,t]),x=!!k&&Ze(k)&&!Ye(k),I=l.useMemo(()=>{if(!k||!x)return null;const L=k.daemonId||k.routeId||"",$=Vt(k),F=za(k);return`${L}:${$}:${k.providerSessionId||""}:${F}`},[k,x]),C=l.useMemo(()=>!k||!x?"":za(k),[k,x]),{isCreatingChat:M,isRefreshingHistory:D,handleSwitchSession:P,handleNewChat:T,handleRefreshHistory:R}=$u({sendDaemonCommand:a,activeConv:k,chats:(B=n.find(L=>L.id===(k==null?void 0:k.routeId)))==null?void 0:B.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),O=l.useCallback(()=>{p(!0)},[]),K=l.useCallback(()=>{p(!1)},[]),S=l.useCallback(async()=>{if(!(!k||!x||w)){j(!0);try{const L=k.daemonId||k.routeId,$=Vt(k),F=za(k),z=await a(L,"list_saved_sessions",{agentType:$,providerType:$,kind:"cli",limit:50,...k.providerSessionId?{providerSessionId:k.providerSessionId}:{},...F?{workspace:F}:{}}),re=(z==null?void 0:z.result)??z;b(Array.isArray(re==null?void 0:re.sessions)?re.sessions:[])}catch(L){console.error("Refresh saved sessions failed",L),b([])}finally{j(!1)}}},[k,w,x,a]);l.useEffect(()=>{if(!d){N.current=null;return}if(!x){N.current=null,b([]),j(!1);return}!I||w||N.current!==I&&(N.current=I,S())},[S,d,w,x,I]);const A=l.useCallback(async L=>{if(!k||!x||!L.providerSessionId||!L.workspace)return;const $=k.daemonId||k.routeId,F=Vt(k);try{v(L.providerSessionId);const z=await m($,{cliType:F,dir:L.workspace,resumeSessionId:L.providerSessionId,initialModel:Id(L.summaryMetadata,"model",{preferShortValue:!0})||void 0}),re=(z==null?void 0:z.result)??z,J=typeof(re==null?void 0:re.sessionId)=="string"?re.sessionId:typeof(re==null?void 0:re.id)=="string"?re.id:"";J&&u(Y=>{const se=new URLSearchParams(Y);return se.set("activeTab",J),se},{replace:!0}),K()}catch(z){console.error("Resume saved session failed",z)}finally{v(null)}},[K,k,x,a,u]);return{historyModalOpen:d,openHistoryModal:O,closeHistoryModal:K,historyTargetConv:k,isSavedSessionHistoryTarget:x,isHistoryCreatingChat:M,isHistoryRefreshingHistory:D,handleHistorySwitchSession:P,handleHistoryNewChat:T,handleHistoryRefresh:R,savedHistorySessions:h,savedHistoryFilters:g,setSavedHistoryFilters:f,missingWorkspaceResumePath:C,isSavedHistoryLoading:w,resumingSavedHistorySessionId:y,handleRefreshSavedHistory:S,handleResumeSavedHistorySession:A}}function Wy({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}){const[u,m]=l.useState(null),[d,p]=l.useState(null),h=l.useMemo(()=>{if(e||!n)return null;const j=c(n);return j&&!Ze(j)&&!Ye(j)?j:null},[e,n,c]),b=l.useMemo(()=>{const j=u==null?void 0:u.routeId;if(!j)return null;const y=u!=null&&u.tabKey?o.find(v=>v.tabKey===u.tabKey):a?o.find(v=>v.tabKey===a):null;return(y==null?void 0:y.routeId)===j?y:Ft(o,j)},[o,u,a]),g=l.useMemo(()=>{if(b)return i.find(j=>j.id===b.routeId)},[i,b]);l.useEffect(()=>{h&&(m({routeId:h.routeId,tabKey:xl(h)}),p(h),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,h]);const f=l.useCallback(j=>{j&&(m({routeId:j.routeId,tabKey:xl(j)}),p(j))},[]),w=l.useCallback(()=>{m(null),p(null)},[]);return{remoteDialogConv:b,remoteDialogIdeEntry:g,remoteDialogActiveConv:d,setRemoteDialogActiveConv:p,openRemoteDialog:f,closeRemoteDialog:w}}function Ky({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:u,sendDaemonCommand:m}){const{remoteDialogConv:d,remoteDialogIdeEntry:p,remoteDialogActiveConv:h,setRemoteDialogActiveConv:b,openRemoteDialog:g,closeRemoteDialog:f}=Wy({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}),[w,j]=l.useState(!1),[y,v]=l.useState(null),N=l.useCallback(async I=>{const C=I||u;!C||!Ze(C)&&!Ye(C)||(v(C),j(!0))},[u]),k=l.useCallback(()=>{j(!1),v(null)},[]),x=l.useCallback(async I=>{const C=y||u;if(!C||!Ze(C)&&!Ye(C)){k();return}j(!1);try{const M=Vt(C),D=C.routeId||C.daemonId||"";await m(D,"stop_cli",{cliType:M,targetSessionId:C.sessionId,mode:I})}catch(M){console.error("Stop CLI failed:",M)}finally{v(null)}},[u,k,y,m]);return{remoteDialogConv:d,remoteDialogIdeEntry:p,remoteDialogActiveConv:h,setRemoteDialogActiveConv:b,openRemoteDialog:g,closeRemoteDialog:f,cliStopDialogOpen:w,cliStopTargetConv:y,requestCliStop:N,cancelCliStop:k,confirmCliStop:x}}function Ha(e,t=!0){return(e??!0)&&t}const wi=l.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:u,handleForceSendChat:m,isSendingChat:d,sendFeedbackMessage:p=null,handleFocusAgent:h,isFocusingAgent:b,actionLogs:g,userName:f,scrollToBottomRequestNonce:w,isInputActive:j=!0,isVisible:y=!0}){const v=n,N=!n,k=Ha(y,v),x=Ha(y,N),I=Ha(y),C=ku(t),M=C.status||C.modalMessage||C.modalButtons?{...t,...C.status?{status:C.status}:{},...C.modalMessage!==void 0?{modalMessage:C.modalMessage}:{},...C.modalButtons!==void 0?{modalButtons:C.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(kd,{activeConv: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(zs,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:c,children:"Relaunch with CDP"})]})}):null,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":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:v?"visible":"hidden",pointerEvents:v?"auto":"none"},children:s.jsx(ng,{activeConv:M,clearToken:r,terminalRef:o,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:p,isVisible:k,isInputActive:j&&k})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:N?"visible":"hidden",pointerEvents:N?"auto":"none"},children:s.jsx(To,{activeConv:M,ideEntry:a,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:p,handleFocusAgent:h,isFocusingAgent:b,actionLogs:g,userName:f,scrollToBottomRequestNonce:w,isInputActive:j&&x,isVisible:x})})]}):s.jsx(To,{activeConv:M,ideEntry:a,handleSendChat:u,handleForceSendChat:m,isSendingChat:d,sendFeedbackMessage:p,handleFocusAgent:h,isFocusingAgent:b,actionLogs:g,userName:f,scrollToBottomRequestNonce:w,isInputActive:j&&I,isVisible:I})]})},(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 Uy({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:o=!1}){var v,N,k;const i=$r(),c=Ms(e),u=o?null:Rd(e),m=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),d=!o&&e.streamSource==="agent-stream"&&!!e.agentName,p=!o&&!d&&(e.transport==="pty"||e.transport==="acp"),h=Ws(e),b=Nx(e),g=(v=e.settings)==null?void 0:v.meshNodeFor,f=e.meshQueueStats,w=((N=e.coordinator)==null?void 0:N.meshId)||((k=e.settings)==null?void 0:k.meshCoordinatorFor),j=l.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),y=l.useCallback(()=>{if(r){r();return}const x=Hu(e);x&&i(Pr(x))},[e,i,r]);return!m&&!d&&!p&&!u&&!g&&!f?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[m&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:y,title:b,children:[s.jsx(Ot,{size:12}),s.jsx("span",{children:b})]}):s.jsxs("span",{className:"conversation-meta-chip",title:b,children:[s.jsx(Ot,{size:12}),s.jsx("span",{children:b})]})),d&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(Hs,{size:12}),s.jsx("span",{children:h})]}),p&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(Hs,{size:12}),s.jsx("span",{children:h})]}),u&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:j,title:u,children:[s.jsx(is,{size:12}),s.jsx("span",{children:u})]}):s.jsxs("span",{className:"conversation-meta-chip",title:u,children:[s.jsx(is,{size:12}),s.jsx("span",{children:u})]})),g&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(is,{size:12}),s.jsx("span",{children:"Mesh Node"})]}),w&&f&&s.jsxs("span",{className:`conversation-meta-chip ${f.pending>0?"is-active":""}`,style:f.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${f.pending} pending, ${f.assigned} assigned, ${f.completed} completed, ${f.failed} failed`,children:[s.jsx(yh,{size:12}),s.jsxs("span",{children:[f.pending," Pending"]})]})]})}function Gy({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:u,onBack:m,onOpenNativeConversation:d,onOpenMachine:p,onOpenHistory:h,onOpenRemote:b,onOpenMeshGraph:g,onStopCli:f,cliViewMode:w,onSetCliViewMode:j,handleSendChat:y,handleForceSendChat:v,handleFocusAgent:N,handleModalButton:k,handleRelaunch:x}){var T,R;const I=l.useRef(null),C=Ze(e)&&!t,M=C&&w==="terminal",D=!!e.daemonId&&!!((T=e.coordinator)!=null&&T.meshId||(R=e.settings)!=null&&R.meshCoordinatorFor),P=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${P} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:s.jsx(Go,{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:it(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(Uy,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>p(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[C&&w&&s.jsx(nu,{mode:w,onChange:j,compact:!0}),C&&f&&s.jsx("button",{onClick:()=>{f(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(vt,{size:14})}),D&&g&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(Qt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>h(e),type:"button",children:s.jsx(Vo,{size:14})}),!t&&!C&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>b(e),type:"button",children:s.jsx(Ot,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(wi,{activeConv:e,clearToken:0,isCliTerminal:M,ideEntry:n,terminalRef:I,handleModalButton:k,handleRelaunch:x,handleSendChat:y,handleForceSendChat:v,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:N,isFocusingAgent:u,actionLogs:a,userName:o})})]})}const Wa={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 Vy(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Uu(){const[e,t]=l.useState("unix"),[r,n]=l.useState("powershell"),[a,o]=l.useState(!1),i=e==="unix"?"unix":r;l.useEffect(()=>{t(Vy())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(Wa[i].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[i]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"🍎🐧 macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"🪟 Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("powershell"),children:"⚡ PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:c,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:Wa[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Wa[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 Gu({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Ot},{key:"chats",label:"Chats",icon:Is}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:a,icon:o})=>{const i=e===n;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${i?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:i?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(n),type:"button","aria-pressed":i,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${i?"text-accent-primary":"bg-transparent text-current"}`,style:i?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(o,{size:15})}),s.jsx("span",{children:a})]},n)})})})}function fn({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 Ts({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 dr({icon:e,title:t,subtitle:r,children:n}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function qy({conversation:e,onCancel:t,onConfirm:r}){const n=it(e),a=Ss(e);return s.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:t}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"fade-in relative w-full sm:w-[min(92vw,420px)] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] border border-border-subtle bg-bg-primary shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border-subtle bg-[var(--surface-primary)] px-4 py-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base font-extrabold text-text-primary",children:"Hide this chat from the inbox?"}),s.jsx("div",{className:"mt-1 text-[13px] leading-relaxed text-text-muted",children:"This only collapses the chat locally. You can restore it from Hidden tabs."})]}),s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary text-text-secondary transition-colors hover:bg-surface-primary hover:text-text-primary",onClick:t,"aria-label":"Cancel hide chat",children:s.jsx(vt,{size:16})})]}),s.jsx("div",{className:"px-4 py-4",children:s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary/60 px-3.5 py-3",children:[s.jsx("div",{className:"truncate text-sm font-bold text-text-primary",children:n}),s.jsx("div",{className:"mt-1 truncate text-xs text-text-muted",children:a})]})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-border-subtle bg-bg-secondary px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))]",children:[s.jsx("button",{type:"button",className:"btn btn-secondary min-h-[40px] px-4 text-sm",onClick:t,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary min-h-[40px] px-4 text-sm",onClick:r,children:"Hide tab"})]})]})]})}function xn({item:e,type:t,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onOpenMeshGraph:o,onCollectChatDebugBundle:i,isMuted:c,onToggleMute:u}){var T,R;const m=t==="needs_attention"||t==="task_complete",d=t==="working",p=t==="earlier",h=t==="task_complete",{isReconnecting:b,isConnecting:g}=Vs(e.conversation),f=it(e.conversation),w=Ss(e.conversation),j=eu(e.conversation,{requiresAction:t==="needs_attention"}),y=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":d?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":p?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",v=m?"bg-accent-primary shadow-glow":d?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":p?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",N=p?"text-text-secondary":"text-text-primary",k=p?"text-text-muted":"text-text-secondary",x=p?"text-text-secondary opacity-80":"text-text-muted",I=p?"text-text-muted opacity-80":"text-text-muted",C=!d&&!h,M=!!e.conversation.daemonId&&!!((T=e.conversation.coordinator)!=null&&T.meshId||(R=e.conversation.settings)!=null&&R.meshCoordinatorFor),D="text-[color:var(--status-warning)]",P=O=>{if(!i)return;O.preventDefault(),O.stopPropagation();const K=i==null?void 0:i(e.conversation);Promise.resolve(K).catch(S=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",S)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${y}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||d?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${v}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:r(f)}),a&&s.jsxs("button",{type:"button",className:"mobile-inbox-hide-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border border-border-subtle bg-bg-primary/70 px-2 text-[10px] font-semibold text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:O=>{O.preventDefault(),O.stopPropagation(),a()},"aria-label":`Hide ${f}`,title:"Hide conversation",children:[s.jsx(qo,{size:11}),s.jsx("span",{children:"Hide"})]}),u&&s.jsxs("button",{type:"button",className:`mobile-inbox-mute-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border px-2 text-[10px] font-semibold transition-colors ${c?"border-amber-500/40 bg-amber-500/10 text-amber-300 hover:bg-amber-500/20":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:O=>{O.preventDefault(),O.stopPropagation(),u()},"aria-label":c?`Unmute ${f}`:`Mute ${f}`,title:c?"Unmute (resume notifications)":"Mute notifications",children:[s.jsx(Er,{size:11}),s.jsx("span",{children:c?"Muted":"Mute"})]}),M&&o&&s.jsxs("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border border-border-subtle bg-bg-primary/70 px-2 text-[10px] font-semibold text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:O=>{O.preventDefault(),O.stopPropagation(),o(e.conversation)},"aria-label":`Open mesh graph for ${f}`,title:"Open live repo mesh graph",children:[s.jsx(Qt,{size:11}),s.jsx("span",{children:"Graph"})]})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>n(e.conversation),onContextMenu:P,type:"button",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${N}`,children:f}),C&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${I}`,children:jd(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${k}`,children:[s.jsx("span",{className:"truncate",children:w}),s.jsx(Gn,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),b?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${D} animate-pulse`,children:"Reconnecting…"})]}):g?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):j==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:D,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${x}`,children:e.preview})]}),m&&!h&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),h&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),d&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]})},e.conversation.tabKey)}function Zl({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 Yy({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:u,sendDaemonCommand:m,onOpenConversation:d,onShowAllHidden:p,onHideConversation:h,onOpenMeshGraph:b,onOpenNewSession:g,onOpenMachine:f,onOpenSettings:w,onSectionChange:j,wsStatus:y="connected",isStandalone:v=!1,onCollectChatDebugBundle:N,isConversationMuted:k,onToggleMuteConversation:x}){const[I,C]=l.useState(null),M=y==="disconnected"||y==="reconnecting"||y==="offline"||y==="auth_failed",D=i.length>0,P=t.length>0||r.length>0||n.length>0||a.length>0,T=e==="machines"?"Machines":"Chats",R=v?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",O=v?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",K=l.useCallback(async B=>{const L=gs(B);if(!L)return;const $=Array.isArray(B.messages)?B.messages:[],F=Od({activeConv:B,visibleMessages:$,actionLogs:u,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:$.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),z=await m(L,"get_chat_debug_bundle",{...bs(B),delivery:"daemon_file",frontendSnapshot:F}),re=vr(z),J=Wd(re),Y=await Hd(J);Y==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),tt.showToast(zd(re,{locatorCopyStatus:Y}),Y==="failed"?"warning":"success")},[u,m]),S=N||K,A=l.useCallback(()=>{I&&(h==null||h(I),C(null))},[I,h]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${R}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:T}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||r.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(Er,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:w,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(ia,{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] ${O}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:M?s.jsx(dr,{icon:s.jsx(Zl,{}),title:y==="offline"?"Network offline":y==="auth_failed"?"Session expired":"Reconnecting",subtitle:y==="offline"?"Waiting for network…":y==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):i.length===0?s.jsx(dr,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:v?"Waiting for your daemon":"Connect your machines",subtitle:v?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can launch sessions with any installed provider.":"Install ADHDev on a machine, sign in, and it will show up here.",children:!v&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Uu,{})})}):s.jsx(Ts,{children:i.map((B,L)=>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] ${L>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(B.id),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:c(B.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:B.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:B.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[B.unread," new"]}):B.total>0?`${B.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:B.subtitle}),B.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[B.total," chat",B.total!==1?"s":"",B.unread>0?` · ${B.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},B.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(fn,{title:"Needs attention",className:"mb-0"}),s.jsx(Ts,{children:t.map((B,L)=>s.jsx("div",{className:L>0?"border-t border-border-subtle/70":"",children:s.jsx(xn,{item:B,type:"needs_attention",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:h?()=>C(B.conversation):void 0,onOpenMeshGraph:b,onCollectChatDebugBundle:S,isMuted:k==null?void 0:k(B.conversation),onToggleMute:x?()=>x(B.conversation):void 0})},B.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(fn,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(Ts,{children:r.map((B,L)=>s.jsx("div",{className:L>0?"border-t border-border-subtle/70":"",children:s.jsx(xn,{item:B,type:"task_complete",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:h?()=>C(B.conversation):void 0,onOpenMeshGraph:b,onCollectChatDebugBundle:S,isMuted:k==null?void 0:k(B.conversation),onToggleMute:x?()=>x(B.conversation):void 0})},B.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(fn,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(Ts,{children:n.map((B,L)=>s.jsx("div",{className:L>0?"border-t border-border-subtle/70":"",children:s.jsx(xn,{item:B,type:"working",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:h?()=>C(B.conversation):void 0,onOpenMeshGraph:b,onCollectChatDebugBundle:S,isMuted:k==null?void 0:k(B.conversation),onToggleMute:x?()=>x(B.conversation):void 0})},B.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(fn,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(Ts,{children:a.map((B,L)=>s.jsx("div",{className:L>0?"border-t border-border-subtle/70":"",children:s.jsx(xn,{item:B,type:"earlier",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:h?()=>C(B.conversation):void 0,onOpenMeshGraph:b,onCollectChatDebugBundle:S,isMuted:k==null?void 0:k(B.conversation),onToggleMute:x?()=>x(B.conversation):void 0})},B.conversation.tabKey))}):P?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):M?s.jsx(dr,{icon:s.jsx(Zl,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):D?s.jsx(dr,{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(Is,{size:20})}),title:"No conversations yet",subtitle:au,children:g&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:g,"aria-label":Ut,title:Ut,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:Ut})]})}):s.jsx(dr,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&o.length>0&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(Ts,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:"Hidden tabs"}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[o.length," collapsed ",o.length===1?"conversation":"conversations"]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:p,children:"Restore all"})]})})})]}),e==="chats"&&g&&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:g,"aria-label":Ut,title:Ut,children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),I&&s.jsx(qy,{conversation:I,onCancel:()=>C(null),onConfirm:A}),s.jsx(Gu,{section:e,onSectionChange:j})]})}function Jy(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 Vu(e){const t=[e.workspace||"Workspace unknown"],r=Ns(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Jy(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function ji({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:u,onConfirm:m}){const[d,p]=l.useState(r);l.useEffect(()=>{p(r)},[r]);const h=Iy(r),b=d.trim();return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:c,"aria-label":"Close folder browser",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!h||a||u(h)},disabled:!h||a,children:[s.jsx(Go,{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:g=>p(g.target.value),onKeyDown:g=>{g.key!=="Enter"||!b||a||(g.preventDefault(),u(b))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!b||a||u(b)},disabled:!b||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):n.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:n.map(g=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(g.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Os,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:g.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:g.path})]})]},g.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>m(b||r),disabled:!b&&!r||a,children:i})]})]})})}function qu({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:i="Launch",busyLabel:c="Launching…",busy:u=!1,showArgsInput:m,argsValue:d,onArgsChange:p,showModelInput:h,modelValue:b,onModelChange:g,historyProviderNode:f,onConfirm:w,onCancel:j}){const y=n==null?void 0:n.find(v=>v.key===a);return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:j,"aria-label":"Close launch confirmation",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),s.jsx("select",{value:a||"",onChange:v=>o(v.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:u,children:n.map(v=>s.jsx("option",{value:v.key,children:v.label},v.key))}),(y==null?void 0:y.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:y.description})]}),f,r.map(v=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:v.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:v.value})]},`${v.label}:${v.value}`)),h&&g&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:b||"",onChange:v=>g(v.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]}),m&&p&&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:v=>p(v.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]})]}),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:u,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:w,disabled:u,children:[s.jsx(ld,{size:14}),u?c:i]})]})]})})}function ec(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Yu(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,o=[];a&&o.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])o.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${ec(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const i=(r==null?void 0:r.trim())||"",c=i?(t.workspaces||[]).find(u=>u.path===i):null;if(i&&!c&&o.push({key:`custom:${i}`,label:ec(i),description:i,workspaceId:null,workspacePath:i}),n){const u=`saved:${n}`;if(o.some(m=>m.key===u))return{options:o,selectedKey:u}}return c?{options:o,selectedKey:`saved:${c.id}`}:i?{options:o,selectedKey:`custom:${i}`}:{options:o,selectedKey:"__home__"}}function Xy(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Qy(e){return[Xy(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Zy(e){return e.lastLaunchedAt?ca(e.lastLaunchedAt):""}function Ju(e){return{metaText:Qy(e),updatedLabel:Zy(e)}}function Ka(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function ev({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var et,ct,st,ft;const i=Or(),[c,u]=l.useState(!1),m=(((et=e.detectedIdes)==null?void 0:et.length)||0)>0,d=l.useMemo(()=>(e.workspaces||[]).map(Me=>({id:Me.id,path:Me.path,label:Me.label})),[e]),p=e.defaultWorkspaceId||null,[h,b]=l.useState(p||((ct=d[0])==null?void 0:ct.id)||""),[g,f]=l.useState(""),[w,j]=l.useState(""),[y,v]=l.useState([]),[N,k]=l.useState(!1),[x,I]=l.useState(""),[C,M]=l.useState(!1),[D,P]=l.useState(Ka(m,t.length,r.length)),T=l.useRef(null),[R,O]=l.useState(null),K=l.useRef("__home__"),[S,A]=l.useState("__home__"),[B,L]=l.useState(""),[$,F]=l.useState(""),[z,re]=l.useState(""),[J,Y]=l.useState([]),[se,fe]=l.useState(()=>Ct().textQuery),[be,X]=l.useState(()=>Ct().workspaceQuery),[Q,we]=l.useState(()=>Ct().modelQuery),[ve,xe]=l.useState(()=>Ct().resumableOnly),[Ne,ae]=l.useState(()=>Ct().sortMode),[ge,me]=l.useState(!1),[U,H]=l.useState(!1),q=l.useRef(null),ne=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const E=h==="__custom__"?g.trim():((st=d.find(Me=>Me.id===h))==null?void 0:st.path)||"",W=h==="__custom__"&&!!E&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),_=h!=="__custom__"&&((ft=d.find(Me=>Me.id===h))==null?void 0:ft.path)||"",ie=l.useMemo(()=>(e.recentLaunches||[]).map(Me=>Me.workspace),[e]),pe=l.useCallback(async Me=>{k(!0),I("");try{const Se=await a(Me);j(Se.path),f(Se.path),v(Se.directories)}catch(Se){I(Se instanceof Error?Se.message:"Could not load folder")}finally{k(!1)}},[a]),ue=l.useCallback(()=>{var Se;b("__custom__"),M(!0);const Me=yi(e.platform,gi(g.trim(),_,ie,e.defaultWorkspacePath,(Se=d.find(Qe=>Qe.id===p))==null?void 0:Se.path,d.map(Qe=>Qe.path)));pe(Me)},[g,p,pe,ie,_,e.platform,d]),oe=l.useCallback(Me=>{if(Me!=null&&Me.workspaceId){b(Me.workspaceId),f("");return}if(Me!=null&&Me.workspacePath){b("__custom__"),f(Me.workspacePath);return}b(""),f("")},[]),Pe=l.useCallback(Me=>{if(b(Me),Me==="__custom__"){ue();return}f("")},[ue]),Ee=l.useCallback(Me=>{b("__custom__"),f(Me)},[]),$e=l.useCallback((Me,Se)=>{T.current=Se,K.current=Me.selectedWorkspaceKey||"__home__",A(Me.selectedWorkspaceKey||"__home__"),L(Me.initialArgs||""),F(Me.initialModel||""),re(""),Y([]);const Qe=Me.providerType?`${e.id}:${Me.providerType}`:null;if(hg(ne.current,Qe)){const Ge=Ct();fe(Ge.textQuery),X(Ge.workspaceQuery),we(Ge.modelQuery),xe(Ge.resumableOnly),ae(Ge.sortMode)}ne.current=Qe,O(Me),Me.providerType&&o&&(me(!0),o(Me.providerType).then(Ge=>Y(Ge||[])).catch(Ge=>console.warn("Failed to load saved sessions",Ge)).finally(()=>me(!1)))},[o,e.id]),He=l.useMemo(()=>ou(J,{textQuery:se,workspaceQuery:be,modelQuery:Q,resumableOnly:ve,sortMode:Ne}),[Q,ve,J,Ne,se,be]);l.useEffect(()=>{z&&(He.some(Me=>Me.providerSessionId===z)||re(""))},[He,z]);const Xe=l.useCallback(()=>{T.current&&(H(!0),T.current().finally(()=>{T.current=null,H(!1),O(null)}))},[]),Je=l.useCallback(()=>{T.current=null,O(null)},[]),nt=l.useCallback(Me=>{K.current=Me,A(Me)},[]);return l.useEffect(()=>{var Me;q.current!==e.id&&(q.current=e.id,b(p||((Me=d[0])==null?void 0:Me.id)||"__custom__"),f(""),j(""),v([]),I(""),M(!1),fe(Ct().textQuery),X(Ct().workspaceQuery),we(Ct().modelQuery),xe(Ct().resumableOnly),ae(Ct().sortMode),ne.current=null,P(Ka(m,t.length,r.length)))},[r.length,t.length,p,m,e.id,d]),l.useEffect(()=>{var Me;h!=="__custom__"&&(h&&d.some(Se=>Se.id===h)||b(p||((Me=d[0])==null?void 0:Me.id)||"__custom__"))},[p,h,d]),l.useEffect(()=>{D==="ide"&&m||D==="cli"&&t.length>0||D==="acp"&&r.length>0||P(Ka(m,t.length,r.length))},[D,r.length,t.length,m]),{showAllRecent:c,setShowAllRecent:u,hasIdeOptions:m,workspaceRows:d,defaultWorkspaceId:p,workspaceChoice:h,customWorkspacePath:g,browseCurrentPath:w,browseDirectories:y,browseBusy:N,browseError:x,browseDialogOpen:C,activeLauncherKind:D,launchConfirm:R,launchConfirmWorkspaceKeyRef:K,launchConfirmWorkspaceKey:S,launchConfirmArgs:B,launchConfirmModel:$,launchConfirmResumeId:z,launchConfirmSavedSessions:J,launchConfirmTextFilter:se,launchConfirmWorkspaceFilter:be,launchConfirmModelFilter:Q,launchConfirmResumableOnly:ve,launchConfirmSortMode:Ne,filteredLaunchConfirmSavedSessions:He,launchConfirmSessionsLoading:ge,launchConfirmBusy:U,resolvedWorkspacePath:E,canCreateMissingWorkspace:W,openBrowseDialog:ue,loadBrowsePath:pe,handleWorkspaceChoiceChange:Pe,chooseCustomWorkspacePath:Ee,setCustomWorkspacePath:f,setBrowseDialogOpen:M,setActiveLauncherKind:P,openLaunchConfirm:$e,handleConfirmLaunch:Xe,closeLaunchConfirm:Je,setWorkspaceSelectionFromOption:oe,setLaunchConfirmWorkspaceKeyAndSync:nt,setLaunchConfirmArgs:L,setLaunchConfirmModel:F,setLaunchConfirmResumeId:re,setLaunchConfirmTextFilter:fe,setLaunchConfirmWorkspaceFilter:X,setLaunchConfirmModelFilter:we,setLaunchConfirmResumableOnly:xe,setLaunchConfirmSortMode:ae}}function tv({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:u,section:m,showBottomNav:d,onBack:p,onSectionChange:h,onOpenConversation:b,onOpenRecent:g,onOpenMachineDetails:f,onMachineUpgrade:w,onLaunchDetectedIde:j,onAddWorkspace:y,onBrowseDirectory:v,onLaunchWorkspaceProvider:N,onListSavedSessions:k}){const x=S=>S==="ide"?"Workspace":S==="cli"?"CLI":"ACP",I=r.slice(0,4),C=t.slice(0,3),M=ev({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:c,onBrowseDirectory:v,onListSavedSessions:k}),D=l.useMemo(()=>I.map(S=>{const{metaText:A,updatedLabel:B}=Ju(S);return{key:`recent-launch:${S.id}`,primary:S.label,secondary:A,updatedLabel:B,onClick:()=>{const{options:L,selectedKey:$}=Yu({machine:{workspaces:M.workspaceRows,defaultWorkspaceId:M.defaultWorkspaceId},currentWorkspacePath:S.workspace});M.openLaunchConfirm({title:S.kind==="ide"?qn("restart-ide",S.label):S.providerSessionId?iu(S.label):qn("start-fresh",S.label),description:S.kind==="ide"?Yn("restart-ide"):S.providerSessionId?lu():Yn("start-fresh"),confirmLabel:S.kind==="ide"?Jn("restart-ide"):S.providerSessionId?Vn(!0):Jn("start-fresh"),busyLabel:S.kind==="ide"?Xn("restart-ide"):S.providerSessionId?ci(!0):Xn("start-fresh"),workspaceOptions:L,selectedWorkspaceKey:$,details:[{label:"Mode",value:x(S.kind)},...S.providerType?[{label:"Provider",value:S.providerType}]:[]]},async()=>{const F=L.find(z=>z.key===M.launchConfirmWorkspaceKeyRef.current);M.setWorkspaceSelectionFromOption(F),await g({...S,workspace:(F==null?void 0:F.workspacePath)??null})})}}}),[M,g,I]),P=l.useMemo(()=>C.map(S=>({key:`recent-chat:${S.conversation.tabKey}`,primary:it(S.conversation),secondary:Kb(S.conversation,{timestampLabel:S.timestamp?jd(S.timestamp):null}),unread:S.unread,onClick:()=>b(S.conversation)})),[b,C]),T=M.showAllRecent?D:D.slice(0,4),R=D.length>0,O=P.length>0,K=u?"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 ${K} 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(Go,{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:Pt(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:[O&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:P.map(S=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${S.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:S.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:S.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:S.secondary})]},S.key))})]}),R&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:T.map(S=>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:S.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:S.primary}),S.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:S.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:S.secondary})]},S.key))}),D.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:()=>M.setShowAllRecent(S=>!S),children:M.showAllRecent?"Show fewer":`Show ${D.length-4} more`})})]}),!1,s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:w,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",i]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:f,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),M.browseDialogOpen&&s.jsx(ji,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:M.browseCurrentPath,directories:M.browseDirectories,busy:M.browseBusy,error:M.browseError,confirmLabel:"Use this folder",onClose:()=>M.setBrowseDialogOpen(!1),onNavigate:S=>{M.loadBrowsePath(S)},onConfirm:S=>{M.chooseCustomWorkspacePath(S),M.setBrowseDialogOpen(!1)}}),M.launchConfirm&&s.jsx(qu,{title:M.launchConfirm.title,description:M.launchConfirm.description,details:M.launchConfirm.details,workspaceOptions:M.launchConfirm.workspaceOptions,selectedWorkspaceKey:M.launchConfirmWorkspaceKey,onWorkspaceChange:M.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:M.launchConfirm.providerType?Vn(!!M.launchConfirmResumeId):M.launchConfirm.confirmLabel,busyLabel:M.launchConfirm.providerType?void 0:M.launchConfirm.busyLabel,busy:M.launchConfirmBusy,showArgsInput:M.launchConfirm.showArgsInput,argsValue:M.launchConfirmArgs,onArgsChange:M.setLaunchConfirmArgs,showModelInput:M.launchConfirm.showModelInput,modelValue:M.launchConfirmModel,onModelChange:M.setLaunchConfirmModel,historyProviderNode:M.launchConfirm.providerType&&(M.launchConfirmSessionsLoading||M.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"}),M.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:di()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:M.launchConfirmTextFilter,onChange:S=>M.setLaunchConfirmTextFilter(S.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:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:M.launchConfirmWorkspaceFilter,onChange:S=>M.setLaunchConfirmWorkspaceFilter(S.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:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:M.launchConfirmModelFilter,onChange:S=>M.setLaunchConfirmModelFilter(S.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:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),s.jsxs("select",{value:M.launchConfirmSortMode,onChange:S=>M.setLaunchConfirmSortMode(S.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:M.launchConfirmBusy||M.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:M.launchConfirmResumableOnly,onChange:S=>M.setLaunchConfirmResumableOnly(S.target.checked),disabled:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:M.launchConfirmResumeId,onChange:S=>M.setLaunchConfirmResumeId(S.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:M.launchConfirmBusy||M.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:bg()}),M.filteredLaunchConfirmSavedSessions.map(S=>s.jsxs("option",{value:S.providerSessionId,disabled:!S.canResume,children:[S.title||S.providerSessionId," ",S.canResume?"":"(workspace missing)"]},S.providerSessionId))]}),!M.launchConfirmSessionsLoading&&M.launchConfirmSavedSessions.length>0&&M.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),M.launchConfirmResumeId&&(()=>{const S=M.filteredLaunchConfirmSavedSessions.find(B=>B.providerSessionId===M.launchConfirmResumeId);if(!S)return null;const A=Vu(S);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:A.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:A.providerSessionId}),s.jsx("div",{className:"mt-1",children:A.metaLine}),A.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:A.updatedLabel}),A.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:A.preview})]})})()]}),onConfirm:M.handleConfirmLaunch,onCancel:M.closeLaunchConfirm}),d&&s.jsx(Gu,{section:m,onSectionChange:h})]})}function _n(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function sv(e,t=[]){const r=new Map(e.map(a=>[a.conversation.tabKey,a])),n=t.map(a=>r.get(a)).filter(a=>!!a);return n.length===e.length?n:_n(e)}function rv(e){var r;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":"Offline"}function nv(e,t){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:Ns(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):t.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var i;const a=Ar(n)?"cli":$s(n)?"acp":"ide",o=Ns(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((i=n.activeChat)==null?void 0:i.title)||(Ar(n)?n.cliName||n.type:$s(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:$s(n)?o||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:n.lastMessageAt||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function av(e,t){const r=new Map;for(const n of t){const a=Ms(n.conversation),o=r.get(a);o?o.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],o=[...a].sort((p,h)=>h.timestamp-p.timestamp)[0]||null,i=(o==null?void 0:o.conversation)||null,c=ko(n),u=a.filter(p=>p.unread||p.requiresAction).length,m=rv(n),d=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:Pt(n,{fallbackId:n.id}),subtitle:d.join(" · "),unread:u,total:a.length,latestConversation:i,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:c,preview:i?Ub(i):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,a)=>{const o=n.latestTimestamp||n.fallbackActivityAt||0,i=a.latestTimestamp||a.fallbackActivityAt||0;return i!==o?i-o:n.label.localeCompare(a.label)})}function ov(e){return e==="chat"}function bn(e,t){var r;if(!(typeof window>"u"))try{if(!(!!((r=import.meta.env)!=null&&r.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,t)}catch{}}function iv({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:p,requestedMobileSection:h,onRequestedMobileSectionConsumed:b,setSelectedTabKey:g,setScreen:f,setSelectedMachineId:w,setSection:j,setMachineBackTarget:y,resetMachineAction:v}){const N=l.useRef(null),k=l.useCallback(x=>{if(!(x!=null&&x.sessionId))return;const I=zn(x,i),C=Math.max(Date.now(),js(x),I.lastUpdated||0);bn("mark_read:start",{tabKey:x.tabKey,sessionId:x.sessionId,displayPrimary:it(x),inboxBucket:I.inboxBucket,unread:I.unread,lastSeenAt:I.lastSeenAt,lastUpdated:I.lastUpdated,activityAt:js(x),readAt:C}),c(Ms(x)||x.routeId,"mark_session_seen",{sessionId:x.sessionId,providerSessionId:x.providerSessionId,seenAt:C,completionMarker:I.completionMarker}).then(M=>{bn("mark_read:result",{tabKey:x.tabKey,sessionId:x.sessionId,result:M})}).catch(M=>{bn("mark_read:error",{tabKey:x.tabKey,sessionId:x.sessionId,error:M instanceof Error?M.message:String(M)})})},[i,c]);return l.useEffect(()=>{var I;if(!n){ov(o)&&f("inbox"),g(((I=e[0])==null?void 0:I.tabKey)||null),N.current=null;return}if(o!=="chat"){N.current=null;return}const x=`${n.tabKey}:${n.sessionId||""}`;N.current!==x&&(N.current=x,k(n))},[e,k,o,n,f,g]),l.useEffect(()=>{if(!u)return;const x=e.find(I=>I.tabKey===u);x&&(g(x.tabKey),f("chat"),m==null||m())},[e,m,u,f,g]),l.useEffect(()=>{if(!d)return;const x=t.find(I=>I.id===d);x&&(w(x.id),v(),j("machines"),y("inbox"),f("machine"),p==null||p())},[t,p,d,v,y,f,j,w]),l.useEffect(()=>{h&&(j(h),f("inbox"),b==null||b())},[b,h,f,j]),l.useEffect(()=>{const x=r.filter(I=>I.inboxBucket==="task_complete"||I.unread);x.length!==0&&bn("inbox_state",{screen:o,selectedTabKey:a,items:x.map(I=>{const C=zn(I.conversation,i);return{liveState:C,tabKey:I.conversation.tabKey,sessionId:I.conversation.sessionId,displayPrimary:it(I.conversation),serverBucket:C.inboxBucket,computedBucket:I.inboxBucket,serverUnread:C.unread,computedUnread:I.unread,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,activityAt:js(I.conversation)}})})},[r,i,o,a]),{markConversationRead:k}}function lv(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function tc(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function cv(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function dv({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const{launchCli:a}=oa(),[o,i]=l.useState("idle"),[c,u]=l.useState(""),[m,d]=l.useState(null),p=l.useCallback(()=>{i("idle"),u(""),d(null)},[]),h=l.useCallback(async(v,N,k)=>{var x;try{i("loading"),u(`Launching ${N}…`);const I={ideType:N,enableCdp:!0};(x=k==null?void 0:k.workspacePath)!=null&&x.trim()&&(I.workspace=k.workspacePath.trim()),await e(v,"launch_ide",I),i("done"),u(`${N} launch requested`)}catch(I){i("error"),u(I instanceof Error?I.message:"Launch IDE failed"),console.error("Launch IDE failed",I)}},[e]),b=l.useCallback(async(v,N,k)=>{if(N.trim())try{i("loading"),u(k!=null&&k.createIfMissing?"Creating folder…":"Saving workspace…");const x=await e(v,"workspace_add",{path:N.trim(),createIfMissing:(k==null?void 0:k.createIfMissing)===!0});if(x!=null&&x.success){i("done"),u(k!=null&&k.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),u((x==null?void 0:x.error)||"Could not save workspace")}catch(x){i("error"),u(x instanceof Error?x.message:"Could not save workspace")}},[e]),g=l.useCallback(async v=>{var N,k,x,I,C,M;try{i("loading"),u("Starting daemon upgrade…");const D=await e(v,"daemon_upgrade",{});if((N=D==null?void 0:D.result)!=null&&N.alreadyLatest){i("done"),u(`Already on v${((k=D==null?void 0:D.result)==null?void 0:k.version)||"latest"}.`);return}if((x=D==null?void 0:D.result)!=null&&x.upgraded||(I=D==null?void 0:D.result)!=null&&I.success){i("done"),u(`Upgrade to v${((C=D==null?void 0:D.result)==null?void 0:C.version)||"latest"} started. Daemon is restarting…`);return}i("error"),u(((M=D==null?void 0:D.result)==null?void 0:M.error)||"Upgrade failed")}catch(D){i("error"),u(D instanceof Error?D.message:"Upgrade failed")}},[e]),f=l.useCallback(async(v,N,k,x)=>{var M,D,P;const I=Date.now(),C={machineId:v,kind:N,providerType:k,workspaceId:(x==null?void 0:x.workspaceId)||null,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,startedAt:I};try{i("loading"),u(`Launching ${k}…`),d(C);const T={cliType:k};(M=x==null?void 0:x.workspacePath)!=null&&M.trim()?T.dir=x.workspacePath.trim():x!=null&&x.workspaceId&&(T.workspaceId=x.workspaceId),x!=null&&x.resumeSessionId&&(T.resumeSessionId=x.resumeSessionId),(D=x==null?void 0:x.args)!=null&&D.trim()&&(T.cliArgs=x.args.trim().split(/\s+/).filter(Boolean)),(P=x==null?void 0:x.model)!=null&&P.trim()&&(T.initialModel=x.model.trim());const R=await a(v,T),O=(R==null?void 0:R.result)||R,K=(O==null?void 0:O.sessionId)||(O==null?void 0:O.id);if(R!=null&&R.success&&K){d(null),i("done"),u(`${k} launched`),t(Pr(K));return}if(R!=null&&R.success){i("loading"),u(`${k} launch requested — waiting for session…`);return}d(null),i("error"),u((R==null?void 0:R.error)||(O==null?void 0:O.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(T){if(cv(T)){i("loading"),u(`${k} launch requested — waiting for session…`);return}d(null),i("error"),u(T instanceof Error?T.message:`Could not launch ${N.toUpperCase()} workspace`)}},[t,e]),w=l.useCallback(async(v,N)=>{try{const k=await e(v,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),x=(k==null?void 0:k.result)??k;return Array.isArray(x==null?void 0:x.sessions)?x.sessions:[]}catch(k){return console.error("Failed to list saved sessions on mobile:",k),[]}},[e]),j=l.useCallback(async(v,N)=>vi(e,v,N),[e]);l.useEffect(()=>{if(!m)return;const v=tc(m.workspacePath),N=r.find(x=>{var T,R,O,K;if(!x||x.type==="adhdev-daemon"||lv(x.daemonId||x.id)!==m.machineId||(x.transport==="acp"?"acp":x.transport==="pty"?"cli":null)!==m.kind||String(x.agentType||x.type||"")!==m.providerType)return!1;const D=String(x.providerSessionId||"");if(m.resumeSessionId&&D)return D===m.resumeSessionId;if(v){const S=tc(x.workspace||x.runtimeWorkspaceLabel);return S?S===v:!1}return Number(x.lastUpdated||x._lastUpdate||x.timestamp||((K=(O=(R=(T=x.activeChat)==null?void 0:T.messages)==null?void 0:R.at)==null?void 0:O.call(R,-1))==null?void 0:K.timestamp)||0)>=m.startedAt-5e3});if(!N)return;const k=Wu({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:n});k&&(d(null),i("done"),u(`${m.providerType} launched`),t(Pr(k)))},[n,r,t,m]),l.useEffect(()=>{if(!m)return;const v=window.setTimeout(()=>{d(N=>!N||N.startedAt!==m.startedAt?N:(i("error"),u("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(v)},[m]);const y=l.useCallback(async(v,N)=>{if(N.kind==="ide"&&N.providerType){await h(v,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await f(v,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[h,f]);return{machineAction:{state:o,message:c},resetMachineAction:p,handleLaunchDetectedIde:h,handleAddWorkspace:b,handleMachineUpgrade:g,handleLaunchWorkspaceProvider:f,handleListSavedSessions:w,handleBrowseDirectory:j,handleOpenRecent:y}}function uv({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:u,setMachineBackTarget:m}){const d=l.useCallback(j=>{o(j.tabKey),i("chat"),n(j)},[n,i,o]),p=l.useCallback(j=>{const y=e.find(v=>v.routeId===j.routeId&&v.streamSource==="native");y&&(o(y.tabKey),i("chat"),n(y))},[e,n,i,o]),h=l.useCallback(()=>{n(t),i("inbox")},[n,t,i]),b=l.useCallback((j,y="inbox")=>{c(j),a(),u("machines"),m(y),i("machine")},[a,m,i,u,c]),g=l.useCallback(j=>{const y=Ms(j);y&&b(y,"chat")},[b]),f=l.useCallback(()=>{a(),i(r)},[r,a,i]),w=l.useCallback(j=>{u(j),i("inbox")},[i,u]);return{openConversation:d,openNativeConversation:p,backFromConversation:h,openMachine:b,openConversationMachine:g,backFromMachine:f,changeMachineSection:w}}function Ks(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function mv(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function pv({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:p,requestedMobileSection:h,onRequestedMobileSectionConsumed:b,onOpenHistory:g,onOpenRemote:f,onStopCli:w,wsStatus:j,isConnected:y,onShowAllHiddenConversations:v,onHideConversation:N,onOpenMeshGraph:k,onOpenNewSession:x,liveSessionInboxState:I,setCliViewModeOverrides:C}){const[M,D]=l.useState(()=>{var oe;return((oe=e[0])==null?void 0:oe.tabKey)||null}),[P,T]=l.useState(()=>e[0]?"chat":"inbox"),[R,O]=l.useState("chats"),[K,S]=l.useState(null),[A,B]=l.useState("inbox"),L=l.useRef([]),$=$r(),F="0.9.82",z=l.useMemo(()=>e.find(oe=>oe.tabKey===M)||e[0]||null,[e,M]),re=l.useMemo(()=>z?r.find(oe=>oe.id===z.routeId):void 0,[r,z]),J=l.useMemo(()=>!z||Ye(z)||!Ze(z)?null:qs(z),[z]),Y=l.useMemo(()=>r.filter(oe=>oe.type==="adhdev-daemon").sort(ei),[r]),se=l.useMemo(()=>Y.find(oe=>oe.id===K)||null,[Y,K]),fe=ma({sendDaemonCommand:a,activeConv:z||void 0,setActionLogs:o,isStandalone:i}),be=dv({sendDaemonCommand:a,navigate:$,ides:r,conversations:e}),X=l.useMemo(()=>e.map(oe=>{const Pe=P==="chat"&&(z==null?void 0:z.tabKey)===oe.tabKey,Ee=da(oe,I,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Pe}),$e=js(oe),He=Zd(oe);return{conversation:oe,timestamp:$e,preview:He,unread:Ee.unread,requiresAction:Ee.requiresAction,isWorking:Ee.isWorking,inboxBucket:Ee.inboxBucket}}),[e,I,P,z]),{markConversationRead:Q}=iv({conversations:e,machineEntries:Y,items:X,selectedConversation:z,selectedTabKey:M,screen:P,liveSessionInboxState:I,sendDaemonCommand:a,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:p,requestedMobileSection:h,onRequestedMobileSectionConsumed:b,setSelectedTabKey:D,setScreen:T,setSelectedMachineId:S,setSection:O,setMachineBackTarget:B,resetMachineAction:be.resetMachineAction}),we=uv({conversations:e,selectedConversation:z,machineBackTarget:A,markConversationRead:Q,resetMachineAction:be.resetMachineAction,setSelectedTabKey:D,setScreen:T,setSelectedMachineId:S,setSection:O,setMachineBackTarget:B}),{isMuted:ve,autoMuteIfCoordinator:xe,toggleTarget:Ne}=C0();l.useEffect(()=>{if(i)for(const oe of X)xe(oe.conversation)},[X,i,xe]);const ae=l.useMemo(()=>_n(X.filter(oe=>oe.requiresAction&&!ve(oe.conversation))),[X,ve]),ge=l.useMemo(()=>_n(X.filter(oe=>oe.unread&&!oe.requiresAction&&!ve(oe.conversation))),[X,ve]),me=l.useMemo(()=>sv(X.filter(oe=>!oe.unread&&!oe.requiresAction&&oe.isWorking),L.current),[X]);l.useEffect(()=>{L.current=me.map(oe=>oe.conversation.tabKey)},[me]);const U=l.useMemo(()=>_n(X.filter(oe=>!oe.unread&&!oe.requiresAction&&!oe.isWorking)),[X]),H=l.useMemo(()=>se?X.filter(oe=>Ms(oe.conversation)===se.id):[],[X,se]),q=l.useMemo(()=>nv(se,r),[r,se]),ne=(se==null?void 0:se.version)||null,E=!!se&&!!ne&&!0&&ne!==F,W=l.useMemo(()=>(se==null?void 0:se.availableProviders)||[],[se]),_=l.useMemo(()=>W.filter(oe=>Ks(oe,"cli")).map(oe=>({type:oe.type,displayName:oe.displayName||oe.type,icon:oe.icon})),[W]),ie=l.useMemo(()=>W.filter(oe=>Ks(oe,"acp")).map(oe=>({type:oe.type,displayName:oe.displayName||oe.type,icon:oe.icon})),[W]),pe=l.useMemo(()=>av(Y,X),[X,Y]),ue=l.useCallback(async oe=>{se&&await be.handleOpenRecent(se.id,oe)},[be,se]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:P==="chat"&&z?s.jsx(Gy,{selectedConversation:z,isAcp:Ye(z),isStandalone:i,selectedIdeEntry:re,actionLogs:n,userName:c,isSendingChat:fe.isSendingChat,sendFeedbackMessage:fe.sendFeedbackMessage,isFocusingAgent:fe.isFocusingAgent,handleModalButton:fe.handleModalButton,handleRelaunch:fe.handleRelaunch,onBack:we.backFromConversation,onOpenNativeConversation:we.openNativeConversation,onOpenMachine:we.openConversationMachine,onOpenHistory:g,onOpenRemote:f,onOpenMeshGraph:k,onStopCli:w,cliViewMode:J,onSetCliViewMode:async oe=>{await Au({conversation:z,mode:oe,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:C})},handleSendChat:fe.handleSendChat,handleForceSendChat:fe.handleForceSendChat,handleFocusAgent:fe.handleFocusAgent}):P==="machine"&&se?s.jsx(tv,{selectedMachineEntry:se,selectedMachineConversations:H,selectedMachineRecentLaunches:q,cliProviders:_,acpProviders:ie,selectedMachineNeedsUpgrade:E,appVersion:F,machineAction:be.machineAction,isStandalone:i,section:R,showBottomNav:A==="inbox",onBack:we.backFromMachine,onSectionChange:we.changeMachineSection,onOpenConversation:we.openConversation,onOpenRecent:ue,onOpenMachineDetails:()=>$(`/machines/${se.id}`),onMachineUpgrade:()=>be.handleMachineUpgrade(se.id),onLaunchDetectedIde:(oe,Pe)=>be.handleLaunchDetectedIde(se.id,oe,Pe),onAddWorkspace:(oe,Pe)=>be.handleAddWorkspace(se.id,oe,Pe),onBrowseDirectory:oe=>be.handleBrowseDirectory(se.id,oe),onLaunchWorkspaceProvider:(oe,Pe,Ee)=>be.handleLaunchWorkspaceProvider(se.id,oe,Pe,Ee),onListSavedSessions:oe=>be.handleListSavedSessions(se.id,oe)}):s.jsx(Yy,{section:R,attentionItems:ae,unreadItems:ge,workingItems:me,completedItems:U,hiddenConversations:t,machineCards:pe,getAvatarText:mv,actionLogs:n,sendDaemonCommand:a,onOpenConversation:we.openConversation,onShowAllHidden:v,onHideConversation:N,onOpenMeshGraph:k,onOpenNewSession:x,onOpenMachine:we.openMachine,onOpenSettings:()=>$("/settings"),onSectionChange:O,wsStatus:j,isConnected:y,isStandalone:i,isConversationMuted:i?ve:void 0,onToggleMuteConversation:i?Ne:void 0})})}function Ua(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function hv({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const i=l.useRef(0),[c,u]=l.useState(!1),[m,d]=l.useState(null),p=l.useCallback(()=>{i.current=0,u(!1),d(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",p),window.addEventListener("drop",p),()=>{window.removeEventListener("dragend",p),window.removeEventListener("drop",p)}),[p]);const h=l.useCallback(w=>{w.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,u(!0))},[]),b=l.useCallback(w=>{if(!w.dataTransfer.types.includes("text/tab-key"))return;if(w.preventDefault(),!Ua(t,r)){d("merge");return}const j=w.currentTarget.getBoundingClientRect(),y=w.clientX-j.left,v=j.width/3;y<v?d("split-left"):y>v*2?d("split-right"):d("merge")},[t,r]),g=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,u(!1),d(null))},[]),f=l.useCallback(w=>{i.current=0,u(!1);const j=w.dataTransfer.getData("text/tab-key"),y=j?e.some(N=>N.tabKey===j):!1,v=m;if(d(null),o(),!!j){if(w.preventDefault(),v==="split-left"&&Ua(t,r)){r==null||r(j,"split-left");return}if(v==="split-right"&&Ua(t,r)){r==null||r(j,"split-right");return}if(y){a(j);return}n==null||n(j)}},[e,m,t,r,n,a,o]);return{dragOver:c,dropAction:m,resetDragState:p,handleDragEnter:h,handleDragOver:b,handleDragLeave:g,handleDrop:f}}function fv(e,t){const r=new Set(t.map(o=>o.tabKey)),n=e.filter(o=>r.has(o)),a=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...n,...a]}function xv({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,i]=l.useState(t??null),[c,u]=l.useState(r??[]),[m,d]=l.useState(null),p=l.useRef(null),h=l.useRef(null),b=l.useRef(n),g=l.useRef(a);l.useEffect(()=>{b.current=n},[n]),l.useEffect(()=>{g.current=a},[a]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{u(I=>{const C=fv(I,e);return C.length===I.length&&C.every((M,D)=>M===I[D])?I:C})},[e]);const f=l.useMemo(()=>{const I=m??c;if(I.length===0)return e;const C=new Map(I.map((M,D)=>[M,D]));return[...e].sort((M,D)=>{const P=C.get(M.tabKey)??999,T=C.get(D.tabKey)??999;return P-T})},[e,m,c]);l.useEffect(()=>{var C,M;if(f.length===0){o!==null&&(i(null),(C=b.current)==null||C.call(b,null));return}if(o&&f.some(D=>D.tabKey===o))return;const I=f[0].tabKey;I!==o&&(i(I),(M=b.current)==null||M.call(b,I))},[f,o]);const w=l.useMemo(()=>f.find(I=>I.tabKey===o),[f,o]),j=l.useCallback(I=>{var C;i(I),(C=b.current)==null||C.call(b,I)},[]),y=l.useCallback((I,C,M)=>{u(D=>{var O;const P=D.filter(K=>K!==I),T=P.indexOf(C);if(T<0)return D;const R=M==="left"?T:T+1;return P.splice(R,0,I),(O=g.current)==null||O.call(g,P),P}),d(null)},[]),v=l.useCallback((I,C,M)=>{const P=(c.length>0?c:e.map(O=>O.tabKey)).filter(O=>O!==I),T=P.indexOf(C);if(T<0)return;const R=M==="left"?T:T+1;P.splice(R,0,I),p.current=P,d(P)},[c,e]),N=l.useCallback(()=>{var C;const I=p.current;I&&(u(I),(C=g.current)==null||C.call(g,I))},[]),k=l.useCallback(()=>{p.current=null,d(null)},[]),x=l.useCallback(I=>{u(C=>{var D;const M=C.filter(P=>P!==I);return M.push(I),(D=g.current)==null||D.call(g,M),M})},[]);return{activeTabId:o,activeConv:w,sortedConversations:f,previewOrderRef:p,draggingTabRef:h,selectTab:j,handleTabReorder:y,updatePreviewOrder:v,commitPreviewOrder:N,clearPreviewOrder:k,moveTabToEnd:x,setDraggingTabKey:I=>{h.current=I}}}function bv({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 ki({conversationsCount:e,isSplitMode:t,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:o}){if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const i=!r&&!n,c=n&&!!o,u=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",m=n?au:r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can launch sessions with any installed provider.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:u}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),c&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:Ut,"aria-label":Ut,children:[s.jsx(cd,{size:14}),s.jsx("span",{children:Ut})]})}),i&&s.jsx(Uu,{}),i&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const Xu="adhdev-tab-shortcuts";function Qu(){try{return JSON.parse(localStorage.getItem(Xu)||"{}")}catch{return{}}}function Zu({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>Qu()),[c,u]=l.useState(null),m=l.useCallback(p=>{const h=[];return p.metaKey&&h.push(a?"⌘":"Meta"),p.ctrlKey&&h.push("Ctrl"),p.altKey&&h.push(a?"⌥":"Alt"),p.shiftKey&&h.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(h.push(p.key.length===1?p.key.toUpperCase():p.key),h.join("+"))},[a]),d=l.useCallback(p=>{i(p);try{localStorage.setItem(Xu,JSON.stringify(p))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const p=h=>{if(h.preventDefault(),h.stopPropagation(),h.key==="Escape"){u(null);return}const b=m(h);if(!b)return;const g={...o};for(const[f,w]of Object.entries(g))w===b&&delete g[f];g[c]=b,d(g),u(null)};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[e,c,o,d,m]),l.useEffect(()=>{if(!e)return;const p=h=>{if(!(!h.ctrlKey&&!h.metaKey&&!h.altKey)){for(const[b,g]of Object.entries(o))if(t.includes(b)&&m(h)===g){h.preventDefault(),r(),n(b);return}}};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[e,o,t,r,n,m]),{isMac:a,tabShortcuts:o,shortcutListening:c,setShortcutListening:u,saveShortcuts:d}}const Ga=e=>{e.preventDefault()},gv=l.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:u,onSelectTab:m,onConversationActivated:d,onPreviewReorder:p,onReorderTab:h,onCommitPreviewOrder:b,onClearPreviewOrder:g,onDragStateReset:f,onDragTabKeyChange:w,onReceiveTab:j,onOpenContextMenu:y,longPressTimer:v,isGroupActive:N}){const k=Vs(t),x=k.isGenerating?"agent-tab-generating":k.isWaiting?"agent-tab-waiting":"",I=k.isReconnecting,C=Hb(t),M=Wb(t),D=l.useCallback(L=>{c.current=t.tabKey,w(t.tabKey),L.dataTransfer.setData("text/tab-key",t.tabKey),L.dataTransfer.effectAllowed="move"},[t.tabKey,c,w]),P=l.useCallback(()=>{c.current=null,w(null),b(),g(),f()},[c,w,b,g,f]),T=l.useCallback(L=>{const $=c.current;if(!(!$||$===t.tabKey)&&L.dataTransfer.types.includes("text/tab-key")){L.preventDefault(),L.stopPropagation();const F=L.currentTarget.getBoundingClientRect(),z=L.clientX<F.left+F.width/2?"left":"right";p($,t.tabKey,z)}},[t.tabKey,c,p]),R=l.useCallback(L=>{L.preventDefault(),L.stopPropagation();const $=L.dataTransfer.getData("text/tab-key");if($&&$!==t.tabKey){const F=L.currentTarget.getBoundingClientRect(),z=L.clientX<F.left+F.width/2?"left":"right";i.includes($)?h($,t.tabKey,z):j&&j($)}g()},[t.tabKey,i,h,j,g]),O=l.useCallback(L=>{L.stopPropagation(),u(),m(t.tabKey),d(t)},[t,d,u,m]),K=l.useCallback(L=>{L.preventDefault(),y(L.clientX,L.clientY,t.tabKey)},[t.tabKey,y]),S=l.useCallback(L=>{const $=L.touches[0];v.current=setTimeout(()=>{y($.clientX,$.clientY,t.tabKey)},600)},[t.tabKey,v,y]),A=l.useCallback(()=>{v.current&&clearTimeout(v.current)},[v]),B=["adhdev-dockview-tab",x,r&&"is-active",N&&"is-group-active",I&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:B,draggable:!0,onDragStart:D,onDragEnd:P,onDragOver:T,onDrop:R,onClick:O,onContextMenu:K,onTouchStart:S,onTouchEnd:A,onTouchMove:A,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:k.isGenerating?s.jsx("div",{className:"tab-spinner"}):k.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):I?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):k.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),C.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:M,"aria-label":M||C.join(" · "),children:C.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:it(t),children:it(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[I?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:ys(t)}):k.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[ys(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:ys(t)}),s.jsx(Gn,{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 yv({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:u,onReorderTab:m,onCommitPreviewOrder:d,onClearPreviewOrder:p,onDragStateReset:h,onDragTabKeyChange:b,onReceiveTab:g,onHideTab:f,isGroupActive:w,allowTabShortcuts:j=!0}){const[y,v]=l.useState(null),N=l.useRef(null),k=l.useRef(null),x=l.useMemo(()=>e.map(R=>R.tabKey),[e]);Br("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(y==null?void 0:y.tabKey)||null});const{isMac:I,tabShortcuts:C,shortcutListening:M,setShortcutListening:D,saveShortcuts:P}=Zu({enabled:j,sortedTabKeys:e.map(R=>R.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!y)return;const R=O=>{const K=document.querySelector("[data-pane-context-menu]");K&&K.contains(O.target)||v(null)};return window.addEventListener("mousedown",R,!0),()=>window.removeEventListener("mousedown",R,!0)},[y]),l.useEffect(()=>{const R=k.current;if(!R)return;const O=K=>{Math.abs(K.deltaY)<=Math.abs(K.deltaX)||(K.preventDefault(),R.scrollLeft+=K.deltaY)};return R.addEventListener("wheel",O,{passive:!1}),()=>R.removeEventListener("wheel",O)},[]);const T=l.useCallback((R,O,K)=>{v({x:R,y:O,tabKey:K})},[]);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(R=>s.jsx(gv,{conv:R,isActive:t===R.tabKey,isDraggedTab:a.current===R.tabKey,isTaskCompleteUnread:n.has(R.tabKey),shortcut:j?C[R.tabKey]:void 0,conversationKeys:x,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:u,onReorderTab:m,onCommitPreviewOrder:d,onClearPreviewOrder:p,onDragStateReset:h,onDragTabKeyChange:b,onReceiveTab:g,onOpenContextMenu:T,longPressTimer:N,isGroupActive:w},R.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),y&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:y.x,top:y.y},children:[j&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:Ga,onClick:R=>{R.stopPropagation(),D(y.tabKey),v(null)},children:["⌨ ",C[y.tabKey]?`Change shortcut (${C[y.tabKey]})`:"Set shortcut"]}),C[y.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:Ga,onClick:()=>{const R={...C};delete R[y.tabKey],P(R),v(null)},children:"✕ Remove shortcut"})]}),f&&s.jsxs(s.Fragment,{children:[j&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:Ga,onClick:()=>{f(y.tabKey),v(null)},children:"🚫 Hide from Dashboard"})]})]}),j&&M&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>D(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:R=>R.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",I?"⌘+1":"Ctrl+1",", ",I?"⌥+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 vv({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,userName:u,groupIndex:m,onFocus:d,isSplitMode:p,numGroups:h,onMoveTab:b,onReceiveTab:g,style:f,onActiveTabChange:w,initialActiveTabId:j,initialTabOrder:y,onTabOrderChange:v,onHideTab:N,isFocused:k,allowTabShortcuts:x=!0,onOpenNewSession:I,liveSessionInboxState:C}){const{sendCommand:M}=lt(),D=l.useRef(null),{activeTabId:P,activeConv:T,sortedConversations:R,draggingTabRef:O,selectTab:K,handleTabReorder:S,updatePreviewOrder:A,commitPreviewOrder:B,clearPreviewOrder:L,moveTabToEnd:$,setDraggingTabKey:F}=xv({conversations:e,initialActiveTabId:j,initialTabOrder:y,onActiveTabChange:w,onTabOrderChange:v}),z=ma({sendDaemonCommand:a,activeConv:T,setActionLogs:o,isStandalone:i}),{dragOver:re,dropAction:J,resetDragState:Y,handleDragEnter:se,handleDragOver:fe,handleDragLeave:be,handleDrop:X}=hv({conversations:e,numGroups:h,onMoveTab:b,onReceiveTab:g,onOwnTabDrop:$,onClearPreviewOrder:L}),Q=T&&!Ye(T)&&qs(T)==="terminal",we=l.useMemo(()=>T?t.find(ae=>ae.id===T.routeId):void 0,[t,T]),ve=l.useMemo(()=>T?n.filter(ae=>ae.routeId===T.tabKey):[],[n,T]),xe=l.useMemo(()=>new Set(R.filter(ae=>wf(ae,C,{isOpenConversation:ae.tabKey===P})).map(ae=>ae.tabKey)),[P,C,R]);Br("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:P,dragOver:re});const Ne=l.useCallback(ae=>{ae.streamSource==="agent-stream"&&ae.agentType&&M(ae.routeId,Fd(),{agentType:ae.agentType,...ae.sessionId&&{targetSessionId:ae.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:re?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(yv,{conversations:R,activeTabId:P,groupIndex:m,numGroups:h,unreadTabKeys:xe,draggingTabRef:O,onFocus:d,onSelectTab:K,onConversationActivated:Ne,onPreviewReorder:A,onReorderTab:S,onCommitPreviewOrder:B,onClearPreviewOrder:L,onDragStateReset:Y,onDragTabKeyChange:F,onMoveTab:b,onReceiveTab:g,onHideTab:N,isGroupActive:k??!1,allowTabShortcuts:x}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:se,onDragOver:fe,onDragLeave:be,onDrop:X,children:[re&&s.jsx(bv,{dropAction:J,canSplit:!!(h<4&&b)}),T?s.jsx(wi,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!Q,ideEntry:we,terminalRef:D,handleModalButton:z.handleModalButton,handleRelaunch:z.handleRelaunch,handleSendChat:z.handleSendChat,handleForceSendChat:z.handleForceSendChat,isSendingChat:z.isSendingChat,sendFeedbackMessage:z.sendFeedbackMessage,handleFocusAgent:z.handleFocusAgent,isFocusingAgent:z.isFocusingAgent,actionLogs:ve,userName:u,isInputActive:!p||!!k}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(ki,{conversationsCount:e.length,isSplitMode:p,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:I})})]})]})}function wv({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:m,isStandalone:d,hasRegisteredMachines:p,userName:h,focusedGroup:b,focusGroup:g,moveTabToGroup:f,splitTabRelative:w,closeGroup:j,handleResizeStart:y,groupActiveTabIds:v,setGroupActiveTab:N,groupTabOrders:k,setGroupTabOrder:x,toggleHiddenTab:I,onOpenNewSession:C,allowTabShortcuts:M=!0,liveSessionInboxState:D}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((P,T)=>{const R=t&&n.length===r?`${n[T]}%`:void 0;return s.jsxs(yt.Fragment,{children:[t&&T>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:O=>y(T-1,O),onDoubleClick:()=>j(T),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(vv,{style:t?{flexBasis:R??`${100/r}%`,flexGrow:R?0:1,flexShrink:R?0:1}:void 0,conversations:P,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:m,isStandalone:d,hasRegisteredMachines:p,userName:h,groupIndex:T,isFocused:t&&b===T,onFocus:()=>g(T),isSplitMode:t,numGroups:r,onMoveTab:(O,K)=>{K==="left"&&T>0?f(O,T-1):K==="right"&&T<r-1?f(O,T+1):K==="split-left"&&r<4?w(O,T,"left"):K==="split-right"&&r<4&&w(O,T,"right")},onReceiveTab:O=>f(O,T),onActiveTabChange:O=>N(T,O),initialActiveTabId:v[T],initialTabOrder:k[T],onTabOrderChange:O=>x(T,O),onHideTab:I,onOpenNewSession:C,allowTabShortcuts:M,liveSessionInboxState:D})]},T)})})}function em({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?pt.onScreenshot("ide-page",(d,p)=>{if(d!==e)return;const h=new FileReader;h.onload=()=>o(h.result),h.readAsDataURL(p)}):void 0,[e]),l.useEffect(()=>{r!=="connected"&&o(null)},[r]),l.useEffect(()=>{var d;return e?((d=pt.onStatus)==null?void 0:d.call(pt,(p,h)=>{p===e&&h!=null&&h.screenshotUsage&&c(h.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const m=e?pt.get(e):null;if(!(!m||r!=="connected"))return n!=="chat"&&t?m.startScreenshots(t):m.stopScreenshots(t),()=>{m.stopScreenshots(t)}},[n,r,t,e]);const u=l.useCallback(async(m,d)=>{const p=e?pt.get(e):null;return!p||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):p.sendInput(m,d,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:i,handleRemoteAction:u}}const tm="adhdev-dashboard-action-shortcuts",jv=1200,kv=[["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 Nv(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function rt(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 sm(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:rt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:rt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:rt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:rt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:rt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:rt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:rt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:rt("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:rt("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:rt("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:rt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:rt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:rt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:rt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:rt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:rt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:rt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:rt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:rt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:rt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:rt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:rt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:rt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:rt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:rt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:rt("toggleCliView",e)}]}function Eo(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function ta(e){const t=Object.fromEntries(sm(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(tm)||"{}"),n={...t,...r};for(const[a,o]of kv)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function rm(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Sv({enabled:e=!0,onTrigger:t}){const r=Nv(),[n,a]=l.useState(()=>ta(r)),[o,i]=l.useState(null),[c,u]=l.useState([]),m=l.useRef({parts:[],timer:null}),d=l.useCallback(f=>{const w=[];return f.metaKey&&w.push(r?"⌘":"Meta"),f.ctrlKey&&w.push("Ctrl"),f.altKey&&w.push(r?"⌥":"Alt"),f.shiftKey&&f.key.length!==1&&w.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(w.push(rm(f.key)),w.join("+"))},[r]),p=l.useCallback(f=>{a(f);try{localStorage.setItem(tm,JSON.stringify(f))}catch{}},[]);l.useEffect(()=>{const f=ta(r),w=Object.entries(n),j=Object.entries(f);w.length===j.length&&w.every(([y,v])=>f[y]===v)||p(f)},[n,r,p]);const h=l.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),b=l.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},jv))},[]);l.useEffect(()=>{if(!o)return;const f=w=>{if(w.preventDefault(),w.stopPropagation(),w.key==="Escape"){i(null),u([]);return}const j=d(w);if(!j)return;const v=!(w.metaKey||w.ctrlKey||w.altKey)&&/^[A-Z0-9]$/.test(j);if(c.length===0&&v){u([j]);return}const k=[...c,j].slice(0,2).join(" "),x={...n};for(const[I,C]of Object.entries(x))C===k&&delete x[I];x[o]=k,p(x),i(null),u([])};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[n,d,p,o,c]),l.useEffect(()=>{if(!e||o)return;const f=w=>{if(w.defaultPrevented)return;const j=d(w);if(!j)return;const y=w.metaKey||w.ctrlKey||w.altKey;if(Eo(w.target))return;const v=m.current.parts,N=y?[j]:[...v.slice(-1),j].slice(-2),k=N.join(" "),x=N[N.length-1],I=Object.entries(n).filter(([,T])=>!!T),C=I.find(([,T])=>T===k);if(C){w.preventDefault(),h(),t(C[0]);return}if(I.some(([,T])=>T.startsWith(`${k} `))){w.preventDefault(),m.current.parts=N,b();return}const D=I.find(([,T])=>T===x);if(D){w.preventDefault(),h(),t(D[0]);return}if(I.some(([,T])=>T.startsWith(`${x} `))){w.preventDefault(),m.current.parts=[x],b();return}h()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[n,b,e,d,t,h,o]),l.useEffect(()=>()=>h(),[h]);const g=l.useMemo(()=>sm(r),[r]);return{isMac:r,actionDefinitions:g,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:u,saveShortcuts:p}}function Cv({isTabInPopout:e,isTabFloating:t,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(t&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:n.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:n.dockActiveTab})):t?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:n.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:n.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:n.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:r?`Change shortcut (${r})`:"Set shortcut",shortcut:n.setActiveTabShortcut}),r&&a.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),a.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:n.hideCurrentTab,tone:"muted"}),a}function nm(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function sc({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!nm(n):!0}function Iv({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:nm(r)}const am=1e3,Mv=4;function rc(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function nc(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function Av({detachDelayMs:e=am,stillnessThresholdPx:t=Mv,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,u=null,m=null,d=!1;const p=()=>{m!=null&&(a(m),m=null)},h=()=>{p(),c=null},b=()=>{p(),o=null,i=null,c=null,u=null,d=!1},g=()=>{!o||!c||!u||d||m!=null||(m=n(()=>{m=null,!(!o||!c||!u||d)&&rc(u,i)&&(nc(c,u,t)||(d=!0,r({panelId:o,clientX:u.clientX,clientY:u.clientY})))},e))},f=j=>{if(!(!o||d)){if(!rc(j,i)){u={clientX:j.clientX,clientY:j.clientY},h();return}(!c||nc(c,j,t))&&(p(),c={clientX:j.clientX,clientY:j.clientY}),u={clientX:j.clientX,clientY:j.clientY},g()}},w=j=>{!o||d||(j&&(u={clientX:j.clientX,clientY:j.clientY}),h())};return{startDrag:j=>{p(),o=j.panelId,i=j.selfPanelBounds??null,c=null,u={clientX:j.clientX,clientY:j.clientY},d=!1},markSelfPanel:f,markNonSelfPanel:w,markNoDropTarget:w,markDockTarget:w,endDrag:b,isDragging:()=>o!=null,hasDetached:()=>d,dispose:b}}function Tv(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function gn(e){return e.isActive}function ac(e){return e.isVisible}const om=l.createContext(null);function xa(){const e=l.useContext(om);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Ln(e){return it(e)||e.tabKey}function _v(e){return`remote:${e}`}function $t(e){return e.startsWith("remote:")}function oc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Lv(e){e.preventDefault()}function Va(e){var n;const t=e==null?void 0:e.defaultView;if(!t)return;const r=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{t.focus(),r(e==null?void 0:e.body),r(e==null?void 0:e.documentElement),(n=t.requestAnimationFrame)==null||n.call(t,()=>{try{t.focus(),r(e==null?void 0:e.body)}catch{}})}catch{}}function qa(e,t){e.classList.remove(fo.className,xo.className),e.classList.add(t==="light"?fo.className:xo.className)}function ic(e){return e?Array.from(new Set(e.groups.map(t=>{var r,n;return(n=(r=t.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(t=>!!t&&t!==window))):[]}function Pv(e){const[,t]=l.useState(0);l.useEffect(()=>{const r=()=>t(a=>a+1),n=[e.api.onDidActiveGroupChange(r),e.api.onDidTitleChange(r),e.api.onDidGroupChange(r),e.containerApi.onDidActivePanelChange(r)];return()=>{for(const a of n)a.dispose()}},[e.api,e.containerApi])}function Rv(e,t,r){var i;const n=[t];let a;for(const c of n){let u;for(const m of c){const d=e.addPanel({id:m.tabKey,component:"conversation",title:Ln(m),params:{kind:"conversation",tabKey:m.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=d.id)}a=u??a}return r??((i=t[0])==null?void 0:i.tabKey)??null}function lc(e,t){const r=new Set(t.map(a=>a.tabKey)),n=new Map;for(const a of t)n.set(a.tabKey,(n.get(a.tabKey)||0)+1);for(const a of[...e.panels])$t(a.id)||r.has(a.id)||e.removePanel(a);for(const a of t){const o=e.getPanel(a.tabKey);if(o){(n.get(a.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:a.tabKey,daemonId:a.daemonId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,panelId:o.id}),o.update({params:{tabKey:a.tabKey}}),o.title!==Ln(a)&&o.api.setTitle(Ln(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:Ln(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 cc(e,t,r){var u,m;const n=r?_v(r):null;for(const d of[...e.panels])$t(d.id)&&(!n||d.id!==n)&&e.removePanel(d);if(!r||!n)return;const a=Ft(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),i=su(a);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(a==null?void 0:a.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((m=e.panels.find(d=>!$t(d.id)))==null?void 0:m.id);e.addPanel({id:n,component:"remote",title:i,params:{kind:"remote",routeId:r},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function Dv({params:e,api:t}){var b;const r=xa(),n=l.useRef(null),[a,o]=l.useState(()=>gn(t)),[i,c]=l.useState(()=>ac(t)),u=r.conversationsByTabKey.get(e.tabKey),m=ma({sendDaemonCommand:r.sendDaemonCommand,activeConv:u,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});l.useEffect(()=>{o(gn(t)),c(ac(t));const g=[t.onDidActiveChange(f=>o(f.isActive)),t.onDidActiveGroupChange(f=>{if(!gn(t)&&!f.isActive){o(!1);return}o(gn(t))}),t.onDidVisibilityChange(f=>c(f.isVisible))];return()=>{for(const f of g)f.dispose()}},[t]);const d=l.useMemo(()=>u?r.ides.find(g=>g.id===u.routeId):void 0,[r.ides,u]),p=l.useMemo(()=>u?r.actionLogs.filter(g=>g.routeId===u.tabKey):[],[r.actionLogs,u]);if(!u)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(ki,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const h=!Ye(u)&&qs(u)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(wi,{activeConv:u,clearToken:r.clearedTabs[u.tabKey]||0,isCliTerminal:h,ideEntry:d,terminalRef:n,handleModalButton:m.handleModalButton,handleRelaunch:m.handleRelaunch,handleSendChat:m.handleSendChat,handleForceSendChat:m.handleForceSendChat,isSendingChat:m.isSendingChat,handleFocusAgent:m.handleFocusAgent,isFocusingAgent:m.isFocusingAgent,actionLogs:p,userName:r.userName,scrollToBottomRequestNonce:((b=r.scrollToBottomRequest)==null?void 0:b.tabKey)===u.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:i})})}function $v({params:e}){var u;const t=xa(),r=l.useMemo(()=>Ft([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=l.useMemo(()=>t.ides.find(m=>m.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((u=r==null?void 0:r.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=em({doId:a,targetSessionId:r?Bd(r):(n==null?void 0:n.sessionId)||(n==null?void 0:n.instanceId),connState:(r==null?void 0:r.connectionState)||"new",viewMode:"remote"});return r?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(yd,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:o,screenshotUsage:i,transportType:r.transport,onAction:c})}):s.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function Ev(){const e=xa();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(ki,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function Bv(e){var y,v;Pv(e);const t=xa(),r=l.useCallback(N=>{"button"in N&&N.button!==0||e.api.setActive()},[e.api]),n=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),a=n==null?void 0:n.sessionId,o=l.useCallback(N=>Cb(N),[]),i=l.useCallback(()=>Sb(a),[a]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const N=Ft([...t.conversationsByTabKey.values()],e.params.routeId),k=((y=e.api.group.activePanel)==null?void 0:y.id)===e.api.id,x=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${k?" is-active":""}${x?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(N==null?void 0:N.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:N!=null&&N.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:N.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const u=t.conversationsByTabKey.get(e.params.tabKey);if(!u)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const m=((v=e.api.group.activePanel)==null?void 0:v.id)===e.api.id,d=e.api.isGroupActive,p=da(u,t.liveSessionInboxState,{isOpenConversation:m}),h=p.isReconnecting,b=p.isConnecting,g=p.isGenerating||c,f=p.isWaiting,w=p.unread,j=t.tabShortcuts[u.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${m?" is-active":""}${d?" is-group-active":""}${h?" is-reconnecting":""}`,title:it(u),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:N=>{var k;N.preventDefault(),r(N),t.openTabContextMenu({x:N.clientX,y:N.clientY,tabKey:u.tabKey,sourceDocument:((k=N.target)==null?void 0:k.ownerDocument)??document})},children:[w&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:g?s.jsx("div",{className:"tab-spinner"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):h?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):b?s.jsx("div",{className:"tab-connecting-spinner"}):u.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:it(u)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:h?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ys(u)}):b?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ys(u)}):s.jsx("span",{children:ys(u)})})]}),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 Fv({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:u,userName:m,toggleHiddenTab:d,actionShortcuts:p,registerActionHandlers:h,onActiveTabChange:b,onOpenNewSession:g,onRequestScrollToBottom:f,requestedActiveTabKey:w,requestedRemoteIdeId:j,onRequestedActiveTabConsumed:y,scrollToBottomRequest:v,liveSessionInboxState:N,layoutProfile:k}){var Qe,Ge,bt;const{theme:x}=Ys(),{sendCommand:I}=lt(),C=l.useRef(null),M=l.useRef(null),D=l.useRef(null),P=l.useRef(!1),T=l.useRef(!1),R=l.useRef(!1),O=l.useRef(null),K=l.useRef([]),[S,A]=l.useState(null),[B,L]=l.useState(0),$=l.useRef(typeof window>"u"?{}:ry(k)),F=l.useMemo(()=>new Map(e.map(V=>[V.tabKey,V])),[e]),z=l.useMemo(()=>{const V=C.current;return V?V.groups.some(G=>{try{const te=G.model.location.type;return te!=="floating"&&te!=="popout"?!1:G.panels.some(de=>F.has(de.id))}catch{return!1}}):!1},[F,B,e]),re=l.useCallback(()=>{var V;(V=C.current)==null||V.focus()},[]),J=l.useCallback((V,G)=>{f==null||f(V,G)},[f]),Y=l.useCallback(V=>{const G=document,te=V.document;for(const ee of G.querySelectorAll('link[rel="stylesheet"]')){const he=te.createElement("link");he.rel="stylesheet",he.href=ee.href,ee.crossOrigin&&(he.crossOrigin=ee.crossOrigin),te.head.appendChild(he)}for(const ee of G.querySelectorAll("style")){const he=te.createElement("style");he.textContent=ee.textContent,te.head.appendChild(he)}const de=[];for(const ee of G.styleSheets)try{for(const he of ee.cssRules)he instanceof CSSStyleRule&&(he.selectorText===":root"||he.selectorText==="html")&&de.push(he.cssText)}catch{}if(de.length>0){const ee=te.createElement("style");ee.textContent=de.join(`
63
+ `),te.head.appendChild(ee)}const ye=G.documentElement.getAttribute("data-theme");ye&&te.documentElement.setAttribute("data-theme",ye),te.documentElement.style.colorScheme=ye==="light"?"light":"dark",te.body.className=G.body.className;const je=G.documentElement.getAttribute("style");je&&te.documentElement.setAttribute("style",je);const Z=te.getElementById("dv-popout-window");Z instanceof HTMLElement&&(Z.classList.add("adhdev-dockview"),qa(Z,x))},[x]),se=l.useCallback(()=>{var G;const V=C.current;if(V)for(const te of V.groups)try{const de=(G=te.element)==null?void 0:G.ownerDocument;if(!de||de===document)continue;const ye=de.getElementById("dv-popout-window");ye instanceof HTMLElement&&(ye.classList.add("adhdev-dockview"),qa(ye,x));const je=document.documentElement.getAttribute("data-theme");je&&de.documentElement.setAttribute("data-theme",je),de.documentElement.style.colorScheme=je==="light"?"light":"dark",de.body.className=document.body.className;const Z=document.documentElement.getAttribute("style");Z?de.documentElement.setAttribute("style",Z):de.documentElement.removeAttribute("style")}catch{}},[x]),fe=l.useCallback(V=>{const G=C.current;if(!G)return;const te=G.getPanel(V);te&&G.addPopoutGroup(te,{popoutUrl:"/popout.html",onDidOpen:({window:de})=>{Y(de),ge();const ye=F.get(V);de.document.title=ye?`${it(ye)} — ADHDev`:"ADHDev — Popout"}})},[F,Y]),be=l.useCallback(V=>{const G=C.current,te=G==null?void 0:G.getPanel(V);if(!G||!te)return;const de=G.groups.filter(ye=>{var je;try{return((je=ye.element)==null?void 0:je.ownerDocument)===document}catch{return!0}});de.length>0?te.api.moveTo({group:de[0],position:"center"}):te.api.moveTo({position:"center"}),te.api.setActive()},[]),X=l.useCallback(V=>{var de;const G=C.current;if(!G)return!1;const te=G.getPanel(V);if(!te)return!1;try{return((de=te.group.element)==null?void 0:de.ownerDocument)!==document}catch{return!1}},[]),Q=l.useCallback(V=>{X(V)&&be(V),d(V)},[X,be,d]),we=l.useCallback(V=>{const G=C.current,te=G==null?void 0:G.getPanel(V);!G||!te||G.addFloatingGroup(te,{width:600,height:500})},[]),ve=l.useCallback(V=>{var te;const G=(te=C.current)==null?void 0:te.getPanel(V);if(!G)return!1;try{return G.group.model.location.type==="floating"}catch{return!1}},[]),xe=l.useCallback(()=>{var G,te;const V=(te=(G=C.current)==null?void 0:G.activePanel)==null?void 0:te.id;return!V||$t(V)?null:F.has(V)?V:null},[F]),Ne=l.useCallback(V=>{const G=C.current,te=G==null?void 0:G.getPanel(V);if(!G||!te)return;const de=G.groups.filter(ye=>{try{return ye.model.location.type==="grid"}catch{return!0}});de.length>0?te.api.moveTo({group:de[0],position:"center"}):te.api.moveTo({position:"center"}),te.api.setActive()},[]),ae=l.useCallback(()=>{var je;const V=C.current;if(!V)return;const te=V.groups.filter(Z=>{var ee;try{return((ee=Z.element)==null?void 0:ee.ownerDocument)===document&&Z.model.location.type==="grid"}catch{return!1}})[0]||null,de=[...V.panels];for(const Z of de){const ee=(je=Z.group.element)==null?void 0:je.ownerDocument,he=Z.group.model.location.type;ee===document&&he==="grid"||(te&&te.id!==Z.group.id?Z.api.moveTo({group:te,position:"center"}):Z.api.moveTo({position:"center"}))}const ye=V.activePanel;ye&&(ye.group.model.openPanel(ye),ye.api.setActive()),Va(document)},[]),ge=l.useCallback(()=>{var G,te;const V=C.current;if(V)for(const de of V.groups){const ye=(G=de.element)==null?void 0:G.ownerDocument;if(!ye||ye===document)continue;const je=ye.getElementById("dv-popout-window");if(!(je instanceof HTMLElement))continue;let Z=null,ee=ye.title||"ADHDev",he="Popout workspace";const Ce=de.activePanel;if(Ce)if(Z=Ce.id,$t(Ce.id)){const Ae=((te=Ce.params)==null?void 0:te.routeId)||Ce.id.slice(7),We=Ft([...F.values()],Ae);ee=su(We),he=We!=null&&We.machineName?`Remote view · ${We.machineName}`:"Remote view"}else{const Ae=F.get(Ce.id);ee=Ae?it(Ae):Ce.title||Ce.id,he=Ae?ys(Ae):"Dockview panel"}ye.title=`${ee} — ADHDev`;const Te=Array.from(ye.querySelectorAll("#adhdev-popout-header"));for(const Ae of Te)Ae.remove();const Ie=ye.createElement("div");Ie.id="adhdev-popout-header",ye.body.appendChild(Ie),Ie.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(";")),Ie.innerHTML=`
64
+ <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
65
+ <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
66
+ <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${oc(ee)}</div>
67
+ <div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${oc(he)}</div>
68
+ </div>
69
+ <div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
70
+ <button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
71
+ <button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
72
+ </div>
73
+ `,je.style.top="52px",je.style.height="calc(100% - 52px)";const Le=Ie.querySelector("[data-adhdev-popout-focus]");Le&&(Le.onclick=()=>{window.focus()});const Be=Ie.querySelector("[data-adhdev-popout-dock]");Be&&(Be.disabled=!Z,Be.style.opacity=Z?"1":"0.5",Be.style.cursor=Z?"pointer":"default",Be.onclick=()=>{var Ae;Z&&be(Z),(Ae=ye.defaultView)==null||Ae.focus()})}},[F,be]),me=l.useCallback(V=>{var de;const G=C.current,te=G==null?void 0:G.getPanel(V);if(!(!G||!te)){te.group.model.openPanel(te),te.api.setActive(),J(V,"dockview-shortcut");try{const ye=te.group.model.location;ye.type==="popout"?ye.getWindow().focus():Va((de=te.group.element)==null?void 0:de.ownerDocument)}catch{}}},[J]),U=l.useCallback(V=>{const G=C.current,te=G==null?void 0:G.activePanel,de=(G==null?void 0:G.activeGroup)||(te==null?void 0:te.group);if(!G||!te||!de)return;const ye=de.panels||[];if(ye.length<=1)return;const je=ye.findIndex(he=>he.id===te.id);if(je<0)return;const Z=(je+V+ye.length)%ye.length,ee=ye[Z];ee&&(ee.group.model.openPanel(ee),ee.api.setActive(),$t(ee.id)||J(ee.id,"dockview-shortcut"))},[J]),H=l.useCallback(V=>{var Le;const G=C.current,te=(G==null?void 0:G.activeGroup)||((Le=G==null?void 0:G.activePanel)==null?void 0:Le.group);if(!G||!te)return;const de=G.groups||[],ye=de.find(Be=>Be.id===te.id);if(!ye)return;const je=ye.element.getBoundingClientRect(),Z=je.left+je.width/2,ee=je.top+je.height/2,he=(Be,Ae,We,qe)=>Math.max(0,Math.min(Ae,qe)-Math.max(Be,We)),Ce=Be=>{const Ae=Be.element.getBoundingClientRect(),We=Ae.left+Ae.width/2,qe=Ae.top+Ae.height/2;let mt=0,gt=0,ht=0,ot=!1;if(V==="left"?(ot=We<Z,mt=Math.max(0,je.left-Ae.right),gt=Math.abs(qe-ee),ht=he(je.top,je.bottom,Ae.top,Ae.bottom)):V==="right"?(ot=We>Z,mt=Math.max(0,Ae.left-je.right),gt=Math.abs(qe-ee),ht=he(je.top,je.bottom,Ae.top,Ae.bottom)):V==="above"?(ot=qe<ee,mt=Math.max(0,je.top-Ae.bottom),gt=Math.abs(We-Z),ht=he(je.left,je.right,Ae.left,Ae.right)):(ot=qe>ee,mt=Math.max(0,Ae.top-je.bottom),gt=Math.abs(We-Z),ht=he(je.left,je.right,Ae.left,Ae.right)),!ot)return Number.POSITIVE_INFINITY;const ze=ht>0?0:120;return mt*3+gt+ze};let Te=null,Ie=Number.POSITIVE_INFINITY;for(const Be of de){if(Be.id===ye.id)continue;const Ae=Ce(Be);Number.isFinite(Ae)&&(Ae>=Ie||(Ie=Ae,Te=Be))}return Te||void 0},[]),q=l.useCallback(V=>{var de;const G=H(V);if(!G)return;const te=G.activePanel||G.panels[0];te&&(G.model.openPanel(te),te.api.setActive(),$t(te.id)||J(te.id,"dockview-focus"),Va((de=G.element)==null?void 0:de.ownerDocument))},[H,J]),ne=l.useCallback((V,G)=>{const te=C.current,de=te==null?void 0:te.activePanel,ye=(te==null?void 0:te.activeGroup)||(de==null?void 0:de.group);if(!te||!de||!ye)return;let je=H(V);!je&&(G!=null&&G.createGroupIfMissing)&&(je=te.addGroup({referenceGroup:ye,direction:V})),je&&(de.api.moveTo({group:je,position:"center"}),de.group.model.openPanel(de),de.api.setActive(),$t(de.id)||J(de.id,G!=null&&G.createGroupIfMissing?"dockview-split":"dockview-move"))},[H,J]),{isMac:E,tabShortcuts:W,shortcutListening:_,setShortcutListening:ie,saveShortcuts:pe}=Zu({sortedTabKeys:e.map(V=>V.tabKey),onFocus:re,onSelectTab:me}),ue=l.useCallback(()=>{var te;const V=C.current;if(!V)return;const G=V.activePanel;if(G){if($t(G.id)){const de=((te=G.params)==null?void 0:te.routeId)||G.id.slice(7),ye=Ft(e,de);ye!=null&&ye.tabKey&&ie(ye.tabKey);return}F.has(G.id)&&ie(G.id)}},[F,me,ie,e]),oe=l.useCallback(V=>{const G=[];return V.metaKey&&G.push(E?"⌘":"Meta"),V.ctrlKey&&G.push("Ctrl"),V.altKey&&G.push(E?"⌥":"Alt"),V.shiftKey&&V.key.length!==1&&G.push(E?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(V.key)?null:(G.push(rm(V.key)),G.join("+"))},[E]),Pe=l.useCallback(V=>{var G,te;switch(V){case"splitActiveTabRight":ne("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":ne("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const de=xe();de&&we(de);return}case"popoutActiveTab":{const de=xe();de&&fe(de);return}case"dockActiveTab":{const de=xe();if(!de)return;X(de)?be(de):ve(de)&&Ne(de);return}case"focusLeftPane":q("left");return;case"focusRightPane":q("right");return;case"focusUpPane":q("above");return;case"focusDownPane":q("below");return;case"moveActiveTabToLeftPane":ne("left");return;case"moveActiveTabToRightPane":ne("right");return;case"moveActiveTabToUpPane":ne("above");return;case"moveActiveTabToDownPane":ne("below");return;case"selectPreviousGroupTab":U(-1);return;case"selectNextGroupTab":U(1);return;case"setActiveTabShortcut":ue();return;case"hideCurrentTab":{const de=(te=(G=C.current)==null?void 0:G.activePanel)==null?void 0:te.id;de&&!$t(de)&&Q(de);return}default:return}},[U,Ne,q,we,xe,Q,ve,X,be,ne,fe,ue]);l.useEffect(()=>{if(!S)return;const V=S.sourceDocument,G=V.defaultView??window,te=de=>{const ye=V.querySelector("[data-dockview-tab-context-menu]");ye&&ye.contains(de.target)||A(null)};return G.addEventListener("mousedown",te,!0),G!==window&&window.addEventListener("mousedown",()=>A(null),!0),()=>{G.removeEventListener("mousedown",te,!0),G!==window&&window.removeEventListener("mousedown",()=>A(null),!0)}},[S]);const Ee=l.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:F,hasDetachedConversationPanels:z,ides:r,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:g,liveSessionInboxState:N,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:Q,userName:m,scrollToBottomRequest:v,tabShortcuts:W,openTabContextMenu:({x:V,y:G,tabKey:te,sourceDocument:de})=>A({x:V,y:G,tabKey:te,sourceDocument:de??document}),popoutTab:fe,moveTabBackToMain:be,isTabInPopout:X,floatTab:we,isTabFloating:ve}),[n,t,F,z,r,i,c,g,N,a,o,Q,m,v,W,fe,be,X,we,ve]),$e=S?Cv({isTabInPopout:X(S.tabKey),isTabFloating:ve(S.tabKey),tabShortcut:W[S.tabKey],actionShortcuts:p}):[],He=l.useCallback(V=>{var de;const G=C.current;if((((de=G==null?void 0:G.activePanel)==null?void 0:de.id)??null)===V.id){V.group.model.openPanel(V);return}V.group.model.openPanel(V),V.api.setActive()},[]),Xe=l.useCallback((V,G="requested-tab")=>{if(!V)return!1;const te=C.current;if(!te)return!1;const de=te.getPanel(V);return de?(He(de),J(V,G),y==null||y(),!0):!1},[He,y,J]),Je=l.useCallback(()=>{if(R.current)return!1;const V=Xe(O.current,"stored-layout-restore");return V&&(R.current=!0),V},[Xe]),nt=l.useCallback(()=>{var G;const V=C.current;V&&sy(k,{activeTabId:((G=V.activePanel)==null?void 0:G.id)??null,layout:V.toJSON()})},[k]),et=l.useCallback(()=>{ny(k,$.current)},[k]),ct=l.useCallback(V=>{var de,ye,je,Z;const G=C.current;if(!G)return{kind:"grid"};const te=G.toJSON();for(const ee of te.floatingGroups||[])if((ye=(de=ee.data)==null?void 0:de.views)!=null&&ye.includes(V)&&ee.position)return{kind:"floating",position:ee.position};for(const ee of te.popoutGroups||[])if((Z=(je=ee.data)==null?void 0:je.views)!=null&&Z.includes(V))return{kind:"popout",position:ee.position,popoutUrl:ee.url};return{kind:"grid"}},[]),st=l.useCallback(V=>{const G=C.current;if(!G)return;const te=G.getPanel(V),de=$.current[V];if(!te||!de||de.kind==="grid")return;if(te.group.model.location.type===de.kind){delete $.current[V],et();return}if(de.kind==="floating"){G.addFloatingGroup(te,{x:de.position.left??24,y:de.position.top??24,width:de.position.width,height:de.position.height}),delete $.current[V],et();return}delete $.current[V],et()},[et]);l.useEffect(()=>(h==null||h({setShortcutForActiveTab:ue,restoreHiddenTabToSavedLocation:st,activateConversationTab:me,resetAllPanelsToMain:ae,activatePreviousTabInGroup:()=>U(-1),activateNextTabInGroup:()=>U(1),floatActiveTab:()=>{const V=xe();V&&we(V)},popoutActiveTab:()=>{const V=xe();V&&fe(V)},dockActiveTab:()=>{const V=xe();V&&(X(V)?be(V):ve(V)&&Ne(V))},splitActiveTabRight:()=>ne("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>ne("below",{createGroupIfMissing:!0}),focusLeftPane:()=>q("left"),focusRightPane:()=>q("right"),focusUpPane:()=>q("above"),focusDownPane:()=>q("below"),moveActiveTabToLeftPane:()=>ne("left"),moveActiveTabToRightPane:()=>ne("right"),moveActiveTabToUpPane:()=>ne("above"),moveActiveTabToDownPane:()=>ne("below")}),()=>h==null?void 0:h(null)),[U,Ne,we,q,xe,ve,X,ne,be,fe,h,ae,st,me,ue]),l.useEffect(()=>()=>{var V;(V=D.current)==null||V.call(D),D.current=null},[]);const ft=l.useCallback(V=>{var te,de;C.current=V.api,(te=D.current)==null||te.call(D),D.current=null;const G=ty(k);if(O.current=(G==null?void 0:G.activeTabId)??null,G!=null&&G.layout&&V.api.fromJSON(G.layout,{reuseExistingPanels:!1}),T.current=sc({hasStoredLayout:!!(G!=null&&G.layout),initialDataLoaded:u,visibleConversationCount:e.length,ides:r}),T.current||(lc(V.api,e),cc(V.api,e,j)),V.api.totalPanels===0&&e.length>0){const ye=Rv(V.api,e,w);if(ye){const je=V.api.getPanel(ye);je&&He(je)}}else!T.current&&!Xe(w)&&Je();if(P.current=!0,V.api.onDidActivePanelChange(ye=>{var Z;if(O.current=(ye==null?void 0:ye.id)??null,R.current=!0,ge(),ye&&$t(ye.id)){const ee=((Z=ye.params)==null?void 0:Z.routeId)||ye.id.slice(7),he=Ft(e,ee);b((he==null?void 0:he.tabKey)??null),nt();return}if(b((ye==null?void 0:ye.id)??null),nt(),!ye)return;const je=F.get(ye.id);(je==null?void 0:je.streamSource)==="agent-stream"&&je.agentType&&I(je.routeId,Fd(),{agentType:je.agentType,...je.sessionId&&{targetSessionId:je.sessionId}}).catch(()=>{})}),V.api.onDidLayoutChange(()=>{nt(),ge(),L(ye=>ye+1)}),Tv()){const ye=Ie=>({clientX:Ie.clientX,clientY:Ie.clientY}),je=Ie=>{const Le=Ie==null?void 0:Ie.getBoundingClientRect();return Le?{left:Le.left,right:Le.right,top:Le.top,bottom:Le.bottom}:null},Z=Ie=>{var Be;const Le=(Be=M.current)==null?void 0:Be.getBoundingClientRect();return Le?Ie.clientX<Le.left||Ie.clientX>Le.right||Ie.clientY<Le.top||Ie.clientY>Le.bottom:!1},ee=Av({detachDelayMs:am,onDetach:({panelId:Ie,clientX:Le,clientY:Be})=>{var ht,ot;const Ae=V.api.getPanel(Ie);if(!Ae)return;try{if(Ae.group.model.location.type!=="grid")return}catch{return}const We=(ht=M.current)==null?void 0:ht.getBoundingClientRect(),qe=(ot=Ae.group.element)==null?void 0:ot.getBoundingClientRect(),mt=Math.round(Math.min(Math.max((qe==null?void 0:qe.width)??600,360),720)),gt=Math.round(Math.min(Math.max((qe==null?void 0:qe.height)??500,260),640));V.api.addFloatingGroup(Ae,{x:We?Math.max(0,Le-We.left-32):void 0,y:We?Math.max(0,Be-We.top-18):void 0,width:mt,height:gt}),Ae.api.setActive(),nt(),ge(),L(ze=>ze+1)}}),he=[V.api.onWillDragPanel(Ie=>{if(!(Ie.nativeEvent.defaultPrevented||Ie.nativeEvent.shiftKey)){try{if(Ie.panel.group.model.location.type!=="grid")return}catch{return}ee.startDrag({panelId:Ie.panel.id,selfPanelBounds:je(Ie.panel.group.element),...ye(Ie.nativeEvent)})}}),V.api.onWillShowOverlay(Ie=>{if(ee.hasDetached()){Ie.preventDefault();return}ee.markDockTarget(ye(Ie.nativeEvent))}),V.api.onWillDrop(Ie=>{if(ee.hasDetached()){Ie.preventDefault(),ee.endDrag();return}ee.markDockTarget(ye(Ie.nativeEvent))}),V.api.onDidDrop(()=>ee.endDrag()),V.api.onUnhandledDragOverEvent(Ie=>{ee.isDragging()&&ee.markSelfPanel(ye(Ie.nativeEvent))})],Ce=Ie=>{if(!ee.isDragging())return;const Le=ye(Ie);Z(Le)&&ee.markNonSelfPanel(Le)},Te=()=>ee.endDrag();window.addEventListener("dragover",Ce,!0),window.addEventListener("drop",Te,!0),window.addEventListener("dragend",Te,!0),D.current=()=>{ee.dispose();for(const Ie of he)Ie.dispose();window.removeEventListener("dragover",Ce,!0),window.removeEventListener("drop",Te,!0),window.removeEventListener("dragend",Te,!0)}}V.api.onDidAddGroup(ye=>{requestAnimationFrame(()=>{var je,Z;try{const ee=(je=ye.element)==null?void 0:je.ownerDocument;if(!ee||ee===document)return;(Z=ee.getElementById("dv-popout-window"))==null||Z.classList.add("adhdev-dockview");const he=document.documentElement.getAttribute("data-theme");he&&ee.documentElement.setAttribute("data-theme",he),ee.body.className=document.body.className;const Ce=document.documentElement.getAttribute("style");Ce&&ee.documentElement.setAttribute("style",Ce)}catch{}ge(),L(ee=>ee+1)})}),b(((de=V.api.activePanel)==null?void 0:de.id)??null)},[He,Xe,F,r,u,k,b,nt,w,j,I,ge,e]);l.useLayoutEffect(()=>{const V=C.current;if(!V||!P.current||T.current&&sc({hasStoredLayout:!0,initialDataLoaded:u,visibleConversationCount:e.length,ides:r}))return;T.current&&(T.current=!1);const G=K.current,te=new Set(G),de=e.map(Te=>Te.tabKey),ye=new Set(de),je=Iv({previousVisibleConversationCount:G.length,visibleConversationCount:e.length,ides:r});let Z=!1;for(const Te of G)ye.has(Te)||je||($.current[Te]=ct(Te),Z=!0);Z&&et(),je||(lc(V,e),cc(V,e,j));const ee=de.filter(Te=>!te.has(Te));let he=!1;for(const Te of ee){const Ie=V.getPanel(Te),Le=$.current[Te];if(!Ie||!Le||Le.kind==="grid")continue;if(Ie.group.model.location.type===Le.kind){delete $.current[Te],he=!0;continue}if(Le.kind==="floating"){V.addFloatingGroup(Ie,{x:Le.position.left??24,y:Le.position.top??24,width:Le.position.width,height:Le.position.height}),delete $.current[Te],he=!0;continue}}if(he&&et(),K.current=de,w&&Xe(w))return;!V.activePanel&&V.panels[0]&&He(V.panels[0]),!!(V.activePanel&&V.getPanel(V.activePanel.id))||Je()},[He,Xe,Je,r,u,et,ct,w,j,e]),l.useEffect(()=>{P.current&&Xe(w)},[Xe,w]),l.useEffect(()=>{const V=te=>{const de=te.target;if(!de)return;const ye=de.querySelector("[data-tab-key]")||de.closest("[data-tab-key]");if(ye){const je=ye.getAttribute("data-tab-key");if(je&&te.dataTransfer){const Z=de.closest(".dv-tab")||ye.closest(".dv-tab")||ye;te.dataTransfer.effectAllowed="move",te.dataTransfer.setData("text/tab-key",je),Z instanceof HTMLElement&&te.dataTransfer.setDragImage(Z,Math.max(12,Math.round(Z.clientWidth/2)),Math.max(10,Math.round(Z.clientHeight/2)))}}};window.addEventListener("dragstart",V);const G=ic(C.current);for(const te of G)te.addEventListener("dragstart",V);return()=>{window.removeEventListener("dragstart",V);for(const te of G)te.removeEventListener("dragstart",V)}},[B]),l.useEffect(()=>{var G;const V=(G=M.current)==null?void 0:G.querySelector(".adhdev-dockview");V instanceof HTMLElement&&qa(V,x),se(),ge()},[ge,se,x]),l.useEffect(()=>{ge()},[ge]),l.useEffect(()=>{const V=G=>{if(G.defaultPrevented||_)return;const te=oe(G);if(!te)return;const de=G.metaKey||G.ctrlKey||G.altKey;Eo(G.target)&&!de||ta(E).setActiveTabShortcut!==te||(G.preventDefault(),G.stopPropagation(),ue())};return window.addEventListener("keydown",V,!0),()=>window.removeEventListener("keydown",V,!0)},[oe,E,_,ue]),l.useEffect(()=>{const V=M.current;if(!V)return;const G=te=>{var ee,he;if(!te.isTrusted)return;const de=(he=(ee=te.target)==null?void 0:ee.closest)==null?void 0:he.call(ee,".dv-scrollable");if(!de)return;te.preventDefault(),te.stopPropagation();const ye=Math.abs(te.deltaX),je=Math.abs(te.deltaY),Z=ye>je?te.deltaX:te.deltaY;de.dispatchEvent(new WheelEvent("wheel",{deltaY:Z,deltaMode:te.deltaMode,bubbles:!1,cancelable:!0}))};return V.addEventListener("wheel",G,{passive:!1,capture:!0}),()=>V.removeEventListener("wheel",G,{capture:!0})},[]),l.useEffect(()=>{const V=ic(C.current);if(V.length===0)return;const G=V.map(te=>{let de=[],ye=null;const je=()=>{ye!=null&&te.clearTimeout(ye),ye=null,de=[]},Z=()=>{ye!=null&&te.clearTimeout(ye),ye=te.setTimeout(()=>{ye=null,de=[]},1200)},ee=Ce=>{if(!Ce.ctrlKey&&!Ce.metaKey&&!Ce.altKey)return;const Te=oe(Ce);if(!Te)return;const Ie=Qu();for(const[Le,Be]of Object.entries(Ie))if(e.some(Ae=>Ae.tabKey===Le)&&Be===Te){Ce.preventDefault(),me(Le);return}},he=Ce=>{if(Ce.defaultPrevented||_)return;const Te=oe(Ce);if(!Te)return;const Ie=Ce.metaKey||Ce.ctrlKey||Ce.altKey;if(Eo(Ce.target))return;const Le=ta(E),Be=Object.entries(Le).filter(([ze,At])=>!!At&&(ze==="splitActiveTabRight"||ze==="splitActiveTabDown"||ze==="floatActiveTab"||ze==="popoutActiveTab"||ze==="dockActiveTab"||ze==="focusLeftPane"||ze==="focusRightPane"||ze==="focusUpPane"||ze==="focusDownPane"||ze==="moveActiveTabToLeftPane"||ze==="moveActiveTabToRightPane"||ze==="moveActiveTabToUpPane"||ze==="moveActiveTabToDownPane"||ze==="selectPreviousGroupTab"||ze==="selectNextGroupTab"||ze==="setActiveTabShortcut"||ze==="hideCurrentTab")),Ae=Ie?[Te]:[...de.slice(-1),Te].slice(-2),We=Ae.join(" "),qe=Ae[Ae.length-1],mt=Be.find(([,ze])=>ze===We);if(mt){Ce.preventDefault(),je(),Pe(mt[0]);return}if(Be.some(([,ze])=>ze.startsWith(`${We} `))){Ce.preventDefault(),de=Ae,Z();return}const ht=Be.find(([,ze])=>ze===qe);if(ht){Ce.preventDefault(),je(),Pe(ht[0]);return}if(Be.some(([,ze])=>ze.startsWith(`${qe} `))){Ce.preventDefault(),de=[qe],Z();return}je()};return te.addEventListener("keydown",ee),te.addEventListener("keydown",he),()=>{je(),te.removeEventListener("keydown",ee),te.removeEventListener("keydown",he)}});return()=>{for(const te of G)te()}},[oe,E,B,me,_,Pe,e]);const Me=x==="light"?fo:xo,Se=((bt=(Ge=(Qe=C.current)==null?void 0:Qe.activePanel)==null?void 0:Ge.group.element)==null?void 0:bt.ownerDocument)??document;return s.jsxs(om.Provider,{value:Ee,children:[s.jsx("div",{ref:M,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(kp,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:Dv,remote:$v},defaultTabComponent:Bv,watermarkComponent:Ev,onReady:ft,singleTabMode:"default",tabAnimation:"smooth",theme:Me,popoutUrl:"/popout.html"})}),S&&Ir.createPortal(s.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:S.x,top:S.y},children:$e.map(V=>{if(V.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},V.id);let G=s.jsx(Rh,{size:13,className:"shrink-0 opacity-70"}),te=()=>{};switch(V.id){case"dockInWindow":case"dockBackToGrid":G=s.jsx($h,{size:13,className:"shrink-0 opacity-70"}),te=()=>{Ne(S.tabKey),A(null)};break;case"moveBackToMain":G=s.jsx(Ph,{size:13,className:"shrink-0 opacity-70"}),te=()=>{be(S.tabKey),A(null)};break;case"floatAsPanel":G=s.jsx(Dh,{size:13,className:"shrink-0 opacity-70"}),te=()=>{we(S.tabKey),A(null)};break;case"openInNewWindow":G=s.jsx(Lh,{size:13,className:"shrink-0 opacity-70"}),te=()=>{fe(S.tabKey),A(null)};break;case"setShortcut":te=de=>{de.stopPropagation(),ie(S.tabKey),A(null)};break;case"removeShortcut":G=s.jsx(vt,{size:13,className:"shrink-0 opacity-70"}),te=()=>{const de={...W};delete de[S.tabKey],pe(de),A(null)};break;case"hideTab":G=s.jsx(qo,{size:13,className:"shrink-0 opacity-70"}),te=()=>{Q(S.tabKey),A(null)};break}return s.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${V.tone==="muted"?"text-text-muted":""}`,onMouseDown:Lv,onClick:te,children:[G,s.jsx("span",{className:"flex-1 min-w-0",children:V.label}),V.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:V.shortcut}):null]},V.id)})}),S.sourceDocument.body),_&&Ir.createPortal(s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>ie(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:V=>V.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. ",E?"⌘+1":"Ctrl+1",", ",E?"⌥+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"})]})}),Se.body)]})}const im="adhdev-recent-launch-args-v1",Ov=8;function zv(e){return String(e||"").trim().replace(/\s+/g," ")}function lm(e,t){return`${e.trim()}::${t.trim()}`}function cm(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(im)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function Hv(e){if(!(typeof window>"u"))try{window.localStorage.setItem(im,JSON.stringify(e))}catch{}}function Wv(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=cm().byKey[lm(r,n)])==null?void 0:o.items)||[]}function Kv(e,t,r){var d;const n=String(e||"").trim(),a=String(t||"").trim(),o=zv(r);if(!n||!a||!o)return;const i=cm(),c=lm(n,a),u=((d=i.byKey[c])==null?void 0:d.items)||[],m=[o,...u.filter(p=>p!==o)].slice(0,Ov);i.byKey[c]={items:m},Hv(i)}function Uv(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Pn({title:e,description:t,action:r,children:n,className:a="",contentClassName:o=""}){return s.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),t&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:t})]}),r?s.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?s.jsx("div",{className:t||r?`mt-3 ${o}`.trim():o,children:n}):null]})}function Gv({savedSessionsLoading:e,savedSessionsLoaded:t,savedSessionsCount:r=0}){return e?"Refreshing saved history…":t?r>0?`${r} saved ${r===1?"history":"histories"} loaded. Open saved history to choose one.`:"No saved history found yet. New Hermes CLI conversations will appear here after ADHDev captures provider history.":"Start fresh, or open saved history when you want continuity."}function Vv({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:i,onOpenHistory:c,onClearSelection:u}){const m=o?Vu(o):null,d=Gv({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Pn,{title:"Saved history",description:di(),action:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:i,children:t?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:c,children:wg()})]}),children:[m?s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),s.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:m.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:m.providerSessionId}),s.jsx("div",{className:"mt-1",children:m.metaLine}),m.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:m.updatedLabel}),m.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:m.preview})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:u,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:d}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function dm({setup:e,providerName:t,className:r=""}){return e?s.jsxs("div",{className:`rounded-xl border border-accent/25 bg-accent/10 px-4 py-3 text-sm text-text-primary ${r}`,children:[s.jsxs("div",{className:"font-semibold",children:["Manual MCP setup required",t?` for ${t}`:""]}),e.instructions&&s.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:e.instructions}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px] text-text-muted",children:[e.serverName&&s.jsxs("span",{children:["Server: ",s.jsx("code",{children:e.serverName})]}),e.configFormat&&s.jsxs("span",{children:["Format: ",s.jsx("code",{children:e.configFormat})]}),e.configPathCommand&&s.jsxs("span",{children:["Config path: ",s.jsx("code",{children:e.configPathCommand})]}),e.requiresRestart&&s.jsx("span",{children:"Start a fresh CLI session after editing config."})]}),e.template&&s.jsx("pre",{className:"mt-3 max-h-72 overflow-auto rounded-lg border border-border-subtle bg-bg-primary p-3 text-xs font-mono leading-relaxed text-text-primary select-all whitespace-pre-wrap",children:e.template})]}):null}function qv({workspaceMode:e,activeKind:t,cliEnabled:r,ideEnabled:n,acpEnabled:a,busy:o,onSelect:i}){return e==="mesh"?null:s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:r},{id:"ide",label:"Workspace",enabled:n},{id:"acp",label:"ACP",enabled:a}].map(c=>s.jsx("button",{type:"button",className:`btn btn-sm ${t===c.id?"btn-primary":"btn-secondary"}`,onClick:()=>i(c.id),disabled:!c.enabled||o,children:c.label},c.id))})]})}function Ya(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>Ks(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>Ks(a,"acp"))?"acp":null}function yn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Yv({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:i,onListMeshes:c,onLaunchMeshCoordinator:u,onListSavedSessions:m}){var ze,At;const d=Or(),p=l.useMemo(()=>[...e].sort(ei),[e]),[h,b]=l.useState(((ze=p[0])==null?void 0:ze.id)||""),g=l.useMemo(()=>p.find(le=>le.id===h)||p[0],[h,p]),f=l.useMemo(()=>((g==null?void 0:g.workspaces)||[]).map(le=>({id:le.id,path:le.path,label:le.label})),[g]),w=(g==null?void 0:g.defaultWorkspaceId)||null,[j,y]=l.useState("workspace"),[v,N]=l.useState(""),[k,x]=l.useState(""),[I,C]=l.useState([]),[M,D]=l.useState(""),[P,T]=l.useState(!1),[R,O]=l.useState(null),[K,S]=l.useState(""),[A,B]=l.useState(Ya(p[0])),[L,$]=l.useState(""),[F,z]=l.useState(""),[re,J]=l.useState([]),[Y,se]=l.useState(""),[fe,be]=l.useState([]),[X,Q]=l.useState(!1),[we,ve]=l.useState(!1),[xe,Ne]=l.useState(""),[ae,ge]=l.useState(!1),[me,U]=l.useState(()=>Ct()),[H,q]=l.useState(null),[ne,E]=l.useState(!1),[W,_]=l.useState(""),[ie,pe]=l.useState(null),[ue,oe]=l.useState(!1),[Pe,Ee]=l.useState(""),[$e,He]=l.useState([]),[Xe,Je]=l.useState(!1),[nt,et]=l.useState(""),[ct,st]=l.useState(!1),ft=l.useRef(null),Me=l.useRef(0);l.useEffect(()=>{var le;!h&&((le=p[0])!=null&&le.id)&&b(p[0].id)},[h,p]),l.useEffect(()=>{!g||!(!g.workspaces||!g.availableProviders||!g.detectedIdes||!g.recentLaunches)||d(g.id,{minFreshMs:3e4}).catch(()=>{})},[d,g]);const Se=l.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(le=>Ks(le,"cli")),[g]),Qe=l.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(le=>Ks(le,"acp")),[g]),Ge=l.useMemo(()=>((g==null?void 0:g.detectedIdes)||[]).map(le=>({id:le.type,label:le.name||le.type,meta:le.running?"Detected locally":"Available to open"})),[g]),bt=l.useMemo(()=>A==="cli"?Se.map(le=>({id:le.type,label:le.displayName||le.type,meta:"CLI provider"})):A==="acp"?Qe.map(le=>({id:le.type,label:le.displayName||le.type,meta:"ACP provider"})):Ge,[Qe,A,Se,Ge]),V=l.useMemo(()=>I.find(le=>le.id===M)||null,[I,M]),G=l.useMemo(()=>Se.find(le=>le.type===L)||null,[Se,L]),te=l.useMemo(()=>zu(G==null?void 0:G.meshCoordinator,{meshId:(V==null?void 0:V.id)||"",workspace:(V==null?void 0:V.workspace)||""}),[G,V]),de=ie||te,ye=l.useCallback(async le=>{T(!0),S("");try{const De=await c(le);C(De),D(ce=>{var Re;return De.some(_e=>_e.id===ce)?ce:((Re=De[0])==null?void 0:Re.id)||""}),O(le)}catch(De){C([]),D(""),O(le),S(De instanceof Error?De.message:"Could not load meshes")}finally{T(!1)}},[c]);l.useEffect(()=>{var De;if(!g)return;if(ft.current!==g.id){ft.current=g.id,y("workspace"),N(w||((De=f[0])==null?void 0:De.id)||"__home__"),x(""),C([]),D(""),O(null),S(""),B(Ya(g)),$(""),z(""),se(""),be([]),ve(!1),Ne(""),U(Ct()),_(""),pe(null);return}N(ce=>{var Re;return ce==="__custom__"||ce==="__home__"||f.some(_e=>_e.id===ce)?ce:w||((Re=f[0])==null?void 0:Re.id)||"__home__"}),B(ce=>ce==="ide"&&Ge.length>0||ce==="cli"&&Se.length>0||ce==="acp"&&Qe.length>0?ce:Ya(g))},[Qe.length,Se.length,w,Ge.length,g,f]),l.useEffect(()=>{!g||j!=="mesh"||R===g.id||P||ye(g.id)},[ye,R,P,g,j]),l.useEffect(()=>{j==="mesh"&&A!=="cli"&&Se.length>0&&B("cli")},[A,Se.length,j]),l.useEffect(()=>{var le;A&&(bt.some(De=>De.id===L)||$(((le=bt[0])==null?void 0:le.id)||""))},[A,bt,L]),l.useEffect(()=>{pe(null)},[g==null?void 0:g.id,M,L,j]);const je=l.useCallback(async(le,De)=>{const ce=Me.current+1;return Me.current=ce,Q(!0),Ne(""),m(le,De).then(Re=>{Me.current===ce&&be(Re)}).catch(Re=>{Me.current===ce&&(be([]),Ne(Re instanceof Error?Re.message:"Could not load saved sessions"))}).finally(()=>{Me.current===ce&&(Q(!1),ve(!0))})},[m]),Z=l.useCallback((le,De)=>{J(Wv(le,De))},[]);l.useEffect(()=>{Me.current+=1,se(""),U(Ct()),!g||!L||A==="ide"?J([]):Z(g.id,L),ve(!1),be([]),Ne(""),Q(!1)},[A,Z,je,g,L]),l.useEffect(()=>{if(!Y)return;const le=fe.find(De=>De.providerSessionId===Y);le!=null&&le.canResume||se("")},[fe,Y]);const ee=v==="__custom__"?k.trim():v==="__home__"?"":((At=f.find(le=>le.id===v))==null?void 0:At.path)||"",he=l.useMemo(()=>g?t.filter(le=>le.id!==g.id&&le.daemonId===g.id).map(le=>le.workspace):[],[t,g]),Ce=l.useMemo(()=>((g==null?void 0:g.recentLaunches)||[]).map(le=>le.workspace),[g]),Te=l.useCallback(le=>{const De=String(le.workspace||"").trim();if(!De)return;const ce=f.find(Re=>yn(Re.path)===yn(De));if(ce){N(ce.id),x("");return}N("__custom__"),x(De)},[f]),Ie=l.useCallback(le=>{const De=String(le.workspace||"").trim();if(!De)return{workspaceId:null,workspacePath:null};const ce=f.find(Re=>yn(Re.path)===yn(De));return ce?{workspaceId:ce.id,workspacePath:null}:{workspaceId:null,workspacePath:De}},[f]),Le=l.useMemo(()=>fe.find(le=>le.providerSessionId===Y)||null,[fe,Y]),Be=l.useMemo(()=>{var De;if(A!=="cli"||!g||!L)return null;const le=((De=Se.find(ce=>ce.type===L))==null?void 0:De.displayName)||L;return{routeId:g.id,daemonId:g.id,providerSessionId:Y||void 0,transport:"pty",mode:"chat",agentName:le,agentType:L,status:"idle",title:le,messages:[],ideType:L,workspaceName:ee,workspacePath:ee,displayPrimary:le,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${g.id}:${L}`,machineName:Pt(g,{fallbackId:g.id})}},[A,Se,ee,g,Y,L]),Ae=l.useCallback(()=>{var De;if(!g)return;N("__custom__"),oe(!0),et("");const le=yi(g.platform,gi(k.trim(),ee,he,Ce,g.defaultWorkspacePath,(De=f.find(ce=>ce.id===w))==null?void 0:De.path,f.map(ce=>ce.path)));Je(!0),n(g.id,le).then(ce=>{Ee(ce.path),x(ce.path),He(ce.directories)}).catch(ce=>{et(ce instanceof Error?ce.message:"Could not load folder")}).finally(()=>Je(!1))},[k,w,Ce,he,n,ee,g,f]),We=l.useCallback(le=>{g&&(Je(!0),et(""),n(g.id,le).then(De=>{Ee(De.path),x(De.path),He(De.directories)}).catch(De=>{et(De instanceof Error?De.message:"Could not load folder")}).finally(()=>Je(!1)))},[n,g]),qe=l.useCallback(async()=>{if(!g||!ee)return;st(!0),_("");const le=await a(g.id,ee);if(st(!1),!le.ok){_(le.error||"Could not save workspace");return}_("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,ee,g]),mt=l.useCallback(async()=>{if(!g)return;if(j==="mesh"){if(!M||!L)return;E(!0),_(""),pe(null);const ce=await u(g.id,M,L);if(E(!1),!ce.ok){if(ce.code==="mesh_coordinator_manual_mcp_setup_required"&&ce.manualSetup){pe(ce.manualSetup),_("Manual MCP setup required before this provider can act as mesh coordinator.");return}_(ce.error||"Could not start mesh coordinator");return}r();return}if(!A||!L)return;E(!0),_("");const le=F.trim()?F.trim().split(/\s+/).filter(Boolean):[],De=A==="ide"?await o(g.id,L,{workspacePath:ee||null}):await i(g.id,A,L,{workspaceId:v!=="__home__"&&v!=="__custom__"?v:null,workspacePath:v==="__custom__"&&ee||null,resumeSessionId:A==="cli"&&Y?Y:null,cliArgs:le});if(E(!1),!De.ok){_(De.error||"Could not start session");return}A!=="ide"&&F.trim()&&(Kv(g.id,L,F),Z(g.id,L)),r()},[A,F,Z,r,o,u,i,ee,g,M,Y,L,v,j]),gt=j==="mesh"?"Start mesh coordinator":A?gg(A,A==="cli"&&!!Y):"Start",ht=j==="mesh"?"Starting coordinator…":A?yg(A,A==="cli"&&!!Y):"Starting…",ot=p.length>5;return g?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:r,"aria-label":"Close new session dialog",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[p.length>1&&s.jsx(Pn,{title:"Machine",children:ot?s.jsx("select",{"aria-label":"Machine",value:g.id,onChange:le=>b(le.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:ne,children:p.map(le=>s.jsx("option",{value:le.id,children:Pt(le,{fallbackId:le.id})},le.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:p.map(le=>{const De=Pt(le,{fallbackId:le.id}),ce=g.id===le.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${De}`,"aria-pressed":ce,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${ce?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/60 text-text-secondary hover:bg-bg-secondary hover:text-text-primary"}`,onClick:()=>b(le.id),disabled:ne,title:De,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${le.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:De})]},le.id)})})}),s.jsxs(Pn,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:j==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ae,disabled:ne,children:"Browse…"}):void 0,children:[s.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2",role:"radiogroup","aria-label":"Launch target type",children:[{id:"workspace",label:"Workspace",desc:"Normal session"},{id:"mesh",label:"Mesh",desc:"Coordinator session"}].map(le=>s.jsxs("button",{type:"button",role:"radio","aria-checked":j===le.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${j===le.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{y(le.id),_(""),le.id==="mesh"&&g&&R!==g.id&&!P&&ye(g.id)},disabled:ne,children:[s.jsx("div",{className:"text-sm font-semibold",children:le.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:le.desc})]},le.id))}),j==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:v,onChange:le=>{const De=le.target.value;N(De),De==="__custom__"?Ae():_("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:ne,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),f.map(le=>s.jsxs("option",{value:le.id,children:[le.id===w?"⭐ ":"",Nd(le.path,le.label)||le.path]},le.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:v==="__home__"?"Launch without a workspace.":ee||"Select a workspace folder."}),v==="__custom__"&&ee&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ae,disabled:ne,children:[s.jsx(Os,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:qe,disabled:ne||ct,children:ct?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[P&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!P&&K&&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:K}),!P&&!K&&I.length===0&&s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2 text-sm text-text-muted",children:"No repo meshes are configured on this machine. Create or sync a mesh first, then reopen this picker."}),I.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:I.map(le=>s.jsxs("button",{type:"button",role:"radio","aria-checked":M===le.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${M===le.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>D(le.id),disabled:ne,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:le.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[le.repoIdentity||"Repo mesh",typeof le.nodesCount=="number"?` · ${le.nodesCount} node${le.nodesCount===1?"":"s"}`:""]}),le.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",le.workspace]})]},le.id))}),V&&s.jsx("div",{className:"text-[11px] text-text-muted",children:"Mesh coordinators use the selected CLI provider and the mesh's configured coordinator workspace."})]})]}),s.jsx(qv,{workspaceMode:j,activeKind:A,cliEnabled:Se.length>0,ideEnabled:Ge.length>0,acpEnabled:Qe.length>0,busy:ne,onSelect:B}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:A==="ide"?"Choose IDE":A==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[bt.map(le=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${L===le.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>$(le.id),disabled:ne,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:le.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:le.meta})]},le.id)),bt.length===0&&s.jsx("div",{className:"text-sm text-text-muted",children:"Nothing usable for this category on the selected machine. Set a custom executable path in Providers if the binary lives outside the default location."})]})]}),j==="mesh"&&de&&s.jsx(dm,{setup:de,providerName:(G==null?void 0:G.displayName)||(G==null?void 0:G.name)||L}),j!=="mesh"&&A!=="ide"&&s.jsxs(Pn,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:F,onChange:le=>z(le.target.value),placeholder:"Optional flags...",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:ne}),re.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:re.map(le=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>z(le),disabled:ne,title:le,children:le},le))})]}),j!=="mesh"&&A==="cli"&&s.jsx(Vv,{busy:ne,savedSessionsLoading:X,savedSessionsError:xe,selectedSession:Le,onRefresh:()=>{!g||!L||je(g.id,L)},onOpenHistory:()=>{!g||!L||(ge(!0),Uv({hasLoadedInitialResults:we,isLoading:X})&&je(g.id,L))},onClearSelection:()=>se("")}),W&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${W.includes("saved")||W.includes("requested")||W.includes("Manual MCP setup")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:W})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:r,disabled:ne,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:mt,disabled:ne||(j==="mesh"?!M||!L||A!=="cli"||P:!A||!L||v==="__custom__"&&!ee),children:[s.jsx(ld,{size:14}),ne?ht:gt]})]})]})}),ue&&s.jsx(ji,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:Pe,directories:$e,busy:Xe,error:nt,onClose:()=>oe(!1),onNavigate:We,onConfirm:le=>{x(le),Ee(le),N("__custom__"),oe(!1)}}),ae&&Be&&s.jsx(cu,{activeConv:Be,ides:[],isCreatingChat:!1,isRefreshingHistory:X,savedSessions:fe,isSavedSessionsLoading:X,isResumingSavedSessionId:H,savedHistoryFilters:me,missingWorkspaceResumePath:ee||null,onSavedHistoryFiltersChange:U,onClose:()=>ge(!1),onNewChat:()=>{se(""),ge(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!g||!L||je(g.id,L)},onResumeSavedSession:le=>{if(!g||!L||H||!le.canResume)return;const De=Ie(le);se(le.providerSessionId),Te(le),q(le.providerSessionId),ge(!1),E(!0),_(""),i(g.id,"cli",L,{workspaceId:De.workspaceId,workspacePath:De.workspacePath,resumeSessionId:le.providerSessionId}).then(ce=>{if(!ce.ok){_(ce.error||"Could not resume session");return}r()}).finally(()=>{E(!1),q(ce=>ce===le.providerSessionId?null:ce)})}})]}):null}function um(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 Ni(e){if(e.type==="submoduleNode")return e.outOfSync||e.error?{label:"submodule drift",tone:"danger"}:e.dirty?{label:"submodule dirty",tone:"warn"}:null;const t=e.branchConvergence;if((t==null?void 0:t.status)==="not_mergeable")return{label:e.hasConflicts?"conflicts present":"dirty workspace",tone:"danger"};if((t==null?void 0:t.status)==="blocked_review"){if(t.reason==="upstream_unverified")return{label:"upstream unverified",tone:"warn"};const r=um(e);return r?{label:r,tone:"danger"}:!e.upstream&&e.branch&&e.branch!==t.defaultBranch?{label:"push branch",tone:"warn"}:{label:"blocked review",tone:"danger"}}return e.refineJobStatus==="failed"?{label:"refine failed",tone:"danger"}:e.refineJobStatus==="running"||e.refineJobStatus==="accepted"?{label:"refining…",tone:"info"}:(t==null?void 0:t.status)==="pushed_feature_branch_needs_merge"?{label:"needs merge",tone:"warn"}:(t==null?void 0:t.status)==="cleanup_candidate"?{label:"refine worktree",tone:"info"}:e.isOrphan?{label:"needs follow-up",tone:"warn"}:e.health==="offline"?{label:"offline",tone:"danger"}:null}function Si(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function mm(e){var t;return!Si(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 vn(e){return[...new Set(e.filter(t=>!!t))]}function Jv(e){const t=e.nodes.find(i=>i.type==="defaultBranchNode")??null,r=(t==null?void 0:t.branch)??null,n=e.nodes.filter(i=>i.type!=="defaultBranchNode"&&i.type!=="submoduleNode"&&!i.isOrphan&&!!r&&i.branch===r),a=e.nodes.filter(i=>i.type!=="submoduleNode"&&!i.isOrphan),o=e.nodes.filter(i=>i.type!=="submoduleNode");return t||n.length>0?vn([t==null?void 0:t.id,...n.map(i=>i.id)]):a.length>0?vn(a.map(i=>i.id)):o.length>0?vn(o.map(i=>i.id)):vn(e.nodes.map(i=>i.id))}function pm(e){const t=[...e.nodes].sort((n,a)=>n.id.localeCompare(a.id)).map(n=>[n.id,n.type,n.branch??"",n.parentNodeId??"",n.submodulePath??""].join(":")).join("|"),r=[...e.edges].sort((n,a)=>n.id.localeCompare(a.id)).map(n=>[n.id,n.source,n.target,n.type].join(":")).join("|");return`${e.meshId}::${t}::${r}`}function Xv(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${pm(e)}::${n}x${a}`}const Qv={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"},Zv={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"},ew={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"},tw={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 Js(e){return e==="light"?{theme:e,isDark:!1,flowColorMode:"light",textPrimary:"text-slate-900",textSecondary:"text-slate-700",textMuted:"text-slate-500",graphShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-slate-200 bg-[radial-gradient(circle_at_top,_rgba(14,165,233,0.16),_rgba(248,250,252,0.98)_42%,_rgba(255,255,255,1))]",graphStatChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-slate-700 shadow-sm",graphHintChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-[10px] text-slate-500 shadow-sm",graphControlsClass:"!bottom-4 !left-4 !shadow-md",graphBackgroundDotColor:"rgba(148, 163, 184, 0.34)",edgeLabelTextColor:"#334155",edgeLabelBackgroundColor:"rgba(255, 255, 255, 0.96)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.45)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-center justify-center bg-[rgba(148,163,184,0.22)] p-0 md:p-4 backdrop-blur-md",dialogShellClass:"flex h-[100dvh] w-full flex-col overflow-hidden bg-white md:h-[min(90vh,960px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-slate-200 md:bg-white/98 md:shadow-[0_28px_120px_rgba(148,163,184,0.28)]",dialogHeaderClass:"flex shrink-0 flex-col gap-3 border-b border-slate-200 bg-white/96 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-slate-900 md:text-xl",dialogKickerClass:"rounded-full border border-slate-300 bg-slate-50 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-600",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-500",dialogRefreshedChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1.5 text-xs text-slate-600",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-slate-300 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",dialogBodyClass:"min-h-0 flex-1 flex flex-col bg-[linear-gradient(180deg,rgba(248,250,252,0.98),rgba(241,245,249,0.96))] px-4 py-4 md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-slate-300 bg-white/90 px-6 text-center text-sm text-slate-500",cardClass:"rounded-2xl border border-slate-200 bg-white/95 shadow-sm",cardHeaderClass:"border-b border-slate-200 px-4 py-3",cardTitleClass:"text-sm font-semibold text-slate-900",cardSubtitleClass:"mt-1 text-xs text-slate-500",rowClass:"flex items-start justify-between gap-3 border-b border-slate-200/80 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"text-slate-500",rowValueClass:"max-w-[65%] break-all text-right text-slate-800",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-slate-200 bg-white/95 p-4 shadow-md md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-slate-200 bg-white/95 p-4 text-xs text-slate-500 shadow-sm md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-900",panelCloseButtonClass:"text-xs text-slate-500 hover:text-slate-900",panelFieldRowClass:"flex justify-between gap-3 border-b border-slate-200/80 py-0.5 text-[11px]",panelFieldLabelClass:"text-slate-500",panelFieldValueClass:"break-all text-right font-medium text-slate-700",infoCalloutClass:"mt-1 rounded border border-sky-300 bg-sky-50 px-2 py-1.5 text-[10px] text-sky-700",badge:t=>Zv[t],actionButton:t=>tw[t]}:{theme:e,isDark:!0,flowColorMode:"dark",textPrimary:"text-slate-100",textSecondary:"text-slate-300",textMuted:"text-slate-400",graphShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-white/10 bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.12),_rgba(15,23,42,0.98)_42%,_rgba(2,6,23,1))]",graphStatChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-slate-200",graphHintChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-[10px] text-slate-300",graphControlsClass:"!bottom-4 !left-4 !shadow-lg",graphBackgroundDotColor:"rgba(148, 163, 184, 0.22)",edgeLabelTextColor:"#cbd5e1",edgeLabelBackgroundColor:"rgba(2, 6, 23, 0.86)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.2)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-center justify-center bg-[#030617]/[0.58] p-0 md:p-4 backdrop-blur-md",dialogShellClass:"flex h-[100dvh] w-full flex-col overflow-hidden bg-slate-950 md:h-[min(90vh,960px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-white/10 md:bg-slate-950/96 md:shadow-[0_28px_120px_rgba(2,6,23,0.46)]",dialogHeaderClass:"flex shrink-0 flex-col gap-3 border-b border-white/10 bg-slate-950/92 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-white md:text-xl",dialogKickerClass:"rounded-full border border-white/10 bg-white/6 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-300",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-400",dialogRefreshedChipClass:"rounded-full border border-white/10 bg-white/6 px-3 py-1.5 text-xs text-slate-300",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-white/10 bg-white/6 text-slate-300 transition hover:bg-white/10 hover:text-white",dialogBodyClass:"min-h-0 flex-1 flex flex-col bg-[linear-gradient(180deg,rgba(2,6,23,0.95),rgba(15,23,42,0.98))] px-4 py-4 md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-white/10 bg-white/[0.03] px-6 text-center text-sm text-slate-400",cardClass:"rounded-2xl border border-white/10 bg-white/[0.04]",cardHeaderClass:"border-b border-white/10 px-4 py-3",cardTitleClass:"text-sm font-semibold text-white",cardSubtitleClass:"mt-1 text-xs text-slate-400",rowClass:"flex items-start justify-between gap-3 border-b border-white/5 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"text-slate-400",rowValueClass:"max-w-[65%] break-all text-right text-slate-100",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-white/10 bg-white/[0.04] p-4 shadow-lg md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-white/10 bg-white/[0.04] p-4 text-xs text-slate-400 md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-100",panelCloseButtonClass:"text-xs text-slate-400 hover:text-slate-100",panelFieldRowClass:"flex justify-between gap-3 border-b border-white/6 py-0.5 text-[11px]",panelFieldLabelClass:"text-slate-400",panelFieldValueClass:"break-all text-right font-medium text-slate-200",infoCalloutClass:"mt-1 rounded bg-blue-500/10 border border-blue-500/20 px-2 py-1.5 text-[10px] text-blue-300",badge:t=>Qv[t],actionButton:t=>ew[t]}}const Us={worktreeCardWidth:256,submoduleCardWidth:228,minWorktreeCardHeight:174,minSubmoduleCardHeight:146,maxEstimatedCardHeight:304,layerGap:220,nodeGap:82,edgeLabelBuffer:180,placeholderTopOffset:0},Ur={worktreeCardWidth:188,submoduleCardWidth:188,minWorktreeCardHeight:88,minSubmoduleCardHeight:88,maxEstimatedCardHeight:178,layerGap:160,nodeGap:52,edgeLabelBuffer:120},sw={maxWidth:180};function rw(e){return e==="TB"?"DOWN":"RIGHT"}function Ci(e,t){return{"elk.algorithm":"layered","elk.direction":rw(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 nw=Ci(Us,"LR");Ci(Ur,"LR");function aw(e){const t=e.nodes.length;if(t<8)return"LR";const r=new Map;for(const a of e.edges)r.set(a.source,(r.get(a.source)??0)+1);let n=0;for(const a of r.values())a>n&&(n=a);return n>=Math.max(6,Math.floor(t/2))?"TB":"LR"}const ow=new Np;function Rr(e,t=!1){const r=t?Ur:Us;return e.type==="submoduleNode"?r.submoduleCardWidth:r.worktreeCardWidth}function Rn(e){var r;if(e.type==="defaultBranchNode")return e.nextStepHint||"Default branch anchor";if(e.type==="submoduleNode"){const n=[e.machineLabel?`parent ${e.machineLabel}`:null];return e.outOfSync?n.push("out of sync"):e.dirty?n.push("local changes"):n.push("synced"),n.filter(Boolean).join(" · ")}const t=[];if(e.upstream&&t.push(e.upstream),e.upstream&&e.upstreamStatus!=="fresh")t.push("upstream unverified");else{const n=um(e);n&&t.push(n)}return e.activeSessionCount>0&&t.push(`${e.activeSessionCount} session${e.activeSessionCount===1?"":"s"}`),e.dirtyFiles>0&&t.push(`${e.dirtyFiles} dirty`),e.hasConflicts&&t.push("conflicts"),t.length===0?(r=e.branchConvergence)!=null&&r.needsConvergence?"Needs follow-up":"Clean and even with upstream":t.join(" · ")}function hm(e,t=!1){const r=t?Ur:Us,n=Rr(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(iw(e)/o),c=wn(e.label,a,2),u=wn(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,a,2),m=wn(Rn(e),a+(t?1:4),t?2:3),d=Ni(e),p=mm(e)?Si(e):null,h=t?0:wn(p,Math.max(24,Math.floor(n/8)),4),b=t?40+c*16+u*12+(d?22:0)+Math.max(0,i-1)*18+Math.max(18,m*16):52+c*18+u*14+(d?30:0)+i*24+Math.max(22,m*18)+(h>0?22+h*16:0),g=e.type==="submoduleNode"?r.minSubmoduleCardHeight:r.minWorktreeCardHeight;return Math.min(r.maxEstimatedCardHeight,Math.max(g,Math.ceil(b)))}function wn(e,t,r){const n=(e||"").trim();return n?Math.max(1,Math.min(r,Math.ceil(n.length/t))):0}function iw(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 lw(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 cw(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.id.localeCompare(t.id)}function dw(e,t,r,n=!0){return{id:e.id,type:"meshNode",position:{x:t,y:r},graphNode:e,selected:!1,draggable:!1,selectable:n}}function uw(e,t,r){return{id:e.id,x:t,y:r,width:Rr(e),height:hm(e)}}function mw(e,t){return{id:`${e.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:t.repoIdentity,branch:e.branch,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:null,locality:"unknown",health:"unknown",ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],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 fm(e){const t=[...e.nodes].sort(lw),r=t.find(a=>a.type==="defaultBranchNode")??null,n=t.some(a=>a.id!==(r==null?void 0:r.id)&&a.type!=="submoduleNode");return!r||n?t:[...t,mw(r,e)]}function pw(e,t=nw,r=!1,n="LR"){const a=fm(e),o=new Set(a.map(u=>u.id)),i=a.map(u=>({id:u.id,width:Rr(u,r),height:hm(u,r)})),c=e.edges.filter(u=>o.has(u.source)&&o.has(u.target)).sort(cw).map(u=>({id:u.id,sources:[u.source],targets:[u.target]}));return{id:`${e.meshId||"mesh"}__elk_root`,layoutOptions:{...t},children:i,edges:c}}function hw(e,t=!1){const r=[...new Set(e.map(a=>Math.round(a.x)))].sort((a,o)=>a-o),n=t?Ur.layerGap:Us.layerGap;return r.length<2?n:Math.min(...r.slice(1).map((a,o)=>a-r[o]))}async function xm(e,t=!1,r="LR",n){var g,f;const o=Ci(t?Ur:Us,r),i=fm(e),c=new Map(i.map(w=>[w.id,w])),u=pw(e,o,t,r);if(n&&n.size>0)for(const w of u.children??[]){const j=n.get(w.id);j&&j>0&&(w.height=j)}const m=await ow.layout(u),d=(m.children??[]).map(w=>{const j=c.get(w.id);return j?dw(j,Math.round(w.x??0),Math.round(w.y??Us.placeholderTopOffset),!w.id.endsWith("__placeholder")):null}).filter(Boolean),p=new Map(i.map((w,j)=>[w.id,j]));d.sort((w,j)=>(p.get(w.id)??0)-(p.get(j.id)??0));const h=d.map(w=>uw(w.graphNode,w.position.x,w.position.y)),b=new Map;for(const w of m.edges??[]){const j=w.sections;if(!j||j.length===0)continue;const y=j[0],v=(g=w.sources)==null?void 0:g[0],N=(f=w.targets)==null?void 0:f[0];if(!v||!N)continue;const k=[];k.push({x:Math.round(y.startPoint.x),y:Math.round(y.startPoint.y)});for(const x of y.bendPoints??[])k.push({x:Math.round(x.x),y:Math.round(x.y)});k.push({x:Math.round(y.endPoint.x),y:Math.round(y.endPoint.y)}),b.set(w.id,{id:w.id,source:v,target:N,points:k})}return{nodes:d,bounds:h,edgeRoutes:b,columnGap:hw(h,t),layoutOptions:{...o}}}function fw(e){var t,r;return[e.id,e.type,e.label,e.branch??"",e.upstream??"",e.upstreamStatus??"",e.daemonId??"",e.machineId??"",e.machineLabel??"",e.locality,e.health,e.ahead,e.behind,e.dirty?1:0,e.dirtyFiles,e.hasConflicts?1:0,e.activeSessionCount,e.sessionDetails.map(n=>[n.sessionId,n.providerType??"",n.state??"",n.chatStatus??"",n.lifecycle??"",n.role??"",n.isSelfCoordinator?1:0,n.statusNote??"",n.startedAt??"",n.createdAt??""].join("/")).join(","),e.isOrphan?1:0,e.outOfSync?1:0,e.snapshotCompleteness,((t=e.branchConvergence)==null?void 0:t.status)??"",(r=e.branchConvergence)!=null&&r.needsConvergence?1:0,e.nextStepHint??"",e.error??"",e.parentNodeId??"",e.submodulePath??"",e.submoduleCommit??""].join("|")}function bm(e){return[e.id,e.source,e.target,e.type,e.label??"",e.direction].join("|")}function xw(e){return[e.meshId,e.refreshedAt,e.nodes.length,e.edges.length,...e.nodes.map(fw),...e.edges.map(bm)].join("::")}function bw(e){return[e.meshId,e.nodes.length,e.edges.length,...e.nodes.map(t=>{var r,n;return[t.id,t.type,t.label,t.branch??"",t.machineLabel??"",t.locality,t.health,t.dirty?1:0,t.dirtyFiles,t.hasConflicts?1:0,t.activeSessionCount,t.isOrphan?1:0,t.outOfSync?1:0,t.snapshotCompleteness,((r=t.branchConvergence)==null?void 0:r.status)??"",(n=t.branchConvergence)!=null&&n.needsConvergence?1:0,t.nextStepHint??"",t.parentNodeId??"",t.submodulePath??"",t.submoduleCommit??""].join("|")}),...e.edges.map(bm)].join("::")}const gw=7,Ii=l.createContext(Js("dark")),gm=l.createContext(!1),ym=l.createContext("LR"),vm={overflowWrap:"anywhere",wordBreak:"break-word"},yw={...vm,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:3,overflow:"hidden"},vw={...vm,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:4,overflow:"hidden"};function wm(e){return e.activeSessionCount>0}function ww(e){return e.health==="offline"||e.snapshotCompleteness==="stale"&&e.activeSessionCount===0}function dc(e,t,r){const n=wm(e),a=ww(e);let o;t?o="border-cyan-400/70 shadow-[0_0_0_1px_rgba(34,211,238,0.35),0_24px_60px_rgba(8,145,178,0.18)]":n?o=r?"border-emerald-400/40 shadow-[0_0_0_1px_rgba(52,211,153,0.18),0_18px_48px_rgba(3,7,18,0.22)]":"border-emerald-400/60 shadow-[0_0_0_1px_rgba(52,211,153,0.2),0_18px_48px_rgba(148,163,184,0.20)]":a?o=r?"border-white/6 shadow-[0_12px_32px_rgba(3,7,18,0.16)] opacity-60":"border-slate-200/70 shadow-[0_12px_32px_rgba(148,163,184,0.14)] opacity-60":o=r?"border-white/10 shadow-[0_18px_48px_rgba(3,7,18,0.22)]":"border-slate-300/90 shadow-[0_18px_48px_rgba(148,163,184,0.20)]";const i=Ni(e);if((i==null?void 0:i.tone)==="danger")return`${o} ${r?"bg-rose-500/12":"bg-rose-50/95"}`;if((i==null?void 0:i.tone)==="warn")return`${o} ${r?"bg-amber-500/10":"bg-amber-50/95"}`;if((i==null?void 0:i.tone)==="info")return`${o} ${r?"bg-violet-500/10":"bg-violet-50/95"}`;switch(e.health){case"online":return`${o} ${r?n?"bg-emerald-500/10":"bg-emerald-500/8":n?"bg-emerald-50":"bg-emerald-50/95"}`;case"dirty":return`${o} ${r?"bg-amber-500/8":"bg-amber-50/95"}`;case"degraded":return`${o} ${r?"bg-rose-500/10":"bg-rose-50/95"}`;case"wrong_branch":return`${o} ${r?"bg-violet-500/10":"bg-violet-50/95"}`;case"offline":return`${o} ${r?"bg-slate-500/10":"bg-slate-100/90"}`;default:return`${o} ${r?"bg-slate-950/78":"bg-white/96"}`}}function St(e,t){switch(e){case"refineDone":return t?"border-emerald-400/25 bg-emerald-500/10 text-emerald-200":"border-emerald-300 bg-emerald-50 text-emerald-700";case"health":return t?"border-white/10 bg-slate-950/60 text-slate-200":"border-slate-300 bg-white/95 text-slate-700";case"dirty":return t?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700";case"conflict":return t?"border-rose-400/25 bg-rose-500/10 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700";case"orphan":return t?"border-fuchsia-400/25 bg-fuchsia-500/10 text-fuchsia-200":"border-fuchsia-300 bg-fuchsia-50 text-fuchsia-700";case"submodule":return t?"border-violet-400/25 bg-violet-500/10 text-violet-200":"border-violet-300 bg-violet-50 text-violet-700";case"meta":default:return t?"border-cyan-400/20 bg-cyan-500/8 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700"}}function uc(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 mc(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 jw(e){return e.replace(/_/g," ")}function Ht(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const r=t.toLowerCase().replace(/[\s-]+/g,"_");return r.includes("approval")?"awaiting approval":r.includes("generating")||r.includes("running")||r.includes("busy")?"generating":r.includes("failed")||r.includes("stopped")||r.includes("interrupted")?r.replace(/_/g," "):r.includes("idle")||r.includes("ready")||r.includes("waiting_input")?"idle":r.replace(/_/g," ")}function kw(e){var t;return((t=e.sessionDetails)==null?void 0:t.some(r=>Ht(r)==="generating"))??!1}function Ja(e,t){const r=Ht(e);return r.includes("approval")?t?"border-amber-400/30 bg-amber-500/12 text-amber-100":"border-amber-300 bg-amber-50 text-amber-700":r==="generating"?t?"border-cyan-400/30 bg-cyan-500/12 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700":r==="idle"?t?"border-emerald-400/30 bg-emerald-500/12 text-emerald-100":"border-emerald-300 bg-emerald-50 text-emerald-700":r.includes("failed")||r.includes("stopped")||r.includes("interrupted")?t?"border-rose-400/30 bg-rose-500/12 text-rose-100":"border-rose-300 bg-rose-50 text-rose-700":St("health",t)}function Nw(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function pc(e){const t=Nw(e);if(t===null)return"runtime age not reported";const r=Math.max(0,Math.floor((Date.now()-t)/1e3));if(r<60)return`${r}s`;const n=Math.floor(r/60);if(n<60)return`${n}m`;const a=Math.floor(n/60);return a<48?`${a}h ${n%60}m`:`${Math.floor(a/24)}d ${a%24}h`}function Xa(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function ur(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function Sw(e){if(e.sessionDetails.length===0)return null;const t=e.sessionDetails.filter(o=>Ht(o)==="generating").length,r=e.sessionDetails.filter(o=>o.isSelfCoordinator).length,n=e.sessionDetails.length-r,a=[`${e.sessionDetails.length} chat${e.sessionDetails.length===1?"":"s"}`];return t>0&&a.push(`${t} generating`),r>0&&a.push(r===1?"coordinator attached":`${r} coordinators`),n>0&&a.push(`${n} worker${n===1?"":"s"}`),t===0&&r>0&&a.push("sampled status"),a.join(" · ")}function hc(e){return e==="local"?"local":e==="remote"?"remote":"machine unknown"}function Cw(e){return e.locality==="remote"?"meta":"health"}function Iw({data:e,selected:t}){const r=l.useContext(Ii),n=l.useContext(gm),a=l.useContext(ym),o=e.graphNode,i=o.type==="defaultBranchNode",c=o.type==="submoduleNode",u=mm(o),m=i?"default branch anchor":c?o.submodulePath||"submodule checkout":[o.machineLabel,hc(o.locality)].filter(Boolean).join(" · ")||o.workspace,d=o.submoduleCommit?o.submoduleCommit.slice(0,7):null,p=Ni(o),h=Si(o),b=wm(o),g=o.sessionDetails,f=o.sessionDetails,w=Sw(o),j=o.sessionDetails.map(v=>{const N=Ht(v),k=v.providerType||"provider unknown",x=ur(v),I=v.startedAt||v.createdAt||null,C=v.statusNote?` · ${v.statusNote}`:"";return`Session: ${v.sessionId} · ${k} · ${N} · ${x} · ${pc(I)}${C}`});if(n)return s.jsxs("div",{className:`rounded-xl border px-3 py-2.5 backdrop-blur-sm transition-all ${dc(o,t,r.isDark)}`,style:{width:Rr(o,!0)},title:[o.label,o.branch?`Branch: ${o.branch}`:null,o.machineLabel?`Machine: ${o.machineLabel}`:null,o.workspace?`Workspace: ${o.workspace}`:null,p?`Status: ${p.label}`:null,Rn(o),...j].filter(Boolean).join(`
74
+ `),children:[s.jsx(tn,{type:"target",position:a==="TB"?ts.Top:ts.Left,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`truncate text-xs font-semibold leading-4 ${r.textPrimary}`,children:o.label}),!i&&s.jsx("div",{className:`truncate text-[10px] leading-3.5 ${r.textMuted}`,children:m})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[b&&s.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${r.isDark?"bg-emerald-400":"bg-emerald-500"} animate-pulse`,"aria-label":"active session"}),s.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full",style:{backgroundColor:mc(o.health)},"aria-hidden":!0})]})]}),o.health==="unknown"&&!p&&s.jsx("div",{className:`mt-1.5 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[9px] italic ${St("health",r.isDark)}`,children:s.jsx("span",{className:"truncate",children:"Connecting..."})}),p&&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] ${uc(p.tone,r.isDark)}`,title:p.label,children:s.jsx("span",{className:"truncate",children:p.label})}),!p&&o.branch&&!c&&o.health!=="unknown"&&s.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[10px] ${St("meta",r.isDark)} rounded-full border px-2 py-0.5 inline-block`,title:o.branch,children:o.branch}),w&&s.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[9px] ${r.isDark?"text-cyan-100/85":"text-sky-700"}`,title:j.join(`
75
+ `),children:w}),f.length>0&&s.jsx("div",{className:"mt-1.5 flex max-h-28 min-w-0 flex-col gap-1 overflow-y-auto pr-1",children:f.map(v=>s.jsxs("div",{className:`min-w-0 rounded-md border px-1.5 py-1 ${r.isDark?"border-cyan-400/15 bg-cyan-500/[0.055]":"border-sky-200 bg-white/80"}`,title:[`Session ID: ${v.sessionId}`,v.providerType?`Provider: ${v.providerType}`:null,`Status: ${Ht(v)}`,`Role: ${ur(v)}`].filter(Boolean).join(`
76
+ `),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-1.5",children:[s.jsx("span",{className:`min-w-0 truncate text-[9px] ${r.textMuted}`,children:v.providerType||"provider unknown"}),s.jsx("span",{className:`shrink-0 rounded-full border px-1 py-0 text-[8px] font-semibold uppercase tracking-[0.1em] ${Ja(v,r.isDark)}`,children:Ht(v)})]}),s.jsxs("div",{className:`mt-0.5 flex min-w-0 items-center gap-1.5 text-[8px] ${r.textMuted}`,children:[s.jsx("span",{className:"min-w-0 truncate font-mono",children:Xa(v.sessionId)}),s.jsx("span",{className:"shrink-0",children:ur(v)})]})]},v.sessionId))}),s.jsx(tn,{type:"source",position:a==="TB"?ts.Bottom:ts.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]});const y=[o.label,m,p?`Status: ${p.label}`:null,Rn(o),o.branch?`Branch: ${o.branch}`:null,o.dirty?c?"Local changes":`${o.dirtyFiles} dirty`:null,o.hasConflicts?"Has conflicts":null,o.outOfSync?"Out of sync":null,!c&&o.upstream&&o.upstreamStatus!=="fresh"?"Upstream unverified":null,o.isOrphan?"Needs follow-up":null,u&&h?`Note: ${h}`:null,...j].filter(Boolean).join(`
77
+ `);return s.jsxs("div",{className:`rounded-2xl border px-4 py-3 backdrop-blur-sm transition-all ${dc(o,t,r.isDark)}${kw(o)?" mesh-node-generating":""}`,style:{width:Rr(o)},title:y,children:[s.jsx(tn,{type:"target",position:a==="TB"?ts.Top:ts.Left,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${r.textPrimary}`,children:o.label}),s.jsx("div",{className:`truncate text-[11px] ${r.textMuted}`,children:m})]}),s.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 shrink-0",children:[b&&s.jsx("span",{className:`h-2 w-2 rounded-full ${r.isDark?"bg-emerald-400":"bg-emerald-500"} animate-pulse`,"aria-label":"active session"}),s.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:mc(o.health)},"aria-hidden":!0})]})]}),p?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] ${uc(p.tone,r.isDark)}`,title:p.label,children:s.jsx("span",{className:"truncate",children:p.label})}):o.branch&&!c?s.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[10px] ${St("meta",r.isDark)}`,title:o.branch,children:s.jsx("span",{className:"truncate",children:o.branch})}):null,w&&s.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[10px] font-medium ${r.isDark?"border-cyan-400/20 bg-cyan-500/8 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700"}`,title:j.join(`
78
+ `),children:s.jsx("span",{className:"truncate",children:w})}),f.length>0&&s.jsx("div",{className:"mt-2 flex max-h-44 min-w-0 flex-col gap-1.5 overflow-y-auto pr-1",children:f.map(v=>{const N=ur(v);return s.jsxs("div",{className:`min-w-0 rounded-lg border px-2.5 py-1.5 ${r.isDark?"border-cyan-400/15 bg-cyan-500/[0.055]":"border-sky-200 bg-white/85"}`,title:[`Session ID: ${v.sessionId}`,v.providerType?`Provider: ${v.providerType}`:null,`Status: ${Ht(v)}`,`Role: ${N}`].filter(Boolean).join(`
79
+ `),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate text-[10px] ${r.textMuted}`,children:v.providerType||"provider unknown"}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${Ja(v,r.isDark)}`,children:Ht(v)})]}),s.jsxs("div",{className:`mt-0.5 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${r.textMuted}`,children:[s.jsx("span",{className:"min-w-0 truncate font-mono",children:Xa(v.sessionId)}),s.jsx("span",{children:N})]})]},v.sessionId)})}),s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"flex min-w-0 flex-wrap gap-1.5 text-[10px]",children:[o.health==="unknown"?s.jsx("span",{className:`rounded-full border px-2 py-0.5 italic ${St("health",r.isDark)}`,children:"connecting..."}):s.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${St("health",r.isDark)}`,children:jw(o.health)}),c&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${St("submodule",r.isDark)}`,children:"submodule"}),!i&&o.health==="unknown"&&!o.locality&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 italic ${St("health",r.isDark)}`,children:"..."}),!i&&(o.health!=="unknown"||o.locality)&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${St(Cw(o),r.isDark)}`,children:hc(o.locality)}),d&&c&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${St("meta",r.isDark)}`,children:d}),o.dirty&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${St("dirty",r.isDark)}`,children:c?"local changes":`${o.dirtyFiles} dirty`}),o.outOfSync&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${St("conflict",r.isDark)}`,children:"out of sync"}),o.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${St("conflict",r.isDark)}`,children:"conflicts"}),!c&&o.upstream&&o.upstreamStatus!=="fresh"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${St("orphan",r.isDark)}`,children:"upstream unverified"}),o.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${St("orphan",r.isDark)}`,children:"needs follow-up"}),!c&&o.refineJobStatus==="completed"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${St("refineDone",r.isDark)}`,title:o.refineJobBranch?`refined ${o.refineJobBranch}${o.refineJobInto?` → ${o.refineJobInto}`:""}`:"refine completed",children:"refined"})]}),s.jsx("div",{className:`mt-3 text-[11px] leading-5 ${r.textSecondary}`,style:yw,children:Rn(o)}),g.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[9px] font-semibold uppercase tracking-[0.16em] ${r.textMuted}`,children:"Attached Chats"}),s.jsx("div",{className:"flex max-h-56 flex-col gap-1.5 overflow-y-auto pr-1",children:g.map(v=>{const N=v.startedAt||v.createdAt||null,k=ur(v);return s.jsxs("div",{className:`min-w-0 rounded-lg border px-2.5 py-1.5 ${r.isDark?"border-white/8 bg-white/[0.035]":"border-slate-200 bg-white/80"}`,title:[`Session ID: ${v.sessionId}`,v.providerType?`Provider: ${v.providerType}`:null,`Status: ${Ht(v)}`,`Role: ${k}`,N?`Started: ${N}`:"Started: not reported",v.statusNote?`Note: ${v.statusNote}`:null].filter(Boolean).join(`
80
+ `),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate font-mono text-[10px] select-text ${r.textPrimary}`,children:Xa(v.sessionId)}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${Ja(v,r.isDark)}`,children:Ht(v)})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${r.textMuted}`,children:[s.jsx("span",{className:"truncate",children:v.providerType||"provider unknown"}),s.jsx("span",{children:k}),s.jsx("span",{children:pc(N)})]}),v.statusNote&&s.jsx("div",{className:`mt-1 text-[9px] leading-4 ${r.textMuted}`,children:v.statusNote})]},v.sessionId)})})]}),u&&h&&s.jsx("div",{className:`mt-3 rounded-xl border px-3 py-2 text-[10px] leading-4 ${r.isDark?"border-cyan-400/15 bg-cyan-500/8 text-cyan-50/90":"border-sky-300 bg-sky-50 text-sky-700"}`,style:vw,children:h})]}),s.jsx(tn,{type:"source",position:a==="TB"?ts.Bottom:ts.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const Mw={meshNode:Iw},Aw=8;function Tw(e){if(e.length<2)return null;if(e.length===2){const[m,d]=e;return{d:`M ${m.x},${m.y} L ${d.x},${d.y}`,labelX:(m.x+d.x)/2,labelY:(m.y+d.y)/2}}const t=Aw,r=[`M ${e[0].x},${e[0].y}`];for(let m=1;m<e.length-1;m+=1){const d=e[m-1],p=e[m],h=e[m+1],b=Math.sign(p.x-d.x),g=Math.sign(p.y-d.y),f=Math.sign(h.x-p.x),w=Math.sign(h.y-p.y),j=Math.hypot(p.x-d.x,p.y-d.y),y=Math.hypot(h.x-p.x,h.y-p.y),v=Math.min(t,j/2,y/2);if(v<1||b===f&&g===w){r.push(`L ${p.x},${p.y}`);continue}const N=p.x-b*v,k=p.y-g*v,x=p.x+f*v,I=p.y+w*v;r.push(`L ${N},${k}`),r.push(`Q ${p.x},${p.y} ${x},${I}`)}const n=e[e.length-1];r.push(`L ${n.x},${n.y}`);let a=0;const o=[0];for(let m=1;m<e.length;m+=1)a+=Math.hypot(e[m].x-e[m-1].x,e[m].y-e[m-1].y),o.push(a);const i=a/2;let c=e[0].x,u=e[0].y;for(let m=1;m<e.length;m+=1)if(o[m]>=i){const d=o[m]-o[m-1],p=d===0?0:(i-o[m-1])/d;c=e[m-1].x+(e[m].x-e[m-1].x)*p,u=e[m-1].y+(e[m].y-e[m-1].y)*p;break}return{d:r.join(" "),labelX:c,labelY:u}}function _w(e){const t=e.data.routePoints;if(t&&t.length>=2){const o=Tw(t);if(o)return[o.d,o.labelX,o.labelY]}const r={sourceX:e.sourceX,sourceY:e.sourceY,sourcePosition:e.sourcePosition,targetX:e.targetX,targetY:e.targetY,targetPosition:e.targetPosition},n=e.data.graphEdge;let a;return n.type==="parentBranch"?a=Ep(r):n.type==="worktreeLink"||n.type==="submoduleLink"||n.type==="cloneLink"?a=Dp(r):a=$p(r),[a[0],a[1],a[2]]}function Lw(e,t){const r="nodrag nopan rounded-md border px-2 py-1 text-[10px] font-semibold shadow-sm backdrop-blur-sm";switch(e.type){case"orphanLink":return t?`${r} border-orange-400/35 bg-orange-500/14 text-orange-100`:`${r} border-orange-300 bg-orange-50 text-orange-700`;case"submoduleLink":return t?`${r} border-violet-400/30 bg-violet-500/14 text-violet-100`:`${r} border-violet-300 bg-violet-50 text-violet-700`;case"sessionLink":return t?`${r} border-emerald-400/30 bg-emerald-500/14 text-emerald-100`:`${r} border-emerald-300 bg-emerald-50 text-emerald-700`;case"cloneLink":return t?`${r} border-teal-400/30 bg-teal-500/14 text-teal-100`:`${r} border-teal-300 bg-teal-50 text-teal-700`;default:return t?`${r} border-sky-400/25 bg-slate-950/78 text-sky-100`:`${r} border-sky-300 bg-white/95 text-sky-700`}}function Pw(e){const t=l.useContext(Ii),r=e.data.graphEdge,[n,a,o]=_w(e),i=typeof e.label=="string"?e.label:void 0;return s.jsxs(s.Fragment,{children:[s.jsx(Tp,{id:e.id,path:n,markerEnd:e.markerEnd,style:e.style,interactionWidth:24}),e.label&&s.jsx(_p,{children:s.jsx("div",{className:Lw(r,t.isDark),title:i,style:{position:"absolute",transform:`translate(-50%, -50%) translate(${a}px, ${o}px)`,pointerEvents:"none",maxWidth:sw.maxWidth},children:s.jsx("span",{className:"block truncate",children:e.label})})})]})}const Rw={meshEdge:Pw};async function Dw(e,t,r,n,a){const o=await xm(e,r,n,a);return jm(e,o,t,r)}async function $w(e,t=Js("dark"),r=!1,n="LR"){const a=await xm(e,r,n);return jm(e,a,t,r)}function jm(e,t,r,n=!1){const a=new Set(t.nodes.map(m=>m.id)),o=t.nodes.map(m=>({id:m.id,type:m.type,position:m.position,data:{graphNode:m.graphNode,compact:n},selected:m.selected,draggable:m.draggable,selectable:m.selectable})),i=e.edges.filter(m=>a.has(m.source)&&a.has(m.target)),c=Fw(i),u=i.map(m=>{var d;return{id:m.id,source:m.source,target:m.target,label:c.has(m.id)?m.label:void 0,type:"meshEdge",data:{graphEdge:m,routePoints:(d=t.edgeRoutes.get(m.id))==null?void 0:d.points},animated:m.type==="orphanLink",markerEnd:m.direction==="directed"?{type:Rp.ArrowClosed,width:m.type==="submoduleLink"?16:18,height:m.type==="submoduleLink"?16:18,color:xc(m)}:void 0,style:{stroke:xc(m),strokeWidth:m.type==="orphanLink"?2.25:m.type==="submoduleLink"?1.7:m.type==="worktreeLink"?1.8:m.type==="cloneLink"?1.6:2,strokeDasharray:m.type==="orphanLink"?"5 4":m.type==="submoduleLink"?"4 3":m.type==="cloneLink"?"6 3":void 0},labelStyle:{fill:r.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:r.edgeLabelBackgroundColor,fillOpacity:1,stroke:r.edgeLabelBorderColor},labelBgPadding:[6,4],labelBgBorderRadius:7}});return{nodes:o,edges:u}}const Ew=3,Bw=2;function fc(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 Fw(e){const t=new Set,r=new Map;for(const n of e){if(!n.label)continue;const a=r.get(n.source);a?a.push(n):r.set(n.source,[n])}for(const n of r.values()){if(n.length<Ew){for(const o of n)t.add(o.id);continue}const a=[...n].sort((o,i)=>{const c=fc(i)-fc(o);return c!==0?c:o.id.localeCompare(i.id)});for(const o of a.slice(0,Bw))t.add(o.id)}return t}function xc(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 Ow(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 zw(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 Hw({data:e,viewportKey:t}){const r=Lp(),n=Pp(),a=l.useRef(null),o=l.useMemo(()=>pm(e),[e]),i=l.useMemo(()=>Jv(e),[e]);return l.useEffect(()=>{if(!r||e.nodes.length===0||a.current===t)return;let c=!1;const u=requestAnimationFrame(()=>{if(c)return;const m=i.length>0&&i.length<e.nodes.length;n.fitView({nodes:m?i.map(d=>({id:d})):void 0,padding:m?.24:.2,maxZoom:m?.98:.9,duration:260}),a.current=t});return()=>{c=!0,cancelAnimationFrame(u)}},[e.nodes.length,i,o,r,n,t]),null}const Ww=12;function Kw(e){return e>=16?"min-h-[720px]":e>=10?"min-h-[580px]":"min-h-[460px]"}function Uw({data:e,selectedNodeId:t=null,directionPref:r,onNodeClick:n,onNodeHoverChange:a,onEdgeHoverChange:o}){const{theme:i}=Ys(),c=l.useMemo(()=>Js(i),[i]),u=l.useMemo(()=>xw(e),[e]),m=l.useMemo(()=>bw(e),[e]),d=e.nodes.length>=gw,[p]=l.useState("LR"),h=r??p,b=l.useMemo(()=>h==="auto"?aw(e):h,[h,u,e]),g=e.nodes.length>=Ww,[f,w]=l.useState({nodes:[],edges:[]}),j=l.useRef(null),[y,v]=l.useState({width:0,height:0}),N=l.useMemo(()=>`${Xv(e,y.width,y.height)}::${b}`,[u,e,y.height,y.width,b]);l.useEffect(()=>{let x=!1;return $w(e,c,d,b).then(I=>{if(x)return;w(I);const C=requestAnimationFrame(()=>{if(x)return;const M=j.current;if(!M)return;const D=new Map;for(const P of I.nodes){const T=M.querySelector(`.react-flow__node[data-id="${CSS.escape(P.id)}"]`);T&&T.offsetHeight>0&&D.set(P.id,T.offsetHeight)}D.size!==0&&Dw(e,c,d,b,D).then(P=>{x||w(P)})});return()=>cancelAnimationFrame(C)}),()=>{x=!0}},[e,m,c,d,b]);const k=l.useMemo(()=>f.nodes.map(x=>({...x,selected:x.id===t})),[f.nodes,t]);return l.useEffect(()=>{const x=j.current;if(!x)return;const I=()=>{const M=Math.max(0,Math.round(x.clientWidth)),D=Math.max(0,Math.round(x.clientHeight));v(P=>P.width===M&&P.height===D?P:{width:M,height:D})};I();const C=typeof ResizeObserver=="function"?new ResizeObserver(()=>I()):null;return C==null||C.observe(x),window.addEventListener("resize",I),()=>{C==null||C.disconnect(),window.removeEventListener("resize",I)}},[]),s.jsx(Ii.Provider,{value:c,children:s.jsx(gm.Provider,{value:d,children:s.jsx(ym.Provider,{value:b,children:s.jsxs("div",{ref:j,className:`${c.graphShellClass} ${Kw(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(Sp,{nodes:k,edges:f.edges,nodeTypes:Mw,edgeTypes:Rw,minZoom:.18,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(x,I)=>n==null?void 0:n(I.data.graphNode),onNodeMouseEnter:(x,I)=>a==null?void 0:a(I.data.graphNode),onNodeMouseLeave:()=>a==null?void 0:a(null),onEdgeMouseEnter:(x,I)=>{var C;return o==null?void 0:o(((C=I.data)==null?void 0:C.graphEdge)??null)},onEdgeMouseLeave:()=>o==null?void 0:o(null),className:"h-full w-full",colorMode:c.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(Hw,{data:e,viewportKey:N}),s.jsx(Cp,{className:c.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),g&&s.jsx(Ip,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:Ow,nodeClassName:zw,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(Mp,{variant:Ap.Dots,gap:18,size:1.2,color:c.graphBackgroundDotColor})]})})]})})})})}function at(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function ke(...e){for(const t of e){if(typeof t!="string")continue;const r=t.trim();if(r)return r}}function Mt(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function It(...e){for(const t of e)if(typeof t=="boolean")return t}function Qa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function Mi(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 Gw(e,t){const r=typeof e=="string"?e.trim().replace(/[\\/]+$/,""):"",n=typeof t=="string"?t.trim():"";if(n){if(/^(?:[A-Za-z]:[\\/]|\/)/.test(n))return n;if(r)return`${r}/${n.replace(/^[\\/]+/,"")}`}}function Vw(e,t){if(!Array.isArray(e))return;const r=e.map(n=>{const a=at(n),o=ke(a.path),i=ke(a.commit),c=ke(a.repoPath,a.repo_root)??Gw(t,o);return!o||!i||!c?null:{path:o,commit:i,repoPath:c,dirty:It(a.dirty)??!1,outOfSync:It(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:Mt(a.lastCheckedAt,a.last_checked_at)??Date.now(),...ke(a.error)?{error:ke(a.error)}:{}}}).filter(n=>n!==null);return r.length>0?r:void 0}function qw(e){return It(e.isGitRepo)!==void 0||!!ke(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||Mt(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 Dn(e,t,r){const n=It(e.isGitRepo);if(!Object.keys(e).length||!qw(e))return;const a=n??!0,o=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(v=>typeof v=="string"):[],i=Mt(e.conflicts)??o.length,c=It(e.hasConflicts)??i>0,u=ke(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,m=Vw(e.submodules,u),d=ke(e.upstreamStatus,e.upstream_status),p=Mt(e.upstreamFetchedAt,e.upstream_fetched_at),h=ke(e.upstreamFetchError,e.upstream_fetch_error),b=ke(e.error),g=Mt(e.staged)??0,f=Mt(e.modified)??0,w=Mt(e.untracked)??0,j=Mt(e.deleted)??0,y=Mt(e.renamed)??0;return{workspace:ke(e.workspace,t.workspace)||"",repoRoot:u??null,isGitRepo:a,branch:ke(e.branch)??null,headCommit:ke(e.headCommit)??null,headMessage:ke(e.headMessage)??null,upstream:ke(e.upstream)??null,upstreamStatus:d??"unchecked",...p!==void 0?{upstreamFetchedAt:p}:{},...h?{upstreamFetchError:h}:{},ahead:Mt(e.ahead)??0,behind:Mt(e.behind)??0,staged:g,modified:f,untracked:w,deleted:j,renamed:y,dirty:It(e.dirty,e.isDirty,e.is_dirty)??(g+f+w+j+y>0||c),hasConflicts:c,conflictFiles:o,stashCount:Mt(e.stashCount,e.stash_count)??0,lastCheckedAt:(r==null?void 0:r.lastCheckedAt)??Mt(e.lastCheckedAt,e.last_checked_at)??Date.now(),...m?{submodules:m}:{},...b?{error:b}:{}}}function Yw(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+=Mi(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 Jw(e){const t=at(e.lastGit??e.last_git),r=at(t.result),n=at(t.status),a=at(r.status),o=at(e.lastProbe??e.last_probe),i=at(o.git),c=at(i.result),u=at(i.status),m=at(c.status);let d=null;for(const p of[n,a,u,m]){const h=Dn(p,e,{lastCheckedAt:Date.now()});if(!h)continue;const b=Yw(h);(!d||b>d.score)&&(d={git:h,score:b})}return d==null?void 0:d.git}function Xw(e){const t=Array.isArray(e==null?void 0:e.submodules)?e.submodules:[];let r=!1,n=!1;for(const a of t)a!=null&&a.outOfSync&&(n=!0),a!=null&&a.dirty&&(r=!0);return{dirty:r,outOfSync:n}}function Qw(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 sa(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=Xw(e);return t.outOfSync?"degraded":t.dirty||Qw(e)?"dirty":"online"}function Zw(e,t){const r=t?sa(t):void 0;return!e||e==="unknown"?r:e}function km(e){const t=at(e),r=ke(t.sessionId,t.session_id,t.id);return r?{sessionId:r,...ke(t.providerType,t.provider)?{providerType:ke(t.providerType,t.provider)}:{},...ke(t.state,t.status)?{state:ke(t.state,t.status)}:{},...ke(t.chatStatus,t.chat_status)?{chatStatus:ke(t.chatStatus,t.chat_status)}:{},...ke(t.lifecycle)?{lifecycle:ke(t.lifecycle)}:{},...ke(t.surfaceKind,t.surface_kind)?{surfaceKind:ke(t.surfaceKind,t.surface_kind)}:{},...ke(t.recoveryState,t.recovery_state)?{recoveryState:ke(t.recoveryState,t.recovery_state)}:{},...ke(t.workspace)?{workspace:ke(t.workspace)}:{},...ke(t.title)?{title:ke(t.title)}:{},...ke(t.role)?{role:ke(t.role)}:{},...It(t.isSelfCoordinator,t.is_self_coordinator)!==void 0?{isSelfCoordinator:It(t.isSelfCoordinator,t.is_self_coordinator)}:{},...ke(t.statusNote,t.status_note)?{statusNote:ke(t.statusNote,t.status_note)}:{},...ke(t.createdAt,t.created_at)?{createdAt:ke(t.createdAt,t.created_at)}:{},...ke(t.startedAt,t.started_at)?{startedAt:ke(t.startedAt,t.started_at)}:{},...ke(t.lastActivityAt,t.last_activity_at)?{lastActivityAt:ke(t.lastActivityAt,t.last_activity_at)}:{},...It(t.isCached,t.is_cached)!==void 0?{isCached:It(t.isCached,t.is_cached)}:{}}:null}function ej(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 a=t.map(km).filter(o=>o!==null);if(a.length>0)return a}const r=at(e.activeSession??e.active_session),n=ke(r.id,r.sessionId,r.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id);if(n)return[{sessionId:n,...ke(r.providerType,r.provider)?{providerType:ke(r.providerType,r.provider)}:{},...ke(r.state,r.status)?{state:ke(r.state,r.status)}:{},...ke(r.chatStatus,r.chat_status)?{chatStatus:ke(r.chatStatus,r.chat_status)}:{},...ke(r.statusNote,r.status_note)?{statusNote:ke(r.statusNote,r.status_note)}:{},...ke(r.createdAt,r.created_at)?{createdAt:ke(r.createdAt,r.created_at)}:{},...ke(r.startedAt,r.started_at)?{startedAt:ke(r.startedAt,r.started_at)}:{}}]}function tj(e){const t=at(e.connection);return Object.keys(t).length>0?t:void 0}function sj(e){const t=e==null?void 0:e.source,r=e==null?void 0:e.transport;return{...e,perspective:(e==null?void 0:e.perspective)??"selected_coordinator",source:t&&t!=="not_reported"?t:"mesh_peer_status",state:"connected",transport:r&&r!=="unknown"?r:"direct",reported:!0,reason:"Live peer git snapshot reported by the selected coordinator."}}function Ai(e){var r;const t=e.git;return!!(t&&(t.isGitRepo===!0||t.isGitRepo===!1||t.branch||t.upstream||t.headCommit||typeof t.lastCheckedAt=="number"||(((r=t.submodules)==null?void 0:r.length)??0)>0))}function bc(e){var n,a,o,i,c,u;let t=0;const r=e.git;return Ai(e)&&(t+=80,(r==null?void 0:r.isGitRepo)===!0&&(t+=20),(r==null?void 0:r.isGitRepo)===!1&&(t+=5),r!=null&&r.branch&&(t+=20),r!=null&&r.upstream&&(t+=12),r!=null&&r.headCommit&&(t+=12),t+=Mi(r==null?void 0:r.upstreamStatus),typeof(r==null?void 0:r.lastCheckedAt)=="number"&&(t+=6),t+=(((n=r==null?void 0:r.submodules)==null?void 0:n.length)??0)*6),(a=e.branchConvergence)!=null&&a.status&&(t+=12),(((o=e.connection)==null?void 0:o.state)==="connected"||((i=e.connection)==null?void 0:i.state)==="self")&&(t+=8),((c=e.connection)==null?void 0:c.transport)==="direct"&&(t+=4),((u=e.connection)==null?void 0:u.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 rj(e,t){var g,f,w,j;const r=bc(e),a=bc(t)>r?t:e,o=a===t?e:t,i=a.git??o.git,c=(((g=a.providers)==null?void 0:g.length)??0)>0?a.providers:o.providers,u=(((f=a.activeSessions)==null?void 0:f.length)??0)>0?a.activeSessions:o.activeSessions,m=(((w=a.activeSessionDetails)==null?void 0:w.length)??0)>0?a.activeSessionDetails:o.activeSessionDetails,d=(((j=a.providerPriority)==null?void 0:j.length)??0)>0?a.providerPriority:o.providerPriority,p=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")?sa(i):a.health,providers:c??[],activeSessions:u??[],...m&&m.length>0?{activeSessionDetails:m}:{},...d&&d.length>0?{providerPriority:d}:{},...p?{connection:p}:{},...i?{git:i}:{}},b=at(a.branchConvergence);return Object.keys(b).length>0?Object.assign(h,{branchConvergence:b}):delete h.branchConvergence,i&&(delete h.gitProbePending,delete h.error),h}function Nm(e){const t=at(e),r=ke(t.nodeId,t.id);if(!r)return null;const n=at(t.cachedStatus),a=Jw(t),o=a?void 0:Dn(at(t.git),t)??Dn(t,t),i=a??o,c=i?void 0:Dn(at(n.git),t),u=i??c,m=ke(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),d=ke(t.health),p=a?sa(u):Zw(d,i)||(u?sa(u):void 0)||ke(n.health)||m||ke(t.status)||"unknown",b=(a?void 0:ke(t.error))??(i?void 0:ke(n.error)),g=ej(t),f=Qa(t.activeSessions),w=(g==null?void 0:g.map(C=>C.sessionId))??[],j=Qa(t.providerPriority),y=It(t.gitProbePending,t.git_probe_pending),v=i?void 0:y,N=tj(t),k=at(t.branchConvergence??t.branch_convergence),x=N==null?void 0:N.state,I=a&&(!(N!=null&&N.reported)||x==="unknown")?sj(N):N;return{nodeId:r,machineLabel:ke(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,r)||r,workspace:ke(t.workspace,u==null?void 0:u.workspace)||"",...ke(t.repoRoot,t.repo_root,u==null?void 0:u.repoRoot)?{repoRoot:ke(t.repoRoot,t.repo_root,u==null?void 0:u.repoRoot)}:{},...ke(t.daemonId,t.daemon_id)?{daemonId:ke(t.daemonId,t.daemon_id)}:{},...ke(t.machineId,t.machine_id)?{machineId:ke(t.machineId,t.machine_id)}:{},...m?{machineStatus:m}:{},...It(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:It(t.isLocalWorktree,t.is_local_worktree)}:{},...ke(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:ke(t.worktreeBranch,t.worktree_branch)}:{},...ke(t.clonedFromNodeId,t.cloned_from_node_id)?{clonedFromNodeId:ke(t.clonedFromNodeId,t.cloned_from_node_id)}:{},health:p,...u?{git:u}:{},...v!==void 0?{gitProbePending:v}:{},providers:Qa(t.providers),activeSessions:f.length>0?f:w,...g&&g.length>0?{activeSessionDetails:g}:{},...j.length>0?{providerPriority:j}:{},...It(t.launchReady)!==void 0?{launchReady:It(t.launchReady)}:a?{launchReady:!0}:{},...ke(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)?{lastSeenAt:ke(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)}:{},...ke(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)?{updatedAt:ke(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)}:{},...I?{connection:I}:{},...Object.keys(k).length>0?{branchConvergence:k}:{},...b?{error:b}:{}}}function gc(e){const t=new Map;for(const r of e){const n=t.get(r.sessionId);t.set(r.sessionId,n?{...n,...r}:r)}return[...t.values()]}function Sm(e,t){const r=Array.isArray(e.coordinatorSessions)?e.coordinatorSessions:Array.isArray(e.coordinator_sessions)?e.coordinator_sessions:[],n=r.map(km).filter(a=>a!==null);return n.length===0?t:t.map(a=>{const o=n.filter(c=>{const u=at(r.find(h=>{const b=at(h);return ke(b.sessionId,b.session_id,b.id)===c.sessionId})),m=ke(u.nodeId,u.node_id),d=ke(u.daemonId,u.daemon_id),p=ke(u.workspace);return m&&m===a.nodeId?!0:d&&a.daemonId&&d===a.daemonId?!p||!a.workspace||p===a.workspace:!!(p&&a.workspace&&p===a.workspace)});if(o.length===0)return a;const i=gc([...a.activeSessionDetails??[],...o]);return{...a,activeSessionDetails:i,activeSessions:gc([...a.activeSessionDetails??[],...o,...(a.activeSessions??[]).map(c=>({sessionId:c}))]).map(c=>c.sessionId)}})}function nj(e){const t=at(e);return Array.isArray(t.sessions)||Array.isArray(t.active_session_details)||ke(t.daemon_id,t.machine_id,t.repo_root,t.worktree_branch,t.cloned_from_node_id)!==void 0||It(t.is_local_worktree)!==void 0}function Cm(e){const t=new Map,r=[];for(const n of e){const a=nj(n)?Nm(n)??n:n;if(!(a!=null&&a.nodeId))continue;const o=t.get(a.nodeId);if(!o){t.set(a.nodeId,a),r.push(a);continue}const i=rj(o,a);t.set(a.nodeId,i);const c=r.findIndex(u=>u.nodeId===a.nodeId);c>=0&&(r[c]=i)}return r}function Im(e){const t=Cm(e.nodes??[]);return{...e,nodes:Sm(e,t)}}function aj(e){var r;const t=e==null?void 0:e.git;return{nodeId:(e==null?void 0:e.nodeId)??null,chosenSource:t?"live_git":e!=null&&e.gitProbePending?"pending_git":"no_git",hasLiveGit:Ai(e??{git:void 0}),branch:(t==null?void 0:t.branch)??null,upstream:(t==null?void 0:t.upstream)??null,headCommit:(t==null?void 0:t.headCommit)??null,submoduleCount:((r=t==null?void 0:t.submodules)==null?void 0:r.length)??0,pendingGit:(e==null?void 0:e.gitProbePending)===!0,connection:e!=null&&e.connection?{state:e.connection.state,transport:e.connection.transport,source:e.connection.source}:null}}function oj(e){const t=ke(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(u=>Nm(u)).filter(u=>u!==null):null;if(!t||!n)return null;const a=Sm(e,Cm(n)),o=ke(e.meshName,e.mesh_name,e.name),i=ke(e.repoIdentity,e.repo_identity),c=ke(e.refreshedAt,e.refreshed_at,e.updatedAt,e.updated_at);return!o||!i||!c?null:{...e,meshId:t,meshName:o,repoIdentity:i,refreshedAt:c,nodes:a}}function ij(e){var o;let t=0;const r=at(e.sourceOfTruth),n=at(r.directPeerTruth);ke(r.currentStatus)==="live_git_and_session_probes"&&(t+=100),r.coordinatorOwnsLiveTruth===!0&&(t+=25),n.satisfied===!0&&(t+=15);for(const i of e.nodes){const c=i.git;if(!c){i.gitProbePending&&(t-=8);continue}t+=10,c.isGitRepo===!0&&(t+=5),c.isGitRepo===!1&&(t+=1),c.branch&&(t+=4),c.upstream&&(t+=3),c.headCommit&&(t+=3),t+=Mi(c.upstreamStatus),typeof c.ahead=="number"&&(t+=1),typeof c.behind=="number"&&(t+=1),typeof c.lastCheckedAt=="number"&&(t+=2),t+=(((o=c.submodules)==null?void 0:o.length)??0)*2}return t}function yc(e){let t=null;for(const r of e){const n=oj(at(r));if(!n)continue;const a=ij(n);(!t||a>t.score)&&(t={status:n,score:a})}return(t==null?void 0:t.status)??null}function Mm(e){const r=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,n=yc([r==null?void 0:r.status,r]);return n||yc([e==null?void 0:e.status,e])}const lj=5*60*1e3;function Am(e){return typeof e.daemonId=="string"&&e.daemonId.trim()?e.daemonId.trim():null}function Tm(e){return typeof e.machineId=="string"&&e.machineId.trim()?e.machineId.trim():null}function cj(e){var t,r,n;return((t=e.connection)==null?void 0:t.state)==="self"||e.isLocalWorktree===!0?"local":((r=e.connection)==null?void 0:r.transport)==="direct"||((n=e.connection)==null?void 0:n.transport)==="relay"||Am(e)||Tm(e)?"remote":"unknown"}function dj(e){return Ai(e)}function _m(e){var t;return dj(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function Lm(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function uj(e){return e.activeSessionDetails&&e.activeSessionDetails.length>0?e.activeSessionDetails:(e.activeSessions??[]).map(t=>({sessionId:t,workspace:e.workspace,isCached:!0}))}function Pm(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function Rm(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function Ti(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function mj(e){return Ti(e)?"degraded":Rm(e)?"dirty":"online"}function pj(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function vc(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 Za(e){return e.length===0?"unknown":e.reduce((t,r)=>vc(r)>vc(t)?r:t)}function hj(e){var o,i,c,u,m;const t=new Map,r=new Map;for(const d of e){const p=(i=(o=d.git)==null?void 0:o.branch)==null?void 0:i.trim();p&&(r.set(p,(r.get(p)??0)+1),(c=d.git)!=null&&c.upstream&&t.set(p,(t.get(p)??0)+1))}const n=[...t.entries()].sort((d,p)=>{if(p[1]!==d[1])return p[1]-d[1];const h=["main","master","develop","dev"],b=h.indexOf(d[0]),g=h.indexOf(p[0]);return b!==-1||g!==-1?b===-1?1:g===-1?-1:b-g:d[0].localeCompare(p[0])});return(u=n[0])!=null&&u[0]?n[0][0]:((m=[...r.entries()].sort((d,p)=>p[1]-d[1])[0])==null?void 0:m[0])??null}function fj(e,t){const r=[],n=e.git;return n?n.isGitRepo?(!n.branch&&n.headCommit&&r.push("Detached HEAD"),n.hasConflicts&&r.push("Merge conflicts need resolution"),n.branch&&t&&n.branch!==t&&!n.upstream&&r.push(`No upstream tracking for ${n.branch}`),n.upstream&&n.upstreamStatus&&n.upstreamStatus!=="fresh"&&r.push(`Upstream freshness unverified for ${n.branch??"workspace"}`),e.error&&r.push(e.error),r):(r.push("Not a git repository"),r):(r.push("No git status available"),r)}function wc(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 xj(e){return e.reduce((t,r)=>wc(r.status)>wc(t.status)?r:t)}function bj(e){const t=e.branchConvergenceSummary;if(Array.isArray(t==null?void 0:t.followUps))return t.followUps;const r=e.followUps;return Array.isArray(r)?r:(t==null?void 0:t.needsFollowUp)===!1||(t==null?void 0:t.unresolvedCount)===0?[]:null}function gj(e){var a,o,i;const t=e.sourceOfTruth,r=[],n=(a=t==null?void 0:t.fallback)==null?void 0:a.warning;return typeof n=="string"&&n.trim()&&r.push(n.trim()),(t==null?void 0:t.currentStatus)==="bootstrap_inventory_fallback"&&((o=t.directPeerTruth)==null?void 0:o.required)===!0&&((i=t.directPeerTruth)==null?void 0:i.satisfied)!==!0&&!r.some(c=>c.includes("direct mesh truth"))&&r.push("Direct mesh truth is not confirmed yet; this graph is drawn from setup inventory only."),r}function yj(e){const t=e.asyncRefineJobs;if(!Array.isArray(t))return[];const r=[];for(const n of t){if(!n||typeof n!="object")continue;const a=n,o=typeof a.jobId=="string"?a.jobId:null,i=a.status;o&&(i!=="accepted"&&i!=="running"&&i!=="completed"&&i!=="failed"||r.push({jobId:o,status:i,nodeId:typeof a.nodeId=="string"?a.nodeId:void 0,targetNodeId:typeof a.targetNodeId=="string"?a.targetNodeId:void 0,workspace:typeof a.workspace=="string"?a.workspace:void 0,branch:typeof a.branch=="string"?a.branch:void 0,into:typeof a.into=="string"?a.into:void 0,lastUpdatedAt:typeof a.lastUpdatedAt=="string"?a.lastUpdatedAt:void 0,startedAt:typeof a.startedAt=="string"?a.startedAt:void 0,completedAt:typeof a.completedAt=="string"?a.completedAt:void 0}))}return r}function jc(e){switch(e){case"running":case"accepted":return 0;case"failed":return 1;case"completed":default:return 2}}function kc(e){const t=e.lastUpdatedAt||e.completedAt||e.startedAt||"";return Lm(t)??0}function vj(e){return e.length===0?null:e.reduce((t,r)=>{const n=jc(t.status),a=jc(r.status);return a!==n?a<n?r:t:kc(r)>kc(t)?r:t})}function wj(e){var r,n;const t=new Map;for(const a of e){const o=((r=a.nodeId)==null?void 0:r.trim())||((n=a.targetNodeId)==null?void 0:n.trim());if(!o)continue;const i=t.get(o)??[];i.push(a),t.set(o,i)}return t}function jj(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 kj(e,t){var r,n;return{status:"merged_to_main",needsConvergence:!1,reason:"clean_default_branch_aggregate",nextStep:null,branch:e,defaultBranch:e,upstream:((r=t.find(a=>a.upstream))==null?void 0:r.upstream)??null,upstreamStatus:((n=t.find(a=>a.upstreamStatus))==null?void 0:n.upstreamStatus)??null,ahead:0,behind:0,dirty:!1,hasConflicts:!1}}function Nj(e,t){if(_m(e))return null;const r=e.branchConvergence;if(!r||typeof r!="object")return null;const n=r.status;if(!n||!["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"].includes(n))return null;const a=e.git,o=Pm(a)||Rm(a),i=!!(a!=null&&a.hasConflicts)||Ti(a),c=(a==null?void 0:a.ahead)??0,u=(a==null?void 0:a.behind)??0,m=(a==null?void 0:a.branch)??null,d=(a==null?void 0:a.upstream)??null,p=(a==null?void 0:a.upstreamStatus)??null,h=r.defaultBranch??t??null;return{status:n,needsConvergence:r.needsConvergence??n!=="merged_to_main",reason:r.reason??"provided_by_coordinator",nextStep:r.nextStep??null,branch:r.branch??m,defaultBranch:h,upstream:r.upstream??d,upstreamStatus:r.upstreamStatus??p,ahead:r.ahead??c,behind:r.behind??u,dirty:r.dirty??o,hasConflicts:r.hasConflicts??i}}function Sj(e,t){const r=Nj(e,t);return r?{...r,defaultBranch:r.defaultBranch??t}:null}function Cj(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function Ij(e){var u,m,d;const{nodeStatus:t,expectedSubmodulePaths:r,refreshedAtMs:n}=e,a=[],o=t.machineLabel||t.nodeId,i=t.git;if(!i){if(_m(t))return a.push(`${o} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:a};const p=t.health==="online"||t.machineStatus==="online"||((u=t.connection)==null?void 0:u.state)==="connected"||((m=t.connection)==null?void 0:m.state)==="self";return a.push(p?`${o} is online but no peer git snapshot is visible yet.`:`${o} has no peer git snapshot visible yet.`),{snapshotCompleteness:"missing_git",snapshotWarnings:a}}const c=new Set((i.submodules??[]).map(p=>p.path));if(r.size>0){const p=[...r].filter(h=>!c.has(h));p.length>0&&a.push(`${o} is missing submodule visibility for ${p.join(", ")} even though another peer reported it.`)}return((d=t.connection)==null?void 0:d.state)!=="self"&&n!==null&&typeof i.lastCheckedAt=="number"&&n-i.lastCheckedAt>lj&&a.push(`${o} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),a.some(p=>p.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:a}:a.some(p=>p.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:a}:{snapshotCompleteness:"complete",snapshotWarnings:a}}function Mj(e){const t=Im(e),n=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??hj(t.nodes),a=Lm(t.refreshedAt),o=new Set(t.nodes.flatMap(S=>{var A;return(((A=S.git)==null?void 0:A.submodules)??[]).map(B=>B.path)})),i=[],c=[],u=gj(t),m=new Map,d=wj(yj(t));for(const S of t.nodes){const A=S.git,B=(A==null?void 0:A.branch)??null,L=mj(A),$=Pm(A)||L==="dirty",F=fj(S,n),z=Sj(S,n),re=Ij({nodeStatus:S,expectedSubmodulePaths:o,refreshedAtMs:a}),J=typeof S.clonedFromNodeId=="string"?S.clonedFromNodeId:null,Y=uj(S),se=vj(d.get(S.nodeId)??[]),fe={id:S.nodeId,type:F.length>0?"orphanNode":"worktreeNode",label:S.machineLabel||S.nodeId.slice(0,8),workspace:S.workspace,branch:B,upstream:(A==null?void 0:A.upstream)??null,upstreamStatus:(A==null?void 0:A.upstreamStatus)??null,daemonId:Am(S),machineId:Tm(S),machineLabel:S.machineLabel||null,locality:cj(S),health:Za([S.health,L]),ahead:(A==null?void 0:A.ahead)??0,behind:(A==null?void 0:A.behind)??0,dirty:$,dirtyFiles:pj(A),hasConflicts:(A==null?void 0:A.hasConflicts)??!1,activeSessionCount:Y.length,activeSessions:Y.map(be=>be.sessionId),sessionDetails:Y,providers:S.providers??[],isOrphan:F.length>0,orphanReasons:F,error:S.error,nextStepHint:re.snapshotWarnings[0]??F[0]??(z==null?void 0:z.nextStep)??void 0,parentNodeId:null,clonedFromNodeId:J,worktreeBranch:S.worktreeBranch??null,submodulePath:null,submoduleCommit:(A==null?void 0:A.headCommit)??null,outOfSync:Ti(A),snapshotCompleteness:re.snapshotCompleteness,snapshotWarnings:re.snapshotWarnings,branchConvergence:z,refineJobStatus:(se==null?void 0:se.status)??null,refineJobId:(se==null?void 0:se.jobId)??null,refineJobBranch:(se==null?void 0:se.branch)??null,refineJobInto:(se==null?void 0:se.into)??null,source:S};if(i.push(fe),B){const be=m.get(B)??[];be.push(fe.id),m.set(B,be)}for(const be of(A==null?void 0:A.submodules)??[]){const X=`${fe.id}::submodule::${be.path}`,Q=be.path.split("/").filter(Boolean).pop()||be.path;i.push({id:X,type:"submoduleNode",label:Q,workspace:be.repoPath,branch:null,upstream:null,upstreamStatus:null,daemonId:fe.daemonId,machineId:fe.machineId,machineLabel:fe.machineLabel,locality:fe.locality,health:Cj(be),ahead:0,behind:0,dirty:be.dirty,dirtyFiles:be.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],error:be.error,nextStepHint:be.error||(be.outOfSync?`${be.path} is out of sync with the parent checkout`:be.dirty?`${be.path} has local changes`:`${be.path} is in sync with the parent checkout`),parentNodeId:fe.id,submodulePath:be.path,submoduleCommit:be.commit,outOfSync:be.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:fe.id,parentWorkspace:S.workspace,submodule:be}}),c.push({id:`${fe.id}--${X}`,source:fe.id,target:X,type:"submoduleLink",label:be.outOfSync?"submodule out of sync":"submodule",direction:"directed"})}}const p=n?`__branch_${n}`:null;if(p&&n){const A=(m.get(n)??[]).map(J=>i.find(Y=>Y.id===J)).filter(Boolean),B=A.map(J=>J.branchConvergence).filter(Boolean),L=bj(t),$=A.length>0&&A.every(J=>jj(J,n)),F=(L==null?void 0:L.length)===0&&$?kj(n,A):B.length>0?xj(B):null,z=(L==null?void 0:L.length)===0&&$?0:B.filter(J=>J.needsConvergence).length,re={id:p,type:"defaultBranchNode",label:n,workspace:t.repoIdentity,branch:n,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:"default branch",locality:"unknown",health:Za(A.map(J=>J.health)),ahead:0,behind:0,dirty:A.some(J=>J.dirty),dirtyFiles:A.reduce((J,Y)=>J+Y.dirtyFiles,0),hasConflicts:A.some(J=>J.hasConflicts),activeSessionCount:A.reduce((J,Y)=>J+Y.activeSessionCount,0),activeSessions:A.flatMap(J=>J.activeSessions),sessionDetails:A.flatMap(J=>J.sessionDetails),providers:[...new Set(A.flatMap(J=>J.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:z>0?`${z} workspace(s) on ${n} still need follow-up`:A.length>0?`${A.length} workspace(s) currently on ${n}`:"No workspaces currently checked out to the default branch",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:F,source:{nodeId:p,machineLabel:n,workspace:t.repoIdentity,health:Za(A.map(J=>J.health)),providers:[],activeSessions:[],activeSessionDetails:[]}};i.push(re);for(const J of i)if(!(J.id===p||J.type==="submoduleNode")){if(J.branch===n){c.push({id:`${p}--${J.id}`,source:p,target:J.id,type:"parentBranch",label:"checked out",direction:"undirected"});continue}if(J.branch){c.push({id:`${p}--${J.id}`,source:p,target:J.id,type:J.isOrphan?"orphanLink":"parentBranch",label:J.branch,direction:"undirected"});continue}J.isOrphan&&c.push({id:`${p}--${J.id}`,source:p,target:J.id,type:"orphanLink",label:"detached",direction:"undirected"})}}const h=new Set(i.map(S=>S.id)),b=new Set;for(const S of i){if(!S.clonedFromNodeId||S.type==="submoduleNode"||!h.has(S.clonedFromNodeId))continue;const A=`clone_${S.clonedFromNodeId}--${S.id}`;if(b.has(A))continue;b.add(A);const B=S.worktreeBranch??S.branch??void 0;c.push({id:A,source:S.clonedFromNodeId,target:S.id,type:"cloneLink",label:B?`cloned · ${B}`:"cloned",direction:"directed"})}const g=i.filter(S=>S.type!=="defaultBranchNode"),f=g.filter(S=>S.isOrphan).length,w=g.filter(S=>S.hasConflicts).length,j=g.filter(S=>S.health==="offline").length,y=g.filter(S=>S.type==="submoduleNode"&&S.outOfSync).length,v=g.filter(S=>{var A;return S.type!=="submoduleNode"&&((A=S.branchConvergence)==null?void 0:A.needsConvergence)}).length,N=g.filter(S=>{var A;return((A=S.branchConvergence)==null?void 0:A.status)==="blocked_review"}).length,k=g.filter(S=>{var A;return((A=S.branchConvergence)==null?void 0:A.status)==="pushed_feature_branch_needs_merge"}).length,x=g.filter(S=>{var A;return((A=S.branchConvergence)==null?void 0:A.status)==="cleanup_candidate"}).length,I=g.filter(S=>{var A;return((A=S.branchConvergence)==null?void 0:A.status)==="not_mergeable"}).length,C=g.filter(S=>S.snapshotWarnings.length>0).length,M=g.filter(S=>S.snapshotCompleteness==="pending_git").length,D=g.filter(S=>S.snapshotCompleteness==="missing_git").length,P=g.filter(S=>S.snapshotCompleteness==="missing_submodule_report").length,T=g.filter(S=>S.snapshotCompleteness==="stale").length,R=g.filter(S=>S.refineJobStatus==="running"||S.refineJobStatus==="accepted").length,O=g.filter(S=>S.refineJobStatus==="failed").length,K=[M>0?`${M} node(s) are still waiting for a live peer git snapshot`:null,D>0?`${D} node(s) have no visible peer git snapshot`:null,P>0?`${P} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,T>0?`${T} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return v>0&&u.push(`${v} workspace(s) still need follow-up before the mesh is converged`),f>0&&u.push(`${f} workspace(s) need attention before safe coordination`),N>0&&u.push(`${N} workspace(s) are blocked on branch convergence or upstream sync`),k>0&&u.push(`${k} clean feature branch workspace(s) still need merge follow-up`),x>0&&u.push(`${x} worktree workspace(s) are ready for refine / cleanup`),I>0&&u.push(`${I} workspace(s) have local changes or conflicts blocking convergence`),w>0&&u.push(`${w} workspace(s) report merge conflicts`),j>0&&u.push(`${j} node(s) are currently offline`),y>0&&u.push(`${y} submodule(s) are out of sync with their parent checkout`),u.push(...K),n||u.push("Could not infer a default branch from live mesh status"),{meshId:t.meshId,meshName:t.meshName,repoIdentity:t.repoIdentity,refreshedAt:t.refreshedAt,nodes:i,edges:c,stats:{totalNodes:g.length,onlineNodes:g.filter(S=>S.health==="online").length,dirtyNodes:g.filter(S=>S.dirty).length,orphanNodes:f,errorNodes:g.filter(S=>!!S.error||S.outOfSync).length,offlineNodes:j,followUpNodes:v,blockedReviewNodes:N,mergeReadyNodes:k,cleanupCandidateNodes:x,notMergeableNodes:I,incompleteSnapshotNodes:C,missingGitSnapshotNodes:D,missingSubmoduleSnapshotNodes:P,staleGitSnapshotNodes:T,activeRefineNodes:R,failedRefineNodes:O,totalActiveSessions:g.reduce((S,A)=>S+A.activeSessionCount,0)},warnings:u,snapshotWarnings:K}}const Aj={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0},_i=l.createContext(Js("dark"));function Oe({label:e,tone:t="default"}){const r=l.useContext(_i);return s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${r.badge(t)}`,children:e})}function dt({label:e,value:t}){const r=l.useContext(_i);return s.jsxs("div",{className:r.rowClass,children:[s.jsx("span",{className:r.rowLabelClass,children:e}),s.jsx("span",{className:r.rowValueClass,children:t})]})}function Nc(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 eo(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 $n(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const r=t.toLowerCase().replace(/[\s-]+/g,"_");return r.includes("approval")?"awaiting approval":r.includes("generating")||r.includes("running")||r.includes("busy")?"generating":r.includes("idle")||r.includes("ready")||r.includes("waiting_input")?"idle":r.replace(/_/g," ")}function Tj(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function _j(e){return e.startedAt||e.createdAt||null}function Lj(e){const t=_j(e);if(!t)return"runtime age not reported";const r=Date.parse(t);if(!Number.isFinite(r))return"runtime age not reported";const n=Math.max(0,Math.floor((Date.now()-r)/1e3));if(n<60)return`${n}s`;const a=Math.floor(n/60);if(a<60)return`${a}m`;const o=Math.floor(a/60);return o<48?`${o}h ${a%60}m`:`${Math.floor(o/24)}d ${o%24}h`}function Dm(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function Pj(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 Rj(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 Dj(e){var r;const t=[];for(const n of e.nodes){const a=n.activeSessionDetails&&n.activeSessionDetails.length>0?n.activeSessionDetails:(n.activeSessions??[]).map(o=>({sessionId:o,workspace:n.workspace,isCached:!0}));for(const o of a)t.push({nodeId:n.nodeId,machineLabel:n.machineLabel,workspace:n.workspace,branch:((r=n.git)==null?void 0:r.branch)??null,nodeHealth:n.health,session:o})}return t}function $j(e){return e.assignedNodeId||e.targetNodeId||null}function Sc(e){return e?e.slice(0,7):null}function Ej(e,t){var o,i,c;const r=Sc((o=e==null?void 0:e.git)==null?void 0:o.headCommit),n=((c=(i=e==null?void 0:e.git)==null?void 0:i.headMessage)==null?void 0:c.trim())||"";if(r||n)return[r,n].filter(Boolean).join(" · ");const a=t[0];return a?[Sc(a.commit),a.message].filter(Boolean).join(" · "):null}function Bj(e,t){const r=Ej(e,t);return r||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function Fj(e){const t=(e==null?void 0:e.result)??e,r=(t==null?void 0:t.log)??(e==null?void 0:e.log)??t;return Array.isArray(r==null?void 0:r.entries)?r.entries:[]}function Oj(e){var r,n,a,o,i,c;const t=((r=e.selectedSessionEntry)==null?void 0:r.session.workspace)||((n=e.selectedSessionEntry)==null?void 0:n.workspace)||((o=(a=e.selectedNodeStatus)==null?void 0:a.git)==null?void 0:o.workspace)||((i=e.selectedNodeStatus)==null?void 0:i.workspace)||null;if(t&&e.selectedSessionEntry){const u=((c=e.selectedNodeStatus)==null?void 0:c.daemonId)||e.coordinatorDaemonId;return u?{daemonId:u,workspace:t}:null}if(t&&e.selectedNodeStatus){const u=e.selectedNodeStatus.daemonId||e.coordinatorDaemonId;return u?{daemonId:u,workspace:t}:null}return null}function zj(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":Rj(e.connection)}function Cc(e){var r;const t=e.source;return t!=null&&t.kind?t.kind:((r=t==null?void 0:t.connection)==null?void 0:r.source)??"mesh_status"}function Ic(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 Hj(e){return e.direction==="directed"?"directed":"undirected"}function Mc(e,t){return t?e.nodes.find(r=>r.id===t)??null:null}function Wj(e){var t,r,n,a;return[e.meshId,e.refreshedAt,e.nodes.length,((r=(t=e.queue)==null?void 0:t.summary)==null?void 0:r.active)??"",((a=(n=e.ledger)==null?void 0:n.summary)==null?void 0:a.recentFailures)??"",...e.nodes.map(o=>{var i,c,u,m,d,p,h,b,g,f,w,j,y,v,N,k,x,I,C,M,D,P;return[o.nodeId,o.daemonId??"",o.machineId??"",o.machineLabel,o.machineStatus??"",((i=o.connection)==null?void 0:i.state)??"",((c=o.connection)==null?void 0:c.transport)??"",((u=o.connection)==null?void 0:u.source)??"",o.health,o.gitProbePending?1:0,((m=o.git)==null?void 0:m.branch)??"",((d=o.git)==null?void 0:d.upstream)??"",((p=o.git)==null?void 0:p.upstreamStatus)??"",((h=o.git)==null?void 0:h.ahead)??"",((b=o.git)==null?void 0:b.behind)??"",((g=o.git)==null?void 0:g.headCommit)??"",((f=o.git)==null?void 0:f.staged)??"",((w=o.git)==null?void 0:w.modified)??"",((j=o.git)==null?void 0:j.untracked)??"",((y=o.git)==null?void 0:y.deleted)??"",((v=o.git)==null?void 0:v.renamed)??"",(N=o.git)!=null&&N.hasConflicts?1:0,((k=o.git)==null?void 0:k.lastCheckedAt)??"",((x=o.activeSessions)==null?void 0:x.join(","))??"",((I=o.activeSessionDetails)==null?void 0:I.length)??"",((C=o.activeSessionDetails)==null?void 0:C.map(T=>[T.sessionId,T.providerType??"",T.state??"",T.chatStatus??"",T.lifecycle??"",T.role??"",T.isSelfCoordinator?1:0,T.statusNote??"",T.startedAt??"",T.createdAt??""].join("/")).join(","))??"",((M=o.providers)==null?void 0:M.join(","))??"",((D=o.providerPriority)==null?void 0:D.join(","))??"",o.error??"",(((P=o.git)==null?void 0:P.submodules)??[]).map(T=>[T.path,T.commit,T.dirty?1:0,T.outOfSync?1:0,T.error??""].join("/")).join(",")].join("|")})].join("::")}function Kj({canonicalStatus:e,queueSummary:t,ledgerSummary:r,isBootstrapMode:n,meshTheme:a,sessionEntries:o,inlineMode:i=!1}){var k;const c=t&&(t.active>0||t.historical>0),u=r.recentFailures>0||r.taskFailed>0,m=(k=e.queue)!=null&&k.tasks?e.queue.tasks.filter(x=>x.status==="failed"||x.status==="cancelled").slice(0,5):[],d=e.asyncRefineJobs,p=(d==null?void 0:d.filter(x=>x.status==="running"||x.status==="accepted"))??[],h=(d==null?void 0:d.filter(x=>x.status==="failed"))??[],b=e.staleDirectWorkSummary,g=b&&b.count>0;if(!c&&!u&&e.nodes.length===0&&!n&&p.length===0&&h.length===0&&!g&&o.length===0)return null;const f=a.isDark,w=`border-t ${f?"border-white/8":"border-slate-200"}`,j=`group w-full rounded-lg border text-xs ${f?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,y=`flex cursor-pointer list-none items-center gap-1.5 px-2.5 py-1.5 [&::-webkit-details-marker]:hidden ${a.textSecondary}`;function v({label:x,value:I,tone:C}){const M=C==="rose"?f?"text-rose-300":"text-rose-600":C==="sky"?f?"text-sky-300":"text-sky-600":C==="amber"?f?"text-amber-300":"text-amber-600":C==="emerald"?f?"text-emerald-300":"text-emerald-600":C==="muted"?a.textMuted:a.textPrimary;return s.jsxs("div",{className:`flex flex-col items-center rounded-lg border px-2 py-1.5 ${f?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/70"}`,children:[s.jsx("span",{className:`tabular-nums text-sm font-semibold leading-none ${M}`,children:I}),s.jsx("span",{className:`mt-0.5 text-[9px] uppercase tracking-wide ${a.textMuted}`,children:x})]})}const N=s.jsxs("div",{className:"flex flex-col gap-3 text-xs",children:[s.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t?s.jsxs(s.Fragment,{children:[s.jsx(v,{label:"Pending",value:t.pending}),s.jsx(v,{label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(v,{label:"Done",value:t.completed,tone:"emerald"}),s.jsx(v,{label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0})]}):s.jsxs(s.Fragment,{children:[s.jsx(v,{label:"Done",value:r.taskCompleted,tone:"emerald"}),s.jsx(v,{label:"Failed",value:r.taskFailed,tone:r.taskFailed>0?"rose":void 0}),s.jsx(v,{label:"Sessions",value:r.sessionLaunched}),s.jsx(v,{label:"Recent↯",value:r.recentFailures,tone:r.recentFailures>0?"amber":"muted"})]})}),t&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(v,{label:"Ledger done",value:r.taskCompleted,tone:"emerald"}),s.jsx(v,{label:"Sessions",value:r.sessionLaunched}),s.jsx(v,{label:"Recent↯",value:r.recentFailures,tone:r.recentFailures>0?"amber":"muted"})]}),r.lastActivityAt&&s.jsxs("div",{className:`flex items-center justify-between ${a.textMuted}`,children:[s.jsx("span",{children:"Last activity"}),s.jsx("span",{className:"font-mono text-[10px]",children:r.lastActivityAt.slice(5,16)})]}),e.nodes.length>0&&s.jsx("div",{className:`pt-2.5 ${w}`,children:s.jsx("div",{className:"flex flex-col gap-1",children:e.nodes.map(x=>{var T;const I=((T=x.connection)==null?void 0:T.state)??"unknown",C=I==="unknown"||I==="connecting",P=C?"bg-amber-400":I==="failed"||I==="closed"||I==="disconnected"?f?"bg-rose-400":"bg-rose-500":I==="connected"||I==="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 ${P}`}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${a.textSecondary}`,title:x.workspace,children:x.machineLabel}),s.jsx("span",{className:`shrink-0 font-mono text-[10px] ${a.textMuted}`,children:C?"…":I})]},x.nodeId)})})}),d&&d.length>0&&s.jsx("div",{className:`pt-2.5 ${w}`,children:s.jsxs("details",{className:j,children:[s.jsxs("summary",{className:y,children:[s.jsx("span",{className:"flex-1",children:"Refine jobs"}),s.jsx("span",{className:`tabular-nums ${f?"text-slate-400":"text-slate-500"}`,children: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(x=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${a.textMuted}`,children:[x.branch??x.jobId.slice(0,14),x.into?` → ${x.into}`:""]}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${x.status==="failed"?f?"text-rose-300":"text-rose-600":x.status==="running"||x.status==="accepted"?f?"text-sky-300":"text-sky-600":f?"text-emerald-300":"text-emerald-600"}`,children:x.status})]},x.jobId))})]})}),m.length>0&&s.jsx("div",{className:d&&d.length>0?"":`pt-2.5 ${w}`,children:s.jsxs("details",{className:j,children:[s.jsxs("summary",{className:y,children:[s.jsx("span",{className:`flex-1 ${f?"text-rose-300":"text-rose-600"}`,children:"Failed tasks"}),s.jsx("span",{className:`tabular-nums ${f?"text-rose-400":"text-rose-500"}`,children:m.length})]}),s.jsx("div",{className:"flex flex-col gap-1 px-2.5 pb-2",children:m.map(x=>s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`font-mono text-[10px] ${a.textMuted}`,children:x.id.slice(0,10)}),x.message&&s.jsx("span",{className:`flex-1 truncate ${f?"text-slate-300":"text-slate-700"}`,children:x.message.slice(0,55)})]}),x.cancelReason&&s.jsx("div",{className:`truncate text-[10px] ${a.textMuted}`,children:x.cancelReason.slice(0,55)})]},x.id))})]})}),g&&s.jsxs("div",{className:`flex items-center justify-between pt-2.5 ${w}`,children:[s.jsx("span",{className:a.textMuted,children:"Stale work"}),s.jsx("span",{className:`tabular-nums ${f?"text-amber-300":"text-amber-600"}`,children:b.count})]}),o.length>0&&s.jsx("div",{className:`pt-2.5 ${w}`,children:s.jsxs("details",{className:j,children:[s.jsxs("summary",{className:y,children:[s.jsx("span",{className:"flex-1",children:"Sessions"}),s.jsx("span",{className:`tabular-nums ${f?"text-slate-400":"text-slate-500"}`,children:o.length})]}),s.jsx("div",{className:"flex flex-col gap-0.5 px-2.5 pb-2",children:o.map(x=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${a.textMuted}`,title:x.session.sessionId,children:Dm(x.session.sessionId)}),s.jsx("span",{className:`shrink-0 ${a.textMuted}`,children:x.session.providerType||"?"}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${a.textMuted}`,children:$n(x.session)})]},x.session.sessionId))})]})})]});return i?N:s.jsxs("details",{className:`rounded-2xl border text-xs ${a.isDark?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsxs("summary",{className:`flex cursor-pointer list-none items-center gap-2 px-4 py-3 font-medium [&::-webkit-details-marker]:hidden ${a.textSecondary}`,children:[s.jsx("span",{className:"flex-1",children:"Mesh Health Panel"}),p.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:[p.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"]}),u&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[r.recentFailures," recent failures"]}),n&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-amber-400/20 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:"awaiting live data"})]}),N]})}function Uj(e){return e.nodes.length===0?!1:e.nodes.every(t=>t.health==="unknown"&&(!t.connection||t.connection.state==="unknown"))}function $m({status:e,emptyMessage:t="No live mesh graph is available for this coordinator yet.",daemonId:r=null,sendDaemonCommand:n=null,bootstrapFallback:a}){var U,H,q,ne;const{theme:o}=Ys(),i=l.useMemo(()=>Js(o),[o]),c=a??Uj(e),u=l.useMemo(()=>Im(e),[e]),m=l.useMemo(()=>Wj(u),[u]),d=l.useMemo(()=>Mj(u),[m]),[p,h]=l.useState(null),[b,g]=l.useState(null),[f,w]=l.useState(null),[j,y]=l.useState(null),[v,N]=l.useState({}),[k,x]=l.useState(null),[I,C]=l.useState(null),M=l.useMemo(()=>new Map(u.nodes.map(E=>[E.nodeId,E])),[u.nodes]),D=l.useMemo(()=>new Map(d.nodes.map(E=>[E.id,E])),[d.nodes]),P=((U=u.queue)==null?void 0:U.summary)??null,T=((H=u.ledger)==null?void 0:H.summary)??Aj,R=l.useMemo(()=>Dj(u),[u]),O=l.useMemo(()=>{const E=new Map;for(const W of R){const _=$n(W.session);E.set(_,(E.get(_)??0)+1)}return[...E.entries()].sort((W,_)=>_[1]-W[1])},[R]);l.useEffect(()=>{p&&(D.has(p)||(h(null),y(E=>!E||"nodeId"in E&&E.nodeId===p?null:E)))},[D,p]);const K=p?M.get(p)??null:null,S=Mc(d,p),A=Mc(d,b),B=f?d.edges.find(E=>E.id===f)??null:null,L=B?d.nodes.find(E=>E.id===B.source)??null:null,$=B?d.nodes.find(E=>E.id===B.target)??null:null;l.useEffect(()=>{var E,W,_;if(p)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:u.meshId,selectedNodeId:p,canonicalNode:aj(K),graphNode:S?{id:S.id,branch:S.branch,upstream:S.upstream,headCommit:S.submoduleCommit,submoduleCount:((W=(E=K==null?void 0:K.git)==null?void 0:E.submodules)==null?void 0:W.length)??0,snapshotCompleteness:S.snapshotCompleteness,snapshotWarnings:S.snapshotWarnings,branchConvergence:((_=S.branchConvergence)==null?void 0:_.status)??null}:null})}catch{}},[u.meshId,S,p,K]);const F=(j==null?void 0:j.kind)==="session"?R.find(E=>E.nodeId===j.nodeId&&E.session.sessionId===j.sessionId)??null:null,z=l.useMemo(()=>R.filter(E=>E.nodeId===p),[p,R]),re=Oj({coordinatorDaemonId:r,selectedNodeStatus:K,selectedSessionEntry:F}),J=(re==null?void 0:re.workspace)??null,Y=J?v[J]??null:null,se=Bj(K,(Y==null?void 0:Y.entries)??[]),fe=(S==null?void 0:S.daemonId)??(K==null?void 0:K.daemonId)??r??null,be=!!(S&&n&&fe&&S.type!=="submoduleNode"&&S.behind>0&&S.ahead===0&&S.dirtyFiles===0&&!S.dirty&&!S.hasConflicts&&S.upstreamStatus==="fresh"),X=l.useCallback(()=>{h(null),y(null),x(null)},[]);l.useEffect(()=>{x(null)},[p]);const Q=l.useCallback(async()=>{if(!S||!fe||!n||!be)return;C(S.id),x(null);const E=(K==null?void 0:K.workspace)??S.workspace??"";try{const W=await n(fe,"fast_forward_mesh_node",{meshId:u.meshId,nodeId:S.id,workspace:E,dryRun:!0,execute:!1}),_=(W==null?void 0:W.result)??W;if(x({phase:"dry_run",code:typeof(_==null?void 0:_.code)=="string"?_.code:void 0,error:typeof(_==null?void 0:_.operationError)=="string"?_.operationError:null,executed:(_==null?void 0:_.executed)===!0}),!(_!=null&&_.success)||_.code!=="fast_forward_available"||!window.confirm(`Apply fast-forward for ${S.label}?`))return;const pe=await n(fe,"fast_forward_mesh_node",{meshId:u.meshId,nodeId:S.id,workspace:E,dryRun:!1,execute:!0}),ue=(pe==null?void 0:pe.result)??pe;x({phase:"execute",code:typeof(ue==null?void 0:ue.code)=="string"?ue.code:void 0,error:typeof(ue==null?void 0:ue.operationError)=="string"?ue.operationError:null,executed:(ue==null?void 0:ue.executed)===!0})}catch(W){x({phase:"dry_run",error:W instanceof Error?W.message:"fast-forward failed"})}finally{C(null)}},[be,u.meshId,S,fe,n]);l.useEffect(()=>{if(!S)return;const E=W=>{W.key==="Escape"&&X()};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[X,S]),l.useEffect(()=>{if(!re||!n)return;const{daemonId:E,workspace:W}=re,_=v[W];if(_!=null&&_.loading||_&&(_.entries.length>0||_.error))return;let ie=!1;return N(pe=>{var ue;return{...pe,[W]:{loading:!0,error:null,entries:((ue=pe[W])==null?void 0:ue.entries)??[]}}}),n(E,"git_log",{workspace:W,limit:5}).then(pe=>{ie||N(ue=>({...ue,[W]:{loading:!1,error:null,entries:Fj(pe)}}))}).catch(pe=>{ie||N(ue=>({...ue,[W]:{loading:!1,error:pe instanceof Error?pe.message:"git_log failed",entries:[]}}))}),()=>{ie=!0}},[v,re,n]);const we=[...d.warnings??[],...u.nodes.filter(E=>E.machineStatus&&E.machineStatus!=="online").map(E=>`${E.machineLabel}: ${E.machineStatus}`)],ve=d.stats.incompleteSnapshotNodes>0,xe=d.stats.followUpNodes>0?`${d.stats.followUpNodes} need follow-up`:ve?"mesh visibility incomplete":"mesh converged",Ne=d.stats.followUpNodes>0?"danger":ve?"warn":"good",[ae,ge]=l.useState("LR"),me=E=>E?i.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":i.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(_i.Provider,{value:i,children:s.jsx("div",{className:"flex min-h-0 flex-1 flex-col gap-4",children:s.jsxs("div",{className:`${i.cardClass} relative flex min-h-0 flex-1 flex-col rounded-[28px]`,style:{minHeight:480},children:[s.jsxs("div",{className:`absolute inset-x-4 top-4 z-30 max-h-[42dvh] overflow-y-auto sm:static sm:mb-3 sm:overflow-visible shrink-0 flex flex-wrap items-start justify-between gap-2 px-4 pt-3 pb-2.5 border-b ${i.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-wrap gap-2 text-xs ${i.textSecondary}`,children:[s.jsx(Oe,{label:xe,tone:Ne}),d.stats.blockedReviewNodes>0&&s.jsx(Oe,{label:`${d.stats.blockedReviewNodes} blocked review`,tone:"danger"}),d.stats.notMergeableNodes>0&&s.jsx(Oe,{label:`${d.stats.notMergeableNodes} not mergeable`,tone:"danger"}),d.stats.mergeReadyNodes>0&&s.jsx(Oe,{label:`${d.stats.mergeReadyNodes} need merge`,tone:"warn"}),d.stats.cleanupCandidateNodes>0&&s.jsx(Oe,{label:`${d.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info"}),d.stats.offlineNodes>0&&s.jsx(Oe,{label:`${d.stats.offlineNodes} offline`,tone:"danger"}),d.stats.incompleteSnapshotNodes>0&&s.jsx(Oe,{label:`${d.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn"}),d.stats.missingGitSnapshotNodes>0&&s.jsx(Oe,{label:`${d.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn"}),d.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(Oe,{label:`${d.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn"}),d.stats.staleGitSnapshotNodes>0&&s.jsx(Oe,{label:`${d.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn"}),((P==null?void 0:P.active)??0)>0&&s.jsx(Oe,{label:`${(P==null?void 0:P.active)??0} active queue`,tone:"info"}),s.jsx(Oe,{label:`${d.stats.totalNodes} nodes`,tone:"default"}),d.stats.totalActiveSessions>0&&s.jsx(Oe,{label:`${d.stats.totalActiveSessions} attached chats`,tone:"info"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[s.jsxs("div",{className:i.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:()=>ge("auto"),className:me(ae==="auto"),title:"Auto-detect direction",children:"Auto"}),s.jsx("button",{type:"button",onClick:()=>ge("LR"),className:me(ae==="LR"),title:"Left to right",children:"LR"}),s.jsx("button",{type:"button",onClick:()=>ge("TB"),className:me(ae==="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 ${i.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 ${i.textSecondary} [&::-webkit-details-marker]:hidden`,children:(()=>{var _;const E=((_=u.asyncRefineJobs)==null?void 0:_.filter(ie=>ie.status==="failed").length)??0,W=T.recentFailures;return E>0?s.jsxs("span",{className:i.isDark?"text-rose-300":"text-rose-600",children:[E," refine failed"]}):W>0?s.jsxs("span",{className:i.isDark?"text-amber-300":"text-amber-600",children:[W," failures"]}):"Health"})()}),s.jsx("div",{className:`absolute right-0 z-40 mt-2 w-72 max-h-[70vh] overflow-y-auto rounded-xl border p-4 shadow-xl backdrop-blur-xl ${i.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsx(Kj,{canonicalStatus:u,queueSummary:P,ledgerSummary:T,isBootstrapMode:c,meshTheme:i,sessionEntries:R,inlineMode:!0})})]})}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${i.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 ${i.textSecondary} [&::-webkit-details-marker]:hidden`,children:"Legend"}),s.jsx("div",{className:`absolute right-0 z-40 mt-2 w-72 rounded-xl border p-3 shadow-xl backdrop-blur-xl ${i.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(Oe,{label:`${d.stats.dirtyNodes} dirty`,tone:d.stats.dirtyNodes>0?"warn":"good"}),s.jsx(Oe,{label:`${d.stats.orphanNodes} orphan`,tone:d.stats.orphanNodes>0?"warn":"good"}),s.jsx(Oe,{label:`${T.recentFailures} recent failures`,tone:T.recentFailures>0?"danger":"good"}),O.length===0?s.jsx(Oe,{label:"no session metadata"}):O.slice(0,2).map(([E,W])=>s.jsx(Oe,{label:`${W} ${E}`,tone:eo(E)},E))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Oe,{label:"Anchor = default branch",tone:"info"}),s.jsx(Oe,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(Oe,{label:"Submodule link = child checkout",tone:"warn"})]}),we.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:we.map(E=>s.jsx("span",{className:i.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:E},E))}),s.jsx("div",{className:`text-xs ${i.textMuted}`,children:"Hover nodes or edges for a quick preview. Click a node when you want pinned drill-down details."})]})})]})})]})]}),c&&d.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 ${i.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 ${i.isDark?"bg-amber-400":"bg-amber-500"}`,"aria-hidden":!0}),s.jsx("span",{children:"Awaiting live data — showing setup inventory until peer mesh_status probes succeed."})]}),s.jsxs("div",{className:"relative flex flex-1 min-w-0",style:{minHeight:360},children:[s.jsx("div",{className:"flex-1 min-w-0",children:d.nodes.length>0?s.jsx(Uw,{data:d,selectedNodeId:p,directionPref:ae,onNodeHoverChange:E=>{g((E==null?void 0:E.id)??null),E&&w(null)},onEdgeHoverChange:E=>{w((E==null?void 0:E.id)??null),E&&g(null)},onNodeClick:E=>{if((j==null?void 0:j.kind)==="node"&&p===E.id){h(null),y(null);return}h(E.id),y({kind:"node",nodeId:E.id})}}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:t})}),S&&(j==null?void 0:j.kind)==="node"&&s.jsxs("div",{role:"dialog",className:`absolute inset-x-3 bottom-3 top-20 sm:relative sm:inset-auto sm:w-72 sm:shrink-0 overflow-y-auto border-l p-4 ${i.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsx("div",{className:`mb-2 text-[10px] font-semibold uppercase tracking-wide ${i.textMuted}`,children:"Selected node"}),s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${i.textPrimary}`,children:S.label}),s.jsx("div",{className:`mt-0.5 font-mono text-[11px] ${i.textMuted}`,children:S.id.slice(0,16)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[S.behind>0&&s.jsx("button",{type:"button",onClick:()=>{Q()},disabled:!be||I===S.id,className:i.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:I===S.id?"Checking":"Heal"}),s.jsx("button",{type:"button",onClick:X,"aria-label":"Close detail panel",className:i.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 E=(K==null?void 0:K.health)??S.health;return E==="unknown"?s.jsx(Oe,{label:"connecting...",tone:"default"}):s.jsx(Oe,{label:E,tone:Nc(E)})})(),S.branch&&s.jsx(Oe,{label:S.branch,tone:"default"}),S.ahead>0&&s.jsx(Oe,{label:`ahead ${S.ahead}`,tone:"warn"}),S.behind>0&&s.jsx(Oe,{label:`behind ${S.behind}`,tone:"warn"}),S.dirtyFiles>0&&s.jsx(Oe,{label:`${S.dirtyFiles} dirty`,tone:"warn"}),(K==null?void 0:K.connection)&&K.connection.state!=="unknown"&&s.jsx(Oe,{label:zj(K),tone:Pj(K.connection)}),((q=K==null?void 0:K.connection)==null?void 0:q.state)==="unknown"&&s.jsx(Oe,{label:"mesh connecting...",tone:"warn"}),z.length>0&&s.jsx(Oe,{label:`${z.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[S.machineLabel&&s.jsx(dt,{label:"Machine",value:S.machineLabel}),S.locality&&S.locality!=="unknown"&&s.jsx(dt,{label:"Locality",value:S.locality}),s.jsx(dt,{label:"Workspace",value:(K==null?void 0:K.workspace)??S.workspace}),se&&s.jsx(dt,{label:"HEAD",value:se}),(S.dirtyFiles>0||S.ahead>0||S.behind>0)&&s.jsx(dt,{label:"Dirty/ahead/behind",value:`${S.dirtyFiles}/${S.ahead}/${S.behind}`}),z.length>0&&s.jsx(dt,{label:"Sessions",value:String(z.length)}),S.upstream&&s.jsx(dt,{label:"Upstream",value:S.upstream}),(()=>{var W;const E=((W=K==null?void 0:K.connection)==null?void 0:W.source)??Cc(S);return E&&E!=="unknown"?s.jsx(dt,{label:"Source",value:String(E)}):null})(),(()=>{var W;const E=(W=K==null?void 0:K.connection)==null?void 0:W.transport;return E&&E!=="unknown"?s.jsx(dt,{label:"Transport",value:E}):null})(),(()=>{const E=S.machineId??(K==null?void 0:K.machineId);return E?s.jsx(dt,{label:"Machine id",value:E}):null})(),(()=>{const E=S.daemonId??(K==null?void 0:K.daemonId);return E?s.jsx(dt,{label:"Daemon id",value:E}):null})()]}),z.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${i.textMuted}`,children:"Active Sessions"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:z.map(E=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${i.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 ${i.textMuted}`,title:E.session.sessionId,children:Dm(E.session.sessionId)}),s.jsx(Oe,{label:$n(E.session),tone:eo($n(E.session))})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 ${i.textMuted}`,children:[s.jsx("span",{className:"truncate",children:E.session.providerType||"provider unknown"}),s.jsx("span",{children:Tj(E.session)}),s.jsx("span",{children:Lj(E.session)})]}),E.session.statusNote&&s.jsx("div",{className:`mt-1 text-[10px] leading-4 ${i.textMuted}`,children:E.session.statusNote}),s.jsxs("div",{className:`mt-0.5 truncate ${i.textMuted}`,title:E.session.workspace||E.workspace,children:[(E.session.workspace||E.workspace).slice(0,38),E.branch?` · ${E.branch}`:""]})]},E.session.sessionId))})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${i.textMuted}`,children:"Ledger (mesh-wide)"}),s.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[s.jsx(dt,{label:"Completed",value:String(T.taskCompleted)}),s.jsx(dt,{label:"Failed",value:s.jsx("span",{className:T.taskFailed>0?i.isDark?"text-rose-300":"text-rose-600":"",children:T.taskFailed})}),s.jsx(dt,{label:"Launched",value:String(T.sessionLaunched)}),s.jsx(dt,{label:"Recent failures",value:s.jsx("span",{className:T.recentFailures>0?i.isDark?"text-amber-300":"text-amber-600":"",children:T.recentFailures})})]})]}),(()=>{var _,ie;const E=((_=u.queue)==null?void 0:_.tasks)??((ie=u.queue)==null?void 0:ie.items)??null;if(!Array.isArray(E)||E.length===0)return null;const W=E.filter(pe=>$j(pe)===p).slice(0,3);return W.length===0?null:s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${i.textMuted}`,children:"Queue tasks"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:W.map(pe=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${i.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 ${i.textMuted}`,children:pe.id.slice(0,12)}),s.jsx(Oe,{label:pe.status??"unknown",tone:eo(pe.status)})]}),pe.message&&s.jsx("div",{className:`mt-0.5 truncate ${i.textMuted}`,children:pe.message.slice(0,48)})]},pe.id))})]})})(),S.snapshotWarnings.length>0&&s.jsxs("div",{className:i.isDark?"mt-3 rounded-xl border border-amber-400/20 bg-amber-500/10 p-3 text-xs text-amber-100":"mt-3 rounded-xl border border-amber-300 bg-amber-50 p-3 text-xs text-amber-800",children:[s.jsx("div",{className:"font-medium",children:"Key warning"}),s.jsx("div",{className:"mt-1",children:S.snapshotWarnings[0]})]}),((ne=S.branchConvergence)==null?void 0:ne.nextStep)&&s.jsxs("div",{className:i.isDark?"mt-3 rounded-xl border border-sky-400/20 bg-sky-500/10 p-3 text-xs text-sky-100":"mt-3 rounded-xl border border-sky-300 bg-sky-50 p-3 text-xs text-sky-800",children:[s.jsx("div",{className:"font-medium",children:"Follow-up"}),s.jsx("div",{className:"mt-1",children:S.branchConvergence.nextStep})]}),k&&s.jsxs("div",{className:i.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:k.phase==="execute"?"Heal result":"Heal preview"}),s.jsx("div",{className:"mt-1",children:k.code??k.error??"No result code returned."})]})]}),!S&&A&&s.jsx("div",{className:"pointer-events-none absolute bottom-3 right-4 z-20",children:s.jsxs("section",{"aria-label":"Hovered node preview",className:i.isDark?"w-[22rem] rounded-2xl border border-white/12 bg-slate-950/94 p-4 shadow-2xl shadow-black/35 backdrop-blur-xl":"w-[22rem] rounded-2xl border border-slate-200 bg-white/96 p-4 shadow-2xl shadow-slate-900/12 backdrop-blur-xl",children:[s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${i.textPrimary}`,children:A.label}),s.jsx("div",{className:`mt-1 font-mono text-[11px] ${i.textMuted}`,children:A.id.slice(0,16)})]}),s.jsx(Oe,{label:"hover preview",tone:"info"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[A.health==="unknown"?s.jsx(Oe,{label:"...",tone:"default"}):s.jsx(Oe,{label:A.health,tone:Nc(A.health)}),A.branch&&s.jsx(Oe,{label:A.branch,tone:"default"}),A.ahead>0&&s.jsx(Oe,{label:`ahead ${A.ahead}`,tone:"warn"}),A.behind>0&&s.jsx(Oe,{label:`behind ${A.behind}`,tone:"warn"}),A.dirtyFiles>0&&s.jsx(Oe,{label:`${A.dirtyFiles} dirty`,tone:"warn"}),A.activeSessionCount>0&&s.jsx(Oe,{label:`${A.activeSessionCount} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[A.machineLabel&&s.jsx(dt,{label:"Machine",value:A.machineLabel}),A.locality&&A.locality!=="unknown"&&s.jsx(dt,{label:"Locality",value:A.locality}),s.jsx(dt,{label:"Workspace",value:A.workspace}),A.upstream&&s.jsx(dt,{label:"Upstream",value:A.upstream}),(()=>{const E=Cc(A);return E&&E!=="unknown"?s.jsx(dt,{label:"Source",value:E}):null})()]})]})}),!S&&!A&&B&&s.jsx("div",{className:"pointer-events-none absolute bottom-3 right-4 z-20",children:s.jsxs("section",{"aria-label":"Hovered edge preview",className:i.isDark?"w-[20rem] rounded-2xl border border-white/12 bg-slate-950/94 p-4 shadow-2xl shadow-black/35 backdrop-blur-xl":"w-[20rem] rounded-2xl border border-slate-200 bg-white/96 p-4 shadow-2xl shadow-slate-900/12 backdrop-blur-xl",children:[s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${i.textPrimary}`,children:B.label||Ic(B)}),s.jsx("div",{className:`mt-1 text-[11px] ${i.textMuted}`,children:B.id})]}),s.jsx(Oe,{label:"hover preview",tone:"info"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[s.jsx(Oe,{label:Ic(B),tone:"default"}),s.jsx(Oe,{label:Hj(B),tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs",children:[s.jsx(dt,{label:"From",value:(L==null?void 0:L.label)??B.source}),s.jsx(dt,{label:"To",value:($==null?void 0:$.label)??B.target}),s.jsx(dt,{label:"Label",value:B.label??"none"})]})]})})]})]})})})}function xt(e){return typeof e=="string"?e.trim():""}function Bo(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Li(...e){const t=new Set;for(const r of e){const n=xt(r);n&&t.add(n)}return[...t]}function Gj(e,t){var p,h;const r=Bo(e==null?void 0:e.settings),n=xt((p=e==null?void 0:e.coordinator)==null?void 0:p.meshId)||xt(r.meshCoordinatorFor),a=xt(r.meshNodeFor),o=!!n||!!a,i=n===t||a===t;if(o&&!i)return null;const c=Bo(e==null?void 0:e.activeChat),u=Li(e==null?void 0:e.id,e==null?void 0:e.sessionId,e==null?void 0:e.session_id,e==null?void 0:e.providerSessionId,e==null?void 0:e.provider_session_id,e==null?void 0:e.targetSessionId,e==null?void 0:e.target_session_id,c.sessionId,c.session_id,c.providerSessionId,c.provider_session_id),m=u[0]||"";if(!m)return null;const d=n===t?xt((h=e==null?void 0:e.coordinator)==null?void 0:h.role)||"coordinator":a===t?xt(r.meshNodeRole)||"worker":xt(e==null?void 0:e.role)||xt(r.meshNodeRole)||void 0;return{sessionId:m,aliases:u,meshId:t,nodeId:i&&xt(r.meshNodeId)||null,providerType:xt(e==null?void 0:e.providerType)||void 0,state:xt(e==null?void 0:e.status)||void 0,chatStatus:xt(c.status)||void 0,lifecycle:xt(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:xt(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:xt(e==null?void 0:e.runtimeRecoveryState)||void 0,...d?{role:d}:{},...i?{isSelfCoordinator:n===t}:{},workspace:xt(e==null?void 0:e.workspace)||null}}function Em(e,t){var n;return t?(Array.isArray((n=e.status)==null?void 0:n.sessions)?e.status.sessions:[]).map(a=>Gj(a,t)).filter(a=>a!==null):[]}function ra(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function Vj(e,t){const r=new Set(ra(t));return ra(e).some(n=>r.has(n))}function qj(e,t){const r=t.filter(a=>!!a);return r.length===0?e:[...e.filter(a=>!r.some(o=>Vj(a,o))),...r]}function Yj(e,t){if(t.length===0)return e;const r=new Map;for(const i of t)for(const c of ra(i))r.set(c,i);let n=!1;const o=(e.nodes??[]).map((i,c)=>{const u=Array.isArray(i.activeSessionDetails)?i.activeSessionDetails:Array.isArray(i.sessions)?i.sessions:[],m=new Map;for(const h of u){const b=Li(h==null?void 0:h.sessionId,h==null?void 0:h.session_id,h==null?void 0:h.id,h==null?void 0:h.providerSessionId,h==null?void 0:h.provider_session_id),g=b[0]||"";if(!g)continue;const f=b.map(w=>r.get(w)).find(Boolean);f&&(n=!0),m.set(g,f?{...h,sessionId:g,providerType:f.providerType||h.providerType,state:f.state||h.state,chatStatus:f.chatStatus||h.chatStatus,lifecycle:f.lifecycle||h.lifecycle,surfaceKind:f.surfaceKind||h.surfaceKind,recoveryState:f.recoveryState||h.recoveryState,role:f.role||h.role,isSelfCoordinator:f.isSelfCoordinator??h.isSelfCoordinator,workspace:f.workspace||h.workspace}:{...h,sessionId:g})}for(const h of i.activeSessions??[])m.has(h)||m.set(h,{sessionId:h,workspace:i.workspace,isCached:!0});const d=c===0;for(const h of t){if(ra(h).some(w=>m.has(w)))continue;const g=h.nodeId!=null&&h.nodeId===i.nodeId,f=h.isSelfCoordinator&&!h.nodeId&&d;!g&&!f||(n=!0,m.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 p=[...m.values()];return p.length===0?i:{...i,activeSessionDetails:p,activeSessions:p.map(h=>h.sessionId)}});return n?{...e,nodes:o}:e}function Jj(e,t){const n=Em(e,t).map(a=>{var u;const o=(Array.isArray((u=e.status)==null?void 0:u.sessions)?e.status.sessions:[]).find(m=>xt(m==null?void 0:m.id)===a.sessionId),i=Bo(o==null?void 0:o.activeInteractivePrompt),c=o!=null&&o.meshQueueStats&&typeof o.meshQueueStats=="object"?JSON.stringify(o.meshQueueStats):"";return[a.sessionId,a.providerType??"",a.state??"",a.chatStatus??"",a.lifecycle??"",a.surfaceKind??"",a.recoveryState??"",xt(i.status)||xt(i.kind)||xt(i.type),a.nodeId??"",a.isSelfCoordinator?"coordinator":"worker",c].join("|")}).filter(a=>!!a).sort();return n.length>0?n.join(`
81
+ `):null}function Bm({status:e,daemonId:t,extraDaemonIds:r,meshId:n,sendData:a,extraLiveSessions:o=[]}){const[i,c]=l.useState(new Map),u=l.useRef(new Map),m=l.useMemo(()=>{const b=new Set;if(t&&b.add(t),r)for(const g of r)g&&b.add(g);return[...b].sort()},[t,r]),d=m.join(",");l.useEffect(()=>{u.current=new Map,c(new Map)},[t,n]),l.useEffect(()=>{if(!n||!a||m.length===0)return;const b=m.map(g=>qt.subscribe({sendData:a},g,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${g}`,params:{includeSessions:!0}},f=>{if(f.topic!=="daemon.metadata")return;const w=Jj(f,n);if(w===(u.current.get(g)??null))return;u.current.set(g,w);const j=Em(f,n);c(y=>{const v=new Map(y);return v.set(g,j),v})}));return()=>{for(const g of b)g()}},[d,n,a]);const p=l.useMemo(()=>{const b=[];for(const g of i.values())b.push(...g);return b},[i]),h=l.useMemo(()=>qj(p,o),[o,p]);return l.useMemo(()=>e?Yj(e,h):null,[h,e])}const Ac=[1500,3e3,5e3,8e3,12e3];function Xj(e){var t,r,n,a,o,i;return!!(((t=e.git)==null?void 0:t.isGitRepo)===!0||(r=e.git)!=null&&r.branch||(n=e.git)!=null&&n.upstream||(a=e.git)!=null&&a.headCommit||(o=e.git)!=null&&o.workspace||(i=e.git)!=null&&i.repoRoot)}function Qj(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>{var r;return Xj(t)?!1:t.gitProbePending||((r=t.connection)==null?void 0:r.state)==="connecting"?!0:t.machineStatus==="online"||t.launchReady===!0})}function Zj(e){return!Number.isInteger(e)||e<0?Ac[0]:Ac[e]??null}const to=new Map;function ek(e,t){return!e||!t?null:`${e}::${t}`}function tk(e,t){var o,i,c,u;if(!t||!e.sessionId)return null;const r=((o=e.coordinator)==null?void 0:o.meshId)??(typeof((i=e.settings)==null?void 0:i.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),n=typeof((c=e.settings)==null?void 0:c.meshNodeFor)=="string"?e.settings.meshNodeFor:null;if(r!==t&&n!==t)return null;const a=typeof((u=e.settings)==null?void 0:u.meshNodeId)=="string"?e.settings.meshNodeId:null;return{sessionId:e.sessionId,aliases:Li(e.sessionId,e.providerSessionId,e.historySessionId,e.nativeSessionId),meshId:t,nodeId:a,providerType:e.agentType,state:e.status,chatStatus:e.status,role:r===t?"coordinator":"worker",isSelfCoordinator:r===t,workspace:e.workspacePath??null}}function sk({activeConv:e,sendDaemonCommand:t,onClose:r}){var L,$,F,z,re,J;const n=((L=e.coordinator)==null?void 0:L.meshId)??(typeof(($=e.settings)==null?void 0:$.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),a=e.daemonId??null,o=ek(a,n),i=o?to.get(o)??null:null,c=Ou(),{sendData:u}=lt(),{theme:m}=Ys(),d=l.useMemo(()=>Js(m),[m]),p=l.useMemo(()=>tk(e,n),[e.agentType,(F=e.coordinator)==null?void 0:F.meshId,e.sessionId,(z=e.settings)==null?void 0:z.meshCoordinatorFor,(re=e.settings)==null?void 0:re.meshNodeFor,(J=e.settings)==null?void 0:J.meshNodeId,e.status,e.workspacePath,n]),[h,b]=l.useState(i),[g,f]=l.useState(!1),[w,j]=l.useState(!1),[y,v]=l.useState(null),[N,k]=l.useState((i==null?void 0:i.refreshedAt)??null),x=l.useRef(i!==null),I=l.useRef(!1),C=l.useRef(!1),M=l.useRef(!0),D=l.useRef(0),P=l.useRef(null);l.useEffect(()=>{x.current=h!==null},[h]);const T=l.useCallback(()=>{P.current!==null&&(clearTimeout(P.current),P.current=null)},[]);l.useEffect(()=>{T(),D.current=0;const Y=o?to.get(o)??null:null;b(Y),k((Y==null?void 0:Y.refreshedAt)??null),x.current=Y!==null,C.current=!1,j(!1),v(null)},[o,T]);const R=l.useCallback(async(Y=!1,se=!1)=>{if(!a||!n){v("This coordinator does not expose a live mesh id."),b(null);return}if(I.current){Y&&(C.current=!0);return}se||(T(),D.current=0),I.current=!0;const fe=!x.current;f(fe),j(Y&&x.current),v(null);try{const be=c!=null&&c.loadMeshStatus?await c.loadMeshStatus(a,n,{refresh:Y,retryProfile:"settled"}):await t(a,"mesh_status",{meshId:n,refresh:Y}),X=Mm(be);if(!X){v("mesh_status returned an unexpected payload.");return}if(o&&to.set(o,X),b(X),x.current=!0,k(X.refreshedAt||new Date().toISOString()),Qj(X.nodes)){const Q=Zj(D.current);Q!==null&&M.current&&(D.current+=1,P.current=setTimeout(()=>{M.current&&R(!0,!0)},Q))}else D.current=0}catch(be){v(be instanceof Error?be.message:"Failed to load live mesh status")}finally{I.current=!1,f(!1),j(!1),C.current&&M.current&&(C.current=!1,window.setTimeout(()=>{M.current&&R(!0)},0))}},[o,T,a,n,c,t]);l.useEffect(()=>(M.current=!0,D.current=0,R(!0),()=>{M.current=!1,T()}),[R,T]),l.useEffect(()=>{const Y=se=>{se.key==="Escape"&&r()};return window.addEventListener("keydown",Y),()=>window.removeEventListener("keydown",Y)},[r]);const O=(h==null?void 0:h.meshName)||n||"Repo Mesh",K=l.useMemo(()=>p?[p]:[],[p]),S=Bm({status:h,daemonId:a,meshId:n,sendData:u,extraLiveSessions:K}),A=N?new Date(N).toLocaleTimeString():null,B=l.useMemo(()=>g?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[g]);return s.jsx("div",{className:d.dialogOverlayClass,onClick:r,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:d.dialogShellClass,onClick:Y=>Y.stopPropagation(),children:[s.jsxs("div",{className:d.dialogHeaderClass,children:[s.jsx("div",{className:"min-w-0 flex-1",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-sky-400/20 bg-sky-500/12 text-sky-200 shadow-[0_12px_30px_rgba(14,165,233,0.18)]",children:s.jsx(Qt,{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:O}),s.jsx("span",{className:d.dialogKickerClass,children:"Mesh observability"})]}),s.jsxs("p",{className:d.dialogSubtitleClass,children:[it(e),e.workspaceName?` · ${e.workspaceName}`:"",h!=null&&h.repoIdentity?` · ${h.repoIdentity}`:""]})]})]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end",children:[A&&s.jsx("span",{className:d.dialogRefreshedChipClass,children:w?"Refreshing mesh...":`Refreshed ${A}`}),!w&&h&&s.jsx("span",{className:d.dialogRefreshedChipClass,children:u&&!y?"Live daemon metadata":"Metadata subscription unavailable"}),s.jsx("button",{type:"button",onClick:()=>{R(!0)},disabled:g||w,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:g||w?"Refreshing...":"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:d.dialogCloseButtonClass,"aria-label":"Close mesh graph",children:s.jsx(vt,{size:16})})]})]}),y&&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:y}),s.jsx("div",{className:d.dialogBodyClass,children:S?s.jsx($m,{status:S,emptyMessage:B,daemonId:a,sendDaemonCommand:t}):s.jsx("div",{className:d.dialogEmptyClass,children:B})})]})})}function rk(e,t){const{sendCommand:r}=lt(),[n,a]=l.useState(null),[o,i]=l.useState(!1);l.useEffect(()=>{if(!e||!t){a(null);return}i(!0),r(e,"git_remote_url",{workspace:t}).then(u=>{const m=(u==null?void 0:u.result)??u;a(typeof(m==null?void 0:m.remoteUrl)=="string"?m.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>i(!1))},[e,t,r]);const c=nk(n);return{remoteUrl:n,githubUrl:c,loading:o}}function nk(e){if(!e)return null;const t=e.match(/git@github\.com[:/](.+?)(?:\.git)?$/);if(t)return`https://github.com/${t[1]}`;const r=e.match(/https?:\/\/github\.com\/(.+?)(?:\.git)?$/);return r?`https://github.com/${r[1]}`:null}const Fm=5e3;function ak(e){return`git:${e}`}function ok({workspace:e,includeDiffSummary:t=!1,intervalMs:r=Fm}){return{type:"subscribe",topic:"workspace.git",key:ak(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function Pi(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Cs(e,t){if(e instanceof Error)return e.message;if(e&&typeof e=="object"){const r=e;if(typeof r.error=="string"&&r.error.trim())return r.error;if(typeof r.message=="string"&&r.message.trim())return r.message}return t}function ik(e){const t=Pi(e);return(t==null?void 0:t.success)===!1?{status:null,error:Cs(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:Cs(t,"Git status response did not include status")}}function lk(e){const t=Pi(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:Cs(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:Cs(t,"Git diff summary response did not include diffSummary")}}function so(e){return e===void 0||typeof e=="boolean"}function ck(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&so(t.binary)&&so(t.truncated)&&so(t.staged)}function dk(e){const t=Pi(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Cs(t,"Git file diff request failed")}:ck(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:Cs(t,"Git file diff response did not include a valid diff object")}}function uk({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=Fm}){const{sendCommand:o,sendData:i}=lt(),c=typeof t=="string"?t.trim():"",u=!!(r&&e&&c),[m,d]=l.useState(null),[p,h]=l.useState(null),[b,g]=l.useState(!1),[f,w]=l.useState(null),j=l.useCallback(async()=>{if(!(!u||!e||!c)){g(!0),w(null);try{const v=ik(await o(e,"git_status",{workspace:c}));if(v.error){d(null),h(null),w(v.error);return}if(d(v.status),!n){h(null);return}const N=lk(await o(e,"git_diff_summary",{workspace:c}));if(N.error){h(null),w(N.error);return}h(N.diffSummary)}catch(v){w(Cs(v,"Git status request failed"))}finally{g(!1)}}},[u,e,n,o,c]),y=l.useMemo(()=>c?ok({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return l.useEffect(()=>{if(!u||!e||!c||!y){d(null),h(null),g(!1),w(null);return}const v=i?qt.subscribe({sendData:i},e,y,N=>{var k,x;N.workspace===c&&(d(N.status),h(N.diffSummary??null),w(((k=N.status)==null?void 0:k.error)||((x=N.diffSummary)==null?void 0:x.error)||null),g(!1))},{retryIntervalMs:1e3}):null;return j(),()=>{v==null||v()}},[u,e,j,y,i,c]),{status:m,diffSummary:p,loading:b,error:f,refresh:j}}const mk={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},pk={added:"text-emerald-400",modified:"text-orange-400",deleted:"text-red-400",renamed:"text-sky-400",copied:"text-sky-400",untracked:"text-zinc-400",conflict:"text-red-400 font-bold"};function Tc(e){return e.split("/").pop()??e}function hk(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function fk({files:e,truncated:t,onFileClick:r,selectedPath:n,className:a=""}){return e.length===0?s.jsx("p",{className:"px-3 py-2 text-xs text-text-secondary",children:"No changed files."}):s.jsxs("div",{className:`flex flex-col ${a}`,children:[s.jsx("ul",{className:"min-w-0 divide-y divide-border/30",children:e.map(o=>{const i=n===o.path,c=mk[o.status]??"?",u=pk[o.status]??"text-zinc-400",m=hk(o.path),d=Tc(o.path),p=o.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 align-middle",title:"Staged"}):null;return s.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${i?"bg-surface-elevated":""}`,onClick:()=>r==null?void 0:r(o),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${u}`,title:o.status,children:c}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[m&&s.jsxs("span",{className:"text-text-secondary",children:[m,"/"]}),s.jsx("span",{className:"text-text-primary",children:d}),o.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",Tc(o.oldPath)]}),p]}),!o.binary&&(o.insertions>0||o.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[o.insertions>0&&s.jsxs("span",{className:"text-emerald-500",children:["+",o.insertions]}),o.insertions>0&&o.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),o.deletions>0&&s.jsxs("span",{className:"text-red-400",children:["-",o.deletions]})]}),o.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${o.path}-${o.staged?"S":"U"}`)})}),t&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",s.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function xk(e,t){let r="text-text-secondary";return e.startsWith("+")&&!e.startsWith("+++")?r="bg-emerald-500/10 text-emerald-300":e.startsWith("-")&&!e.startsWith("---")?r="bg-red-500/10 text-red-300":e.startsWith("@@")?r="text-sky-400":(e.startsWith("diff ")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ "))&&(r="text-text-secondary"),s.jsx("div",{className:`px-3 ${r}`,children:s.jsx("code",{className:"whitespace-pre font-mono text-[11px] leading-5",children:e})},t)}function Om({diff:e,binary:t,truncated:r,loading:n,error:a,className:o=""}){const i=l.useRef(null);if(l.useEffect(()=>{i.current&&(i.current.scrollTop=0)},[e]),n)return s.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${o}`,children:"Loading diff…"});if(a)return s.jsx("div",{className:`px-3 py-4 text-xs text-red-400 ${o}`,children:a});if(t)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"Binary file — diff not available."});if(!e)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"No diff available."});const c=e.split(`
82
+ `);return s.jsxs("div",{ref:i,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:c.map((u,m)=>xk(u,m))}),r&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary border-t border-border/30",children:["Diff truncated — run ",s.jsx("code",{className:"font-mono",children:"git diff"})," locally for full output."]})]})}function bk(e,t){const r=[`Branch: ${e||"unknown"}`];r.push(`Changed: ${t.files.length} file(s) +${t.totalInsertions}/-${t.totalDeletions}`);const n={};for(const a of t.files)n[a.status]||(n[a.status]=[]),n[a.status].push(a.path);for(const[a,o]of Object.entries(n))r.push(`${a}: ${o.slice(0,5).join(", ")}${o.length>5?` (+${o.length-5} more)`:""}`);return r.join(`
83
+ `)}function zm({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=lt(),{status:a,diffSummary:o,loading:i,error:c,refresh:u}=uk({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,d]=l.useState(null),[p,h]=l.useState(null),[b,g]=l.useState(""),[f,w]=l.useState(!1),[j,y]=l.useState(!1),[v,N]=l.useState(null),[k,x]=l.useState(null),{githubUrl:I}=rk(e,t),C=l.useCallback(async O=>{if(!((m==null?void 0:m.path)===O.path&&!m.loading)){d({path:O.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const K=await n(e,"git_diff_file",{workspace:t,path:O.path,staged:O.staged}),S=dk(K);if(S.error||!S.diff){d({path:O.path,diff:"",binary:!1,truncated:!1,loading:!1,error:S.error??"Failed to load diff"});return}d({path:O.path,diff:S.diff.diff,binary:S.diff.binary??!1,truncated:S.diff.truncated??!1,loading:!1,error:null})}catch(K){const S=K instanceof Error?K.message:"Failed to load diff";d({path:O.path,diff:"",binary:!1,truncated:!1,loading:!1,error:S})}}},[e,n,m,t]),M=l.useCallback(O=>{g(""),w(!1),N(null),x(null),h(O)},[]),D=l.useCallback(()=>{h(null),N(null),y(!1)},[]),P=l.useCallback(async()=>{var O,K,S;if(p){y(!0),N(null);try{let A;p==="checkpoint"?A=await n(e,"git_checkpoint",{workspace:t,message:b,includeUntracked:f}):p==="stash"?A=await n(e,"git_stash_push",{workspace:t,message:b,includeUntracked:f}):p==="stash_pop"?A=await n(e,"git_stash_pop",{workspace:t}):p==="checkout_files"&&m&&(A=await n(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const B=(A==null?void 0:A.result)??A;if((B==null?void 0:B.success)===!1||B!=null&&B.error){N((B==null?void 0:B.error)??"Action failed"),y(!1);return}p==="checkpoint"?x(`Checkpoint created: ${((K=(O=B==null?void 0:B.checkpoint)==null?void 0:O.commit)==null?void 0:K.slice(0,7))??"done"}`):p==="stash"?x(`Stashed as ${((S=B==null?void 0:B.stash)==null?void 0:S.stashRef)??"stash@{0}"}`):p==="stash_pop"?x("Stash restored"):(x("File reverted"),d(null)),h(null),await u()}catch(A){N(A instanceof Error?A.message:"Action failed")}finally{y(!1)}}},[p,n,e,t,b,f,m,u]),T=!!(a!=null&&a.hasConflicts),R=a?a.staged+a.modified+a.untracked+a.deleted+a.renamed:null;return s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:O=>{O.target===O.currentTarget&&r()},children:s.jsxs("div",{className:"relative flex h-[80vh] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[s.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??"Git Status"}),s.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),I&&s.jsx("a",{href:`${I}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-sky-400 underline",title:"Open on GitHub",children:"GitHub ↗"})]}),s.jsx("button",{onClick:u,disabled:i,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),s.jsx("button",{onClick:r,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:s.jsx(vt,{className:"h-4 w-4"})})]}),a&&s.jsxs("div",{className:"flex shrink-0 flex-wrap gap-x-4 gap-y-1 border-b border-border/50 px-4 py-2 text-xs text-text-secondary",children:[a.headCommit&&s.jsxs("span",{title:a.headMessage??void 0,children:[s.jsx("span",{className:"font-mono",children:a.headCommit.slice(0,7)}),a.headMessage&&s.jsx("span",{className:"ml-1 truncate",children:a.headMessage.slice(0,60)})]}),a.ahead>0&&s.jsxs("span",{className:"text-orange-400",children:["↑",a.ahead," ahead"]}),a.behind>0&&s.jsxs("span",{className:"text-orange-400",children:["↓",a.behind," behind"]}),a.staged>0&&s.jsxs("span",{className:"text-emerald-400",children:[a.staged," staged"]}),a.modified>0&&s.jsxs("span",{children:[a.modified," modified"]}),a.untracked>0&&s.jsxs("span",{children:[a.untracked," untracked"]}),a.deleted>0&&s.jsxs("span",{className:"text-red-400",children:[a.deleted," deleted"]}),a.stashCount>0&&s.jsxs("span",{children:[a.stashCount," stashed"]}),a.hasConflicts&&s.jsx("span",{className:"font-bold text-red-400",children:"conflicts"}),R===0&&!a.error&&s.jsx("span",{className:"text-emerald-500",children:"clean"}),o&&o.files.length>0&&s.jsxs("span",{className:"text-text-secondary",children:[o.files.length," file",o.files.length!==1?"s":"",o.totalInsertions>0&&s.jsxs("span",{className:"text-emerald-500",children:[" +",o.totalInsertions]}),o.totalDeletions>0&&s.jsxs("span",{className:"text-red-400",children:[" -",o.totalDeletions]})]})]}),c&&s.jsx("div",{className:"shrink-0 border-b border-border/50 bg-red-500/10 px-4 py-2 text-xs text-red-400",children:c}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[i&&!o&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),o&&s.jsx(fk,{files:o.files,truncated:o.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:C}),!i&&!o&&!c&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),s.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:m?s.jsx(Om,{diff:m.diff,binary:m.binary,truncated:m.truncated,loading:m.loading,error:m.error,className:"h-full"}):s.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:"Select a file to view diff"})})]}),k&&s.jsxs("div",{className:"shrink-0 border-t border-border/50 bg-emerald-500/10 px-4 py-2 text-xs text-emerald-400 flex items-center justify-between",children:[s.jsx("span",{children:k}),s.jsx("button",{onClick:()=>x(null),className:"ml-2 text-emerald-400 hover:text-text-primary",children:"×"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[s.jsx("button",{onClick:()=>M("checkpoint"),disabled:T,title:T?"Resolve conflicts before checkpointing":"Create a git commit checkpoint",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkpoint"}),s.jsx("button",{onClick:()=>M("stash"),disabled:T,title:T?"Resolve conflicts before stashing":"Stash current changes",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Stash"}),s.jsx("button",{onClick:()=>M("stash_pop"),disabled:T||!(a!=null&&a.stashCount),title:T?"Resolve conflicts before restoring a stash":a!=null&&a.stashCount?"Restore the latest stash":"No stashes to restore",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Pop stash"}),s.jsx("button",{onClick:()=>M("checkout_files"),disabled:!m,title:m?`Revert changes to ${m.path}`:"Select a file to revert",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkout selected"}),o&&o.files.length>0&&s.jsx("button",{onClick:()=>{const O=bk((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(O),x("Copied to clipboard"),setTimeout(()=>x(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),p&&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:[p==="checkpoint"&&"Create checkpoint commit",p==="stash"&&"Stash changes",p==="stash_pop"&&"Restore latest stash?",p==="checkout_files"&&`Revert changes to ${(m==null?void 0:m.path)??"file"}?`]}),(p==="checkpoint"||p==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:b,onChange:O=>g(O.target.value),maxLength:200,placeholder:"Message (required)",className:"rounded border border-border bg-surface-alt px-2 py-1 text-xs text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-1 focus:ring-border",autoFocus:!0}),s.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:f,onChange:O=>w(O.target.checked)}),"Include untracked files"]})]}),v&&s.jsx("p",{className:"text-xs text-red-400",children:v}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:D,disabled:j,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:"Cancel"}),s.jsx("button",{onClick:P,disabled:j||(p==="checkpoint"||p==="stash")&&!b.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:j?"Working…":"Confirm"})]})]})})]})})}function gk({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=l.useState(!1),[o,i]=l.useState(!1),[c,u]=l.useState(!1),[m,d]=l.useState(!1),[p,h]=l.useState(!1),[b,g]=l.useState("quickstart"),[f,w]=l.useState("workspace"),j=l.useMemo(()=>!t&&!e,[t,e]),y=l.useCallback(C=>{a(C),C&&i(!1)},[]),v=l.useCallback(C=>{i(C),C&&a(!1)},[]),N=l.useCallback(()=>{g(r===0?"quickstart":"shortcuts"),w("workspace"),u(!0),a(!1),i(!1)},[r]),k=l.useCallback(()=>{u(!1)},[]),x=l.useCallback(()=>{d(!0)},[]),I=l.useCallback(()=>{d(!1)},[]);return l.useEffect(()=>{if(!j){h(!1);return}h(!0);const C=window.setTimeout(()=>{h(!1)},1e4);return()=>window.clearTimeout(C)},[j]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:m,guideNudgeVisible:p,guideTab:b,shortcutSection:f,isDesktopDashboard:j,setGuideTab:g,setShortcutSection:w,handleInboxOpenChange:y,handleHiddenOpenChange:v,handleOpenShortcutHelp:N,closeShortcutHelp:k,openNewSession:x,closeNewSession:I}}function yk(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 vk(e){return e instanceof Error?e.message:String(e||"")}function wk(e){const t=vk(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function jk({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:i,onStopCli:c,activeCliViewMode:u,onSetActiveCliViewMode:m,mobileChatConversations:d,hiddenConversations:p,ides:h,actionLogs:b,sendDaemonCommand:g,setActionLogs:f,setCliViewModeOverrides:w,isStandalone:j,initialDataLoaded:y,userName:v,requestedMobileTabKey:N,onRequestedMobileTabConsumed:k,requestedMachineId:x,onRequestedMachineConsumed:I,requestedMobileSection:C,onRequestedMobileSectionConsumed:M,containerRef:D,isSplitMode:P,numGroups:T,groupSizes:R,groupedConvs:O,clearedTabs:K,focusedGroup:S,focusGroup:A,moveTabToGroup:B,splitTabRelative:L,closeGroup:$,handleResizeStart:F,groupActiveTabIds:z,setGroupActiveTab:re,groupTabOrders:J,setGroupTabOrder:Y,toggleHiddenTab:se,visibleConversations:fe,requestedDesktopTabKey:be,onRequestedDesktopTabConsumed:X,onDesktopActiveTabChange:Q,onRequestScrollToBottom:we,onHideConversation:ve,onShowHiddenConversation:xe,onShowAllHiddenConversations:Ne,scrollToBottomRequest:ae,machineEntries:ge,layoutProfile:me,onBrowseMachineDirectory:U,onSaveMachineWorkspace:H,onLaunchMachineIde:q,onLaunchMachineProvider:ne,onListMachineMeshes:E,onLaunchMeshCoordinator:W,onListMachineSavedSessions:_,notifications:ie,notificationUnreadCount:pe,liveSessionInboxState:ue,onMarkNotificationRead:oe,onMarkNotificationUnread:Pe,onDeleteNotification:Ee}){const $e=yt.useRef(null),{inboxOpen:He,hiddenOpen:Xe,shortcutHelpOpen:Je,newSessionOpen:nt,guideNudgeVisible:et,guideTab:ct,shortcutSection:st,isDesktopDashboard:ft,setGuideTab:Me,setShortcutSection:Se,handleInboxOpenChange:Qe,handleHiddenOpenChange:Ge,handleOpenShortcutHelp:bt,closeShortcutHelp:V,openNewSession:G,closeNewSession:te}=gk({isMobile:t,showMobileChatMode:e,visibleConversationCount:fe.length}),[de,ye]=yt.useState(null),[je,Z]=yt.useState(null),ee=yt.useCallback((ce,Re)=>{ye({daemonId:ce,workspace:Re})},[]),he=yt.useCallback(ce=>{Z(ce)},[]),Ce=yt.useCallback(ce=>{var Re;Ir.flushSync(()=>{xe(ce)}),(Re=$e.current)==null||Re.restoreHiddenTabToSavedLocation(ce.tabKey)},[xe]),Te=yt.useCallback(ce=>{var _e;const Re=d.find(Ve=>Co(Ve,ce))||p.find(Ve=>Co(Ve,ce));Re&&(p.some(Ve=>Ve.tabKey===Re.tabKey)&&Ce(Re),Q(Re.tabKey),(_e=$e.current)==null||_e.activateConversationTab(Re.tabKey),we(Re.tabKey,"notification-open")),oe(ce.id),Qe(!1)},[Ce,p,d,Q,oe,we]),Ie=yt.useCallback(()=>{var Re;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Re=$e.current)==null||Re.resetAllPanelsToMain(),Ge(!1))},[Ge]),Le=yt.useCallback(async ce=>{var cs;if(!r)return;const Re=(cs=r.modalButtons)==null?void 0:cs[ce];if(!Re)return;const _e=gs(r);if(!_e)return;const Ve=Re.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),zt=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(Ve);try{await g(_e,"resolve_action",{button:Re,action:zt?"approve":"reject",buttonIndex:ce,...bs(r)})}catch(ds){wk(ds)||console.error("[Shortcut approval] Failed:",ds)}},[r,g]),{isMac:Be,actionDefinitions:Ae,actionShortcuts:We,shortcutListening:qe,shortcutListeningDraft:mt,setShortcutListening:gt,setShortcutListeningDraft:ht,saveShortcuts:ot}=Sv({enabled:ft&&!Je,onTrigger:ce=>{var Re,_e,Ve,zt,cs,ds,Gr,Vr,qr,Yr,Jr,Xr,Qr,Zr,us,en;if(ce==="openShortcutHelp"){bt();return}if(ce==="openNewSession"){G();return}if(ce==="hideCurrentTab"){r&&ve(r);return}if(ce==="toggleHiddenTabs"){Ge(!Xe);return}if(ce==="openHistoryForActiveTab"){r&&!Ye(r)&&o(r);return}if(ce==="openRemoteForActiveTab"){r&&!Ze(r)&&!Ye(r)&&i(r);return}if(ce==="splitActiveTabRight"){(Re=$e.current)==null||Re.splitActiveTabRight();return}if(ce==="splitActiveTabDown"){(_e=$e.current)==null||_e.splitActiveTabDown();return}if(ce==="floatActiveTab"){(Ve=$e.current)==null||Ve.floatActiveTab();return}if(ce==="popoutActiveTab"){(zt=$e.current)==null||zt.popoutActiveTab();return}if(ce==="dockActiveTab"){(cs=$e.current)==null||cs.dockActiveTab();return}if(ce==="focusLeftPane"){(ds=$e.current)==null||ds.focusLeftPane();return}if(ce==="focusRightPane"){(Gr=$e.current)==null||Gr.focusRightPane();return}if(ce==="focusUpPane"){(Vr=$e.current)==null||Vr.focusUpPane();return}if(ce==="focusDownPane"){(qr=$e.current)==null||qr.focusDownPane();return}if(ce==="moveActiveTabToLeftPane"){(Yr=$e.current)==null||Yr.moveActiveTabToLeftPane();return}if(ce==="moveActiveTabToRightPane"){(Jr=$e.current)==null||Jr.moveActiveTabToRightPane();return}if(ce==="moveActiveTabToUpPane"){(Xr=$e.current)==null||Xr.moveActiveTabToUpPane();return}if(ce==="moveActiveTabToDownPane"){(Qr=$e.current)==null||Qr.moveActiveTabToDownPane();return}if(ce==="triggerPrimaryApprovalAction"){Le(0);return}if(ce==="triggerSecondaryApprovalAction"){Le(1);return}if(ce==="triggerTertiaryApprovalAction"){Le(2);return}if(ce==="setActiveTabShortcut"){(Zr=$e.current)==null||Zr.setShortcutForActiveTab();return}if(ce==="selectPreviousGroupTab"){(us=$e.current)==null||us.activatePreviousTabInGroup();return}if(ce==="selectNextGroupTab"){(en=$e.current)==null||en.activateNextTabInGroup();return}!r||!Ze(r)||Ye(r)||ce==="toggleCliView"&&m(u==="chat"?"terminal":"chat")}}),ze=yt.useCallback(()=>{V(),gt(null),ht([])},[V,gt,ht]),At=yt.useMemo(()=>st==="all"?Ae:Ae.filter(ce=>yk(ce)===st),[Ae,st]),le=yt.useCallback(()=>{const ce=Object.fromEntries(Ae.map(Re=>[Re.id,""]));ot(ce)},[Ae,ot]),De=yt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const ce=Object.fromEntries(Ae.map(Re=>[Re.id,Re.defaultShortcut]));ot(ce)},[Ae,ot]);return yt.useEffect(()=>{const ce=Re=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Re.metaKey&&Re.key.toLowerCase()==="w":Re.ctrlKey&&Re.key.toLowerCase()==="w")&&(Re.preventDefault(),r&&ve&&ve(r))};return window.addEventListener("keydown",ce),()=>window.removeEventListener("keydown",ce)},[r,ve]),yt.useEffect(()=>{if(!Je||qe)return;const ce=Re=>{Re.key==="Escape"&&(Re.preventDefault(),ze())};return window.addEventListener("keydown",ce,!0),()=>window.removeEventListener("keydown",ce,!0)},[ze,Je,qe]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(pg,{activeConv:r,wsStatus:n,isConnected:a,conversations:fe,hiddenConversations:p,onOpenHistory:o,onHideConversation:ve,onShowConversation:Ce,onShowAllHidden:Ne,onResetPanelsToMain:Ie,notifications:ie,notificationUnreadCount:pe,onOpenNotification:Te,onMarkNotificationRead:oe,onMarkNotificationUnread:Pe,onDeleteNotification:Ee,inboxOpen:He,onInboxOpenChange:Qe,hiddenOpen:Xe,onHiddenOpenChange:Ge,onOpenNewSession:t?void 0:G,onOpenDashboardGuide:bt,guideNudgeVisible:et,actionShortcuts:We,onOpenRemote:()=>{!r||Ze(r)||Ye(r)||i(r)},onStopCli:c,activeCliViewMode:u,onSetCliViewMode:m,onOpenGitDialog:ee,onOpenMeshGraph:he}),e?s.jsx(pv,{conversations:d,hiddenConversations:p,ides:h,actionLogs:b,sendDaemonCommand:g,setActionLogs:f,setCliViewModeOverrides:w,isStandalone:j,userName:v,requestedActiveTabKey:N,onRequestedActiveTabConsumed:k,requestedMachineId:x,onRequestedMachineConsumed:I,requestedMobileSection:C,onRequestedMobileSectionConsumed:M,onOpenHistory:o,onOpenRemote:i,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:Ne,onHideConversation:ve,onOpenMeshGraph:he,onOpenNewSession:G,liveSessionInboxState:ue}):t?s.jsx(wv,{containerRef:D,isSplitMode:P,numGroups:T,groupSizes:R,groupedConvs:O,clearedTabs:K,ides:h,actionLogs:b,sendDaemonCommand:g,setActionLogs:f,isStandalone:j,hasRegisteredMachines:ge.length>0,userName:v,focusedGroup:S,focusGroup:A,moveTabToGroup:B,splitTabRelative:L,closeGroup:$,handleResizeStart:F,groupActiveTabIds:z,setGroupActiveTab:re,groupTabOrders:J,setGroupTabOrder:Y,toggleHiddenTab:se,onOpenNewSession:G,allowTabShortcuts:!1,liveSessionInboxState:ue}):s.jsx(Fv,{visibleConversations:fe,clearedTabs:K,ides:h,actionLogs:b,sendDaemonCommand:g,setActionLogs:f,isStandalone:j,hasRegisteredMachines:ge.length>0,initialDataLoaded:y,userName:v,toggleHiddenTab:se,actionShortcuts:We,registerActionHandlers:ce=>{$e.current=ce},onActiveTabChange:Q,requestedActiveTabKey:be,onRequestedActiveTabConsumed:X,onRequestScrollToBottom:we,scrollToBottomRequest:ae,onOpenNewSession:G,liveSessionInboxState:ue,layoutProfile:me}),nt&&s.jsx(Yv,{machines:ge,ides:h,onClose:te,onBrowseDirectory:U,onSaveWorkspace:H,onLaunchIde:q,onLaunchProvider:ne,onListMeshes:E,onLaunchMeshCoordinator:W,onListSavedSessions:_}),je&&s.jsx(sk,{activeConv:je,sendDaemonCommand:g,onClose:()=>Z(null)}),de&&s.jsx(zm,{daemonId:de.daemonId,workspace:de.workspace,onClose:()=>ye(null)}),Je&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:ze,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:ce=>ce.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:ze,"aria-label":"Close dashboard guide",children:s.jsx(vt,{size:14})})]}),s.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(ce=>s.jsx("button",{type:"button",className:`btn btn-sm ${ct===ce.id?"btn-primary":"btn-secondary"}`,onClick:()=>Me(ce.id),children:ce.label},ce.id))}),ct==="overview"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Hidden tabs:"})," stash sessions you do not want in the main strip but still want to keep around."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Review notifications:"})," open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Reduce clutter:"})," hide less important sessions instead of closing them, then restore from hidden tabs when needed."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Split work:"})," keep one pane active for input and let secondary panes stay read-only until you focus them."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Detached views:"})," float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Docking:"})," use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Per-tab shortcuts:"})," right-click a Dockview tab to assign a direct shortcut for that specific session."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",Be?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),ct==="quickstart"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),ct==="shortcuts"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:"All"},{id:"workspace",label:"Workspace"},{id:"panes",label:"Panes"},{id:"approvals",label:"Approvals"}].map(ce=>s.jsx("button",{type:"button",className:`btn btn-sm ${st===ce.id?"btn-primary":"btn-secondary"}`,onClick:()=>Se(ce.id),children:ce.label},ce.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:le,children:"Disable all"}),s.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:De,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:At.map(ce=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${qe===ce.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:ce.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:ce.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:ce.defaultShortcut})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-bg-tertiary border border-border-subtle min-w-[72px] text-center",children:qe===ce.id?mt.length>0?`${mt.join(" ")} ...`:"Listening...":We[ce.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{gt(ce.id),ht([])},children:qe===ce.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Re={...We};Re[ce.id]="",ot(Re)},children:"Disable"})]})]})},ce.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Be?"⌘⇧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 ro=[{icon:"🦦",title:"Welcome to ADHDev",desc:"Monitor and control your AI coding agents from anywhere — web, mobile, or CLI.",visual:"🎉"},{icon:"💬",title:"Real-time chat",desc:"See what your AI agent is doing in real-time. Send messages, approve or reject actions — all from your browser or phone.",visual:"📱"},{icon:"🖥️",title:"Remote desktop",desc:"View and control your IDE screen via P2P connection. Click, type, scroll — just like being there.",visual:"🖱️"},{icon:"🚀",title:"Get started",desc:"Install the daemon and link it to your dashboard. It connects automatically.",code:"npm install -g @adhdev/daemon-standalone && adhdev-standalone"}];function kk({onClose:e}){const[t,r]=l.useState(0),n=ro[t],a=t===ro.length-1;return s.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:o=>{o.stopPropagation()},children:[s.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[s.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:s.jsx(vt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:ro.map((o,i)=>s.jsx("div",{style:{width:i===t?24:8,height:8,borderRadius:4,background:i===t?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},i))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),s.jsxs("div",{style:{textAlign:"center"},children:[s.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[s.jsx("span",{children:n.icon})," ",n.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&s.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[s.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),s.jsx("div",{className:"flex justify-end items-center mt-6",children:s.jsx("button",{onClick:()=>a?e():r(o=>o+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
84
+ @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
85
+ @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
86
+ `})]})}function Nk({hasExtensions:e,ideName:t,activeChatTab:r,extensionTabs:n,onSelectTab:a}){return e?s.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[s.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${r==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a("native"),children:t}),n.map(o=>{const i=r===o.tabKey,c=o.status==="waiting_approval",u=o.status==="generating";return s.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${i?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a(o.tabKey),children:[s.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:c?"var(--status-warning)":u?"var(--accent-primary)":"var(--text-muted)",boxShadow:u?"0 0 6px var(--accent-primary)":"none"}}),o.title,c&&s.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},o.tabKey)})]}):null}function Sk({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,i]=l.useState(()=>a||"native"),c=l.useMemo(()=>uu(t),[t]),u=l.useMemo(()=>e?ui(e,{machineNames:c,connectionStates:r,defaultConnectionState:"new"}):[],[e,c,r]),m=l.useMemo(()=>u.find(f=>f.streamSource==="native"),[u]),d=l.useMemo(()=>u.filter(f=>f.streamSource==="agent-stream"),[u]),p=l.useMemo(()=>e?Ft(u,e.id):null,[u,e]);l.useEffect(()=>{a&&i(a)},[a]),l.useEffect(()=>{if(a||!p)return;const f=p.streamSource==="native"?"native":p.tabKey;!f||o===f||o==="native"&&i(f)},[o,p,a]),l.useEffect(()=>{var f;o!=="native"&&(d.some(w=>w.tabKey===o)||i(((f=d[0])==null?void 0:f.tabKey)||"native"))},[o,d]),l.useEffect(()=>{o==="native"&&(m||d[0]&&i(d[0].tabKey))},[o,m,d]);const h=l.useMemo(()=>o==="native"&&m?m:d.find(f=>f.tabKey===o)||p||m||d[0],[o,m,p,d]),b=l.useMemo(()=>d.map(f=>({tabKey:f.tabKey,title:tu(f)||n,status:f.status})),[d,n]),g=l.useCallback(f=>{if(f)return u.find(w=>Co(w,{sessionId:f,routeId:f,tabKey:f,providerSessionId:f}))},[u]);return{activeChatTab:o,setActiveChatTab:i,activeConv:h,conversations:u,extensionTabs:b,hasExtensions:b.length>0,resolveConversationByTarget:g}}function Ck({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:i,isStandalone:c,userName:u,onOpenHistory:m,onConversationChange:d,onClose:p}){const[h,b]=l.useState("split"),[g,f]=l.useState(()=>ls(e)?"native":e.tabKey),w=l.useRef(null),j=l.useMemo(()=>t||r.find(A=>A.id===e.routeId),[e.routeId,t,r]),y=l.useMemo(()=>wt((j==null?void 0:j.type)||""),[j==null?void 0:j.type]),{conversations:v,extensionTabs:N,hasExtensions:k}=Sk({ideData:j,allIdes:r,connectionStates:n,ideName:y||"IDE",preferredTabKey:ls(e)?void 0:e.tabKey}),x=l.useMemo(()=>j?Ft(v,j.id):null,[j,v]);l.useEffect(()=>{const A=w.current,B={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(w.current=B,!(A&&A.routeId===B.routeId&&A.tabKey===B.tabKey&&A.streamSource===B.streamSource)){if(ls(e)){f("native");return}f(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),l.useEffect(()=>{if(g==="native"){if(v.some(A=>A.streamSource==="native"))return;(x==null?void 0:x.streamSource)==="agent-stream"&&f(x.tabKey);return}if(!v.some(A=>A.tabKey===g)){if((x==null?void 0:x.streamSource)==="agent-stream"){f(x.tabKey);return}f("native")}},[v,g,x]);const I=l.useMemo(()=>g==="native"?v.find(A=>A.streamSource==="native")||e:v.find(A=>A.tabKey===g)||e,[e,v,g]),C=ku(I),M=l.useMemo(()=>C.status||C.modalMessage||C.modalButtons?{...I,...C.status?{status:C.status}:{},...C.modalMessage!==void 0?{modalMessage:C.modalMessage}:{},...C.modalButtons!==void 0?{modalButtons:C.modalButtons}:{}}:I,[I,C]),D=Fr(M),P=ma({sendDaemonCommand:o,activeConv:M,setActionLogs:i,isStandalone:c}),{connScreenshot:T,screenshotUsage:R,handleRemoteAction:O}=em({doId:D,targetSessionId:Bd(M),connState:M.connectionState||"new",viewMode:h}),K=l.useMemo(()=>a.filter(A=>A.routeId===M.tabKey),[a,M.tabKey]);l.useEffect(()=>{d==null||d(M)},[M,d]),l.useEffect(()=>{const A=B=>{B.key==="Escape"&&p()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[p]);const S=l.useCallback(A=>{A.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:p,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:S,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(Ot,{size:16})}),s.jsx("span",{className:"truncate",children:ri(I)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:p,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(A=>{const B=h===A;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${B?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>b(A),title:A==="split"?"Split view":"Remote only",children:A==="split"?s.jsx(wh,{size:15}):s.jsx(Ot,{size:15})},A)})}),s.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),s.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>m(I),title:"Chat History",children:[s.jsx(Vo,{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:p,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(Nk,{hasExtensions:k,ideName:y||"IDE",activeChatTab:g,extensionTabs:N,onSelectTab:f}),s.jsx(kd,{activeConv:M,onModalButton:P.handleModalButton}),s.jsx(To,{activeConv:M,ideEntry:j,showMetaChips:!1,handleSendChat:P.handleSendChat,handleForceSendChat:P.handleForceSendChat,isSendingChat:P.isSendingChat,sendFeedbackMessage:P.sendFeedbackMessage,handleFocusAgent:P.handleFocusAgent,isFocusingAgent:P.isFocusingAgent,actionLogs:K,userName:u})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${h==="split"?"order-1 md:order-2":""}`,children:s.jsx(yd,{addLog:()=>{},connState:M.connectionState||"new",connScreenshot:T,screenshotUsage:R,transportType:M.transport,onAction:O})})]})]})})}function Ik({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=Vb(e);return s.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:r,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[s.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",o,"?"]}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:t?"Stop asks the provider to exit cleanly when supported. Force Stop ends the runtime immediately.":"This provider does not support graceful stop. Force Stop will end the runtime immediately."})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[t&&s.jsx("button",{onClick:a,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),s.jsx("button",{onClick:n,className:"btn btn-secondary w-full justify-center min-h-[42px] text-red-400 border-red-500/25 hover:bg-red-500/10",children:"Force Stop"}),s.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function Mk({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o,interactivePrompt:i}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(lg,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(cu,{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(Ck,{activeConv:t.conversation,ideEntry:t.ideEntry,ides:t.ides,connectionStates:t.connectionStates,actionLogs:t.actionLogs,sendDaemonCommand:t.sendDaemonCommand,setActionLogs:t.setActionLogs,isStandalone:t.isStandalone,userName:t.userName,onOpenHistory:t.onOpenHistory,onConversationChange:t.onConversationChange,onClose:t.onClose}),r.open&&r.targetConv&&(Ze(r.targetConv)||Ye(r.targetConv))&&s.jsx(Ik,{activeConv:r.targetConv,canSaveAndStop:Ze(r.targetConv)&&!Ye(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(du,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),s.jsx(wd,{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(kk,{onClose:o.onClose})]})}function Ak({daemons:e,targetVersion:t,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:o}){return e.length===0?null:s.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:r?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:r?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[s.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:s.jsx(la,{size:14})}),s.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[s.jsxs("span",{children:[r?"Daemon update required":"Update available",t?s.jsxs(s.Fragment,{children:[": ",s.jsxs("strong",{children:["v",t]})]}):null]}),e.map(i=>{const c=Pt(i,{fallbackId:i.id}),u=n[i.id],m=i.version||i.daemonVersion||"unknown",d=i.versionUpdateRequired===!0,h=Eu(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:c}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",m]}),d&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),u==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:d?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):u==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):u==="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)})]}),!r&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:o,title:"Dismiss",children:s.jsx(vt,{size:16})})]})}function Tk(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function _k(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 Lk(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>_k(t)).map(t=>t.id)}}function Pk(){var Oi,zi,Hi,Wi;const{sendCommand:e}=lt(),t=Or(),r=ju(),n=Ko(),a=$r(),[o,i]=Bp(),c=o.get("activeTab"),u=((Oi=n.state)==null?void 0:Oi.openRemoteForTabKey)||null,m=((zi=n.state)==null?void 0:zi.openMachineId)||null,d=((Hi=n.state)==null?void 0:Hi.mobileSection)||null,p=Xd(),h=p.ides||[],b=p.initialLoaded??!0,{updateRouteChats:g,setToasts:f}=p,[w,j]=l.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),y=p.toasts||[],v=p.wsStatus||"connected",N=p.isConnected??!0,k=p.connectionStates||{},x=p.showReconnected||!1,{layoutProfile:I,groupAssignments:C,updateGroupAssignments:M,focusedGroup:D,updateFocusedGroup:P,focusGroup:T,groupActiveTabIds:R,updateGroupActiveTabIds:O,setGroupActiveTab:K,groupTabOrders:S,updateGroupTabOrders:A,setGroupTabOrder:B,groupSizes:L,updateGroupSizes:$,isMobile:F,hasHydratedStoredLayout:z,hydrateStoredLayout:re,focusConversationTab:J}=iy(),[Y,se]=l.useState(()=>fi());l.useEffect(()=>m0(se),[]);const fe=l.useMemo(()=>Tk({isMobile:F,mobileViewMode:Y}),[F,Y]),[be,X]=l.useState([]),[Q,we]=l.useState({}),[ve,xe]=l.useState({});Br("Dashboard",{ideCount:h.length,toastCount:y.length,focusedGroup:D,groupCount:Object.keys(C).length,actionLogCount:be.length});const Ne=l.useMemo(()=>h.filter(Ke=>Ke.type==="adhdev-daemon").sort(ei),[h]),ge=!!Ne[0];l.useEffect(()=>{const{metadataDaemonIds:Ke,runtimeDaemonIds:Rt}=Lk(Ne);for(const Xs of Ke)t(Xs,{minFreshMs:3e4}).catch(()=>{});for(const Xs of Rt)r(Xs,{minFreshMs:3e4}).catch(()=>{})},[t,r,Ne]);const me=l.useMemo(()=>P0(h,Q),[h,Q]),{hiddenTabs:U,autoHiddenTabs:H,autoHideTarget:q,hideTarget:ne,toggleTarget:E,showTarget:W,showAllTabs:_}=N0(),{conversations:ie,visibleConversations:pe,visibleTabKeys:ue,resolveConversationBySessionId:oe,resolveConversationByTarget:Pe}=G0({ides:me,connectionStates:k,clearedTabs:ve,hiddenTabs:U}),Ee=l.useMemo(()=>new Map(ie.map(Ke=>[Ke.tabKey,Ke])),[ie]),$e=l.useMemo(()=>k0(ie,U,H),[ie,U,H]);l.useEffect(()=>{for(const Ke of $e)q(Ke)},[$e,q]),yb(pe,fe),l.useEffect(()=>{Object.keys(Q).length!==0&&we(Ke=>R0(Ke,h))},[h,Q]);const He=l.useMemo(()=>vf(h),[h]),{notifications:Xe,unreadCount:Je}=ky({conversations:ie,liveSessionInboxState:He}),{handleMarkDashboardNotificationRead:nt,handleMarkDashboardNotificationUnread:et,handleDeleteDashboardNotification:ct}=Ny({notifications:Xe,sendDaemonCommand:e}),{containerRef:st,normalizedGroupAssignments:ft,numGroups:Me,isSplitMode:Se,groupedConvs:Qe,moveTabToGroup:Ge,closeGroup:bt,handleResizeStart:V,splitTabRelative:G}=hy({groupAssignments:C,updateGroupAssignments:M,updateFocusedGroup:P,updateGroupActiveTabIds:O,updateGroupTabOrders:A,groupSizes:L,updateGroupSizes:$,isMobile:F,visibleConversations:pe,visibleTabKeys:ue}),{activeConv:te,openDesktopConversation:de,requestScrollToBottom:ye,scrollToBottomRequest:je,setDesktopActiveTab:Z}=By({isMobile:F,conversations:ie,visibleConversations:pe,groupActiveTabIds:R,focusedGroup:D,groupedConvs:Qe,setSearchParams:i});zy({activeConv:te,isMobile:F,liveSessionInboxState:He,sendDaemonCommand:e});const{requestedDesktopTabKey:ee,requestedMobileTabKey:he,consumeRequestedActiveTab:Ce}=V0({isMobile:F,urlActiveTab:c,resolveConversationBySessionId:oe,setSearchParams:i}),{remoteDialogConv:Te,remoteDialogIdeEntry:Ie,remoteDialogActiveConv:Le,setRemoteDialogActiveConv:Be,openRemoteDialog:Ae,closeRemoteDialog:We,cliStopDialogOpen:qe,cliStopTargetConv:mt,requestCliStop:gt,cancelCliStop:ht,confirmCliStop:ot}=Ky({isMobile:F,location:n,navigate:a,requestedRemoteTabTarget:u,requestedDesktopTabKey:ee,conversations:ie,ides:h,resolveConversationByTarget:Pe,activeConv:te,sendDaemonCommand:e}),{historyModalOpen:ze,openHistoryModal:At,closeHistoryModal:le,historyTargetConv:De,isSavedSessionHistoryTarget:ce,isHistoryCreatingChat:Re,isHistoryRefreshingHistory:_e,handleHistorySwitchSession:Ve,handleHistoryNewChat:zt,handleHistoryRefresh:cs,savedHistorySessions:ds,savedHistoryFilters:Gr,setSavedHistoryFilters:Vr,missingWorkspaceResumePath:qr,isSavedHistoryLoading:Yr,resumingSavedHistorySessionId:Jr,handleRefreshSavedHistory:Xr,handleResumeSavedHistorySession:Qr}=Hy({activeConv:te,remoteDialogConv:Te,remoteDialogActiveConv:Le,ides:h,sendDaemonCommand:e,updateRouteChats:g,setToasts:f,setClearedTabs:xe,setSearchParams:i}),Zr=l.useMemo(()=>pe,[pe]),us=F&&Y==="chat",en=l.useMemo(()=>ie.filter(Ke=>fa(U,Ke)),[ie,U]),Ei=l.useCallback(Ke=>{const Rt=new URLSearchParams(o);Rt.set("activeTab",Ke),i(Rt,{replace:!0})},[o,i]),{trackPendingLaunch:Jm}=Ry({ides:h,conversations:ie,onOpenSession:Ei}),{handleBrowseMachineDirectory:Xm,handleSaveMachineWorkspace:Qm,handleLaunchMachineIde:Zm,handleLaunchMachineProvider:ep,handleListMachineMeshes:tp,handleLaunchMeshCoordinator:sp,handleListMachineSavedSessions:rp,setActiveCliViewMode:np}=Dy({sendDaemonCommand:e,trackPendingLaunch:Jm,onOpenSession:Ei,activeConv:te,ides:h,setCliViewModeOverrides:we});D0({visibleConversations:pe,clearedTabs:ve,setClearedTabs:xe,setActionLogs:X}),q0({ides:h,sendDaemonCommand:e,setToasts:f,resolveConversationByTarget:Pe});const ap=Iu(),{isRefreshingHistory:op,handleRefreshHistory:ip}=$u({sendDaemonCommand:e,activeConv:te,chats:(Wi=h.find(Ke=>Ke.id===(te==null?void 0:te.routeId)))==null?void 0:Wi.chats,updateRouteChats:g,setToasts:f,setClearedTabs:xe});cy({urlActiveTab:F&&!us?c:null,conversations:ie,resolveConversationBySessionId:oe,normalizedGroupAssignments:ft,hasHydratedStoredLayout:F&&!us?z:!0,hydrateStoredLayout:F&&!us?re:()=>{},focusConversationTab:J,setSearchParams:i,historyModalOpen:ze,activeConv:te,isRefreshingHistory:op,ides:h,handleRefreshHistory:ip});const lp=l.useMemo(()=>!te||!Ze(te)||Ye(te)?null:qs(te),[te]),{versionMismatchDaemons:cp,hasRequiredVersionDaemons:Bi,targetVersion:dp,versionBannerDismissed:up,setVersionBannerDismissed:mp,upgradingDaemons:pp,handleBannerUpgrade:hp}=xy({ides:h,sendDaemonCommand:e}),Fi=l.useCallback(Ke=>{W(Ke),de(Ke)},[de,W]),fp=l.useCallback(Ke=>{ne(Ke)},[ne]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[(!up||Bi)&&s.jsx(Ak,{daemons:cp,targetVersion:dp,required:Bi,upgradingDaemons:pp,onUpgrade:hp,onDismiss:()=>mp(!0)}),s.jsx(jk,{showMobileChatMode:us,isMobile:F,activeConv:te,wsStatus:v,isConnected:N,onOpenHistory:Ke=>{Ke&&Be(Ke),At()},onOpenRemote:Ae,onStopCli:gt,activeCliViewMode:lp,onSetActiveCliViewMode:np,mobileChatConversations:Zr,ides:h,actionLogs:be,sendDaemonCommand:e,setActionLogs:X,setCliViewModeOverrides:we,isStandalone:ge,initialDataLoaded:b,userName:p.userName,requestedMobileTabKey:he,onRequestedMobileTabConsumed:Ce,requestedMachineId:m,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:d,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:st,isSplitMode:Se,numGroups:Me,groupSizes:L,groupedConvs:Qe,clearedTabs:ve,focusedGroup:D,focusGroup:T,moveTabToGroup:Ge,splitTabRelative:G,closeGroup:bt,handleResizeStart:V,groupActiveTabIds:R,setGroupActiveTab:K,groupTabOrders:S,setGroupTabOrder:B,toggleHiddenTab:Ke=>E(Ee.get(Ke)||{tabKey:Ke}),visibleConversations:pe,hiddenConversations:en,requestedDesktopTabKey:ee,onRequestedDesktopTabConsumed:Ce,onDesktopActiveTabChange:Z,onRequestScrollToBottom:ye,onHideConversation:fp,onShowHiddenConversation:Fi,onShowAllHiddenConversations:_,scrollToBottomRequest:je,machineEntries:Ne,layoutProfile:I,onBrowseMachineDirectory:Xm,onSaveMachineWorkspace:Qm,onLaunchMachineIde:Zm,onLaunchMachineProvider:ep,onListMachineMeshes:tp,onLaunchMeshCoordinator:sp,onListMachineSavedSessions:rp,notifications:Xe,notificationUnreadCount:Je,liveSessionInboxState:He,onMarkNotificationRead:nt,onMarkNotificationUnread:et,onDeleteNotification:ct}),s.jsx("style",{children:`
87
+ body { overflow: hidden; overscroll-behavior: none; }
88
+ `}),s.jsx(Mk,{historyModal:{open:ze,targetConv:De,ides:h,isCreatingChat:Re,isRefreshingHistory:ce?!1:_e,savedSessions:ds,savedHistoryFilters:Gr,missingWorkspaceResumePath:qr||null,onSavedHistoryFiltersChange:Vr,isSavedSessionsLoading:Yr,isResumingSavedSessionId:Jr,onClose:le,onNewChat:zt,onSwitchSession:Ve,onRefreshHistory:ce?Xr:cs,onResumeSavedSession:Qr},remoteDialog:{conversation:Te,ideEntry:Ie,ides:h,connectionStates:k,actionLogs:be,sendDaemonCommand:e,setActionLogs:X,isStandalone:ge,userName:p.userName,onOpenHistory:Ke=>{Ke&&Be(Ke),At()},onConversationChange:Be,onClose:We},cliStopDialog:{open:qe,targetConv:mt,onCancel:ht,onStopNow:async()=>{await ot("hard")},onSaveAndStop:async()=>{await ot("save")}},connectionBanner:{wsStatus:v,showReconnected:x,loginUrl:p.connectionLoginUrl,onReconnect:p.retryServerConnection},toastOverlay:{toasts:y,onDismiss:Ke=>f(Rt=>Rt.filter(Xs=>Xs.id!==Ke)),onClick:Ke=>{if(Ke.targetKey){const Rt=Pe(Ke.targetKey);Rt&&(J(Rt.tabKey,ft),Fi(Rt),ye(Rt.tabKey,"toast-open"))}}},onboarding:{open:w,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}j(!1)}},interactivePrompt:ap})]})}function Rk({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const{launchCli:o}=oa(),[i,c]=l.useState([]),[u,m]=l.useState(null),[d,p]=l.useState(null),[h,b]=l.useState(!1),[g,f]=l.useState(null),[w,j]=l.useState(!1),[y,v]=l.useState(""),N=l.useRef(null),k=l.useCallback($=>{N.current=$},[]),x=l.useCallback(($,F,z=!1)=>{c(re=>[...re.slice(-100),{timestamp:Date.now(),level:$,message:F}]),setTimeout(()=>{var re;return(re=a.current)==null?void 0:re.scrollIntoView({behavior:"smooth"})},100),z&&tt.showToast(F,$==="error"||$==="warn"?"warning":"success")},[a]),I=l.useCallback($=>{const F=$ instanceof Error?$.message:String($||"");return F.includes("P2P command timeout")||F.includes("P2P not connected")||F.includes("P2P not available")},[]),C=l.useCallback(async($,F)=>{var z;if(!e||u)return!1;m($),x("info",`Launching ${wt($)}${F!=null&&F.workspace?` in ${F.workspace}`:""}...`);try{const re={ideType:$,enableCdp:!0};(z=F==null?void 0:F.workspace)!=null&&z.trim()?re.workspace=F.workspace.trim():F!=null&&F.useDefaultWorkspace&&(re.useDefaultWorkspace=!0);const J=await r(e,"launch_ide",re);return x(J!=null&&J.success?"info":"error",J!=null&&J.success?`${wt($)} launched`:`Failed: ${J==null?void 0:J.error}`,!0),!!(J!=null&&J.success)}catch(re){return x("error",`Launch error: ${re.message}`,!0),!1}finally{m(null)}},[e,u,x,r]),M=l.useCallback(async $=>{if(!e)return{success:!1};const{cliType:F,dir:z,workspaceId:re,useDefaultWorkspace:J,useHome:Y,argsStr:se,model:fe,resumeSessionId:be}=$;if(!F)return x("warn","Select a CLI or ACP provider first",!0),{success:!1};const X=se?se.split(/\s+/).filter(Boolean):void 0,Q=(z==null?void 0:z.trim())||(re?"(saved id)":J?"(default workspace)":Y?"(home)":"");x("info",`Launching ${F}${Q?` in ${Q}`:""}${fe?` (model: ${fe})`:""}...`),p(F);try{const we={cliType:F,cliArgs:X,initialModel:fe||void 0};z!=null&&z.trim()?we.dir=z.trim():re?we.workspaceId=re:J?we.useDefaultWorkspace=!0:Y&&(we.useHome=!0),be&&(we.resumeSessionId=be);const ve=await o(e,we),xe=(ve==null?void 0:ve.result)||ve;return ve!=null&&ve.success?(x("info",`${F} launched`,!0),(xe==null?void 0:xe.launchSource)==="home"?x("info","📂 Running in home directory (explicit choice)"):(xe==null?void 0:xe.launchSource)==="defaultWorkspace"&&x("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:xe==null?void 0:xe.sessionId}):(x("error",`Failed: ${(ve==null?void 0:ve.error)||(xe==null?void 0:xe.error)}`,!0),(ve==null?void 0:ve.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&f({cliType:F,argsStr:se,model:fe}),{success:!1,sessionId:xe==null?void 0:xe.sessionId})}catch(we){return I(we)?(x("warn",`${F} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(x("error",`Launch error: ${we.message}`,!0),{success:!1})}finally{p(null)}},[e,x,I,r]),D=l.useCallback(async($,F,z,re)=>e?$?F.trim()?M({cliType:$,dir:F,argsStr:z,model:re}):(f({cliType:$,argsStr:z,model:re}),{success:!1}):(x("warn","Select a provider",!0),{success:!1}):{success:!1},[e,x,M]),P=l.useCallback(async($,F,z)=>{if(e&&window.confirm(`Stop ${$}?
89
+ This will terminate the process.`))try{const re=await r(e,"stop_cli",{cliType:$,dir:F,targetSessionId:z});re!=null&&re.success?x("info",`${$} stopped`,!0):x("error",`Stop failed: ${(re==null?void 0:re.error)||"Unknown error"}`,!0)}catch(re){x("error",`Stop failed: ${re.message}`,!0)}},[e,x,r]),T=l.useCallback(async $=>{try{await r($.daemonId,"restart_ide",{ideType:$.type}),x("info",`${wt($.type)} restart initiated`,!0)}catch(F){x("error",`Restart failed: ${F.message}`,!0)}},[x,r]),R=l.useCallback(async $=>{if(window.confirm(`Stop ${wt($.type)}?
90
+ This will disconnect CDP and optionally kill the process.`))try{const F=await r($.daemonId,"stop_ide",{ideType:$.type,killProcess:!0});F!=null&&F.success?x("info",`${wt($.type)} stopped`,!0):x("error",`Stop failed: ${(F==null?void 0:F.error)||"Unknown error"}`,!0)}catch(F){x("error",`Stop failed: ${F.message}`,!0)}},[x,r]),O=l.useCallback(async()=>{if(e)try{const $=await r(e,"detect_ides",{});x("info",`Found ${(($==null?void 0:$.result)||[]).length} IDE(s)`,!0)}catch($){x("error",`Detection failed: ${$.message}`,!0)}},[e,x,r]),K=l.useCallback(async $=>{if(!e||!$.trim())return!1;b(!0);try{const F=await r(e,"workspace_add",{path:$.trim()});return F!=null&&F.success?(x("info",`Workspace added: ${$.trim()}`),!0):(x("error",(F==null?void 0:F.error)||"workspace_add failed"),!1)}catch(F){return x("error",F.message),!1}finally{b(!1)}},[e,x,r]),S=l.useCallback(async $=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){b(!0);try{const F=await r(e,"workspace_remove",{id:$});F!=null&&F.success?x("info","Workspace removed",!0):x("error",(F==null?void 0:F.error)||"workspace_remove failed",!0)}catch(F){x("error",F.message,!0)}finally{b(!1)}}},[e,x,r]),A=l.useCallback(async $=>{var F;if(e){b(!0);try{const z=await r(e,"workspace_set_default",$===null?{clear:!0}:{id:$});if(z!=null&&z.success){x("info",$?"Default workspace updated":"Default workspace cleared",!0);const re=typeof z.defaultWorkspacePath=="string"?z.defaultWorkspacePath:"";re&&((F=N.current)==null||F.call(N,re))}else x("error",(z==null?void 0:z.error)||"workspace_set_default failed",!0)}catch(z){x("error",z.message,!0)}finally{b(!1)}}},[e,x,r]),B=l.useCallback(async $=>{var z;if(!e||!$.trim())return;const F=$.trim();b(!0);try{const re=await r(e,"workspace_set_default",{path:F});re!=null&&re.success?(x("info","Default workspace set from history"),(z=N.current)==null||z.call(N,F)):x("error",(re==null?void 0:re.error)||"Could not set default (path missing on disk?)")}catch(re){x("error",re.message)}finally{b(!1)}},[e,x,r]),L=l.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:y}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:y})}catch($){x("warn",`Live nickname updated, but account sync failed: ${$.message}`)}x("info",`Nickname set to "${y||"(cleared)"}"`),j(!1)}catch($){x("error",`Failed: ${$.message}`)}},[e,y,t,x,n,r]);return{logs:i,launchingIde:u,launchingAgentType:d,workspaceBusy:h,launchPick:g,setLaunchPick:f,editingNickname:w,setEditingNickname:j,nicknameInput:y,setNicknameInput:v,addLog:x,handleLaunchIde:C,runLaunchCliCore:M,handleLaunchCli:D,handleStopCli:P,handleRestartIde:T,handleStopIde:R,handleDetectIdes:O,handleWorkspaceAdd:K,handleWorkspaceRemove:S,handleWorkspaceSetDefault:A,handleWorkspaceResumePath:B,handleSaveNickname:L,setOnDefaultWorkspaceChanged:k}}function Dk({machine:e,ideSessions:t,cliSessions:r,acpSessions:n}){var u;const a=typeof e.uptime=="number"||typeof e.freeMem=="number"||typeof e.availableMem=="number"||Array.isArray(e.loadavg)&&e.loadavg.length>0,o=e.availableMem??e.freeMem??e.totalMem,i=a&&e.totalMem>0?Math.min(100,Math.max(0,Math.round((e.totalMem-o)/e.totalMem*100))):0,c=((u=e.loadavg)==null?void 0:u[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(rn,{icon:s.jsx(id,{size:16}),label:"Uptime",value:typeof e.uptime=="number"?Cf(e.uptime):"Waiting…"}),s.jsx(rn,{icon:s.jsx(Ot,{size:16}),label:"IDEs",value:`${t.length}`}),s.jsx(rn,{icon:s.jsx(Yo,{size:16}),label:"CLIs",value:`${r.length}`}),s.jsx(rn,{icon:s.jsx(kh,{size:16}),label:"ACPs",value:`${n.length}`})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),s.jsxs("div",{className:"flex gap-6",children:[s.jsx(rl,{value:a?Math.min(Math.round(c/e.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:a?`${c.toFixed(2)} avg / ${e.cpus} cores`:"Polled from machine page"}),s.jsx(rl,{value:i,max:100,label:"Memory",color:"#3b82f6",detail:a?`${Sa(e.totalMem-o)} / ${Sa(e.totalMem)}${e.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Sa(e.totalMem)} total`})]})]})]})}function $k(e){if(!e||typeof e!="object")return null;const t=e,r=t.result&&typeof t.result=="object"?t.result:t;return!r.settings||typeof r.settings!="object"?null:{settings:r.settings,values:r.values&&typeof r.values=="object"?r.values:{}}}function Ek(e,t,r){const n=[];for(const[a,o]of Object.entries(e.settings)){const i=r!=null&&r.filterSchema?r.filterSchema(o):o;if(i.length===0)continue;const c=t.find(u=>u.type===a);n.push({type:a,displayName:(c==null?void 0:c.displayName)||a,icon:(c==null?void 0:c.icon)||"",category:(c==null?void 0:c.category)||"unknown",schema:i,values:e.values[a]||{}})}return n}function no(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 _c(e){if(!e||typeof e!="object")return null;if(no(e))return e;const t=e,r=t.result;return no(r)?r:no(t.sourceConfig)?t.sourceConfig:null}function Bk(e){const t=e.trim();return t||null}function Fk({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var k;const o=t.filter(x=>x.category==="ide"),[i,c]=l.useState(((k=o[0])==null?void 0:k.type)||""),[u,m]=l.useState(""),[d,p]=l.useState(""),[h,b]=l.useState(!1),[g,f]=l.useState(""),[w,j]=l.useState(!1),y=x=>{const I=x.toLowerCase().replace(/[^a-z0-9-]/g,"");m(I),(!d||d===v(u))&&p(v(I))},v=x=>x.split("-").map(I=>I.charAt(0).toUpperCase()+I.slice(1)).join(" "),N=async()=>{if(!(!u||!d||!i)){b(!0),f("");try{const x=await r(e,"provider_clone",{type:u,name:d,category:"ide",location:"user",cloneFrom:i});x!=null&&x.success||x!=null&&x.created?(j(!0),a==null||a(u)):f((x==null?void 0:x.error)||"Failed to create provider")}catch(x){f((x==null?void 0:x.message)||"Connection failed")}b(!1)}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:s.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:x=>x.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[s.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:w?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:u})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",u,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",u]})," or use Auto-Fix to implement scripts."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:o.map(x=>s.jsxs("button",{onClick:()=>c(x.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:i===x.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:i===x.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:x.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:i===x.type?"#a78bfa":"var(--text-secondary)"},children:x.displayName})]},x.type))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),s.jsx("input",{value:u,onChange:x=>y(x.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",u||"...","/"]})]})]}),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:x=>p(x.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),g&&s.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:g})]})}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:w?s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:N,disabled:!u||!d||h,className:"machine-btn",style:{background:u&&d?"rgba(34,197,94,0.12)":void 0,borderColor:u&&d?"rgba(34,197,94,0.3)":void 0,color:u&&d?"#86efac":void 0,opacity:!u||!d||h?.4:1},children:h?"⏳ Creating...":"✨ Create Provider"})]})})]})})}const Lc={"user-custom":"Custom",trusted:"Official","trusted-with-scripts":"Official · runs JS","external-safe":"External · spec-only","external-untrusted":"⚠ External · untrusted JS"},Ok={"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 zk({trust:e,sourceName:t,description:r}){const n=t&&(e==="external-safe"||e==="external-untrusted")?`${Lc[e]} · ${t}`:Lc[e];return s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded border whitespace-nowrap ${Ok[e]}`,title:r,children:n})}function Hk(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 Wk={detected:"Detected",not_detected:"Not detected",enabled_unchecked:"Enabled (unchecked)",disabled:"Disabled"},Pc={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"},Kk={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 Rc(e){if(!e)return"—";const t=e.ok?"OK":"Failed",r=e.message||e.path||e.command||"";return r?`${t} — ${r}`:t}function Uk(e){return e==="cli"||e==="acp"}function Gk({prov:e,providerInfo:t,savingKey:r,onSetSetting:n,onEnableToggle:a,onDetect:o,onResetCommand:i}){const[c,u]=l.useState(!1),m=(t==null?void 0:t.enabled)===!0||e.values.enabled===!0,d=t==null?void 0:t.machineStatus,p=m&&d==="disabled"?"enabled_unchecked":d||(m?"enabled_unchecked":"disabled"),h=Uk(e.category);return s.jsxs("div",{className:"rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("button",{onClick:()=>u(b=>!b),className:"w-full px-4 py-2.5 flex items-center gap-3 text-left",children:[s.jsx("span",{className:"text-base shrink-0",children:e.icon}),s.jsx("span",{className:"text-[13px] font-semibold text-text-primary truncate",children:e.displayName}),s.jsx("span",{className:`text-[9px] font-semibold px-1.5 py-px rounded border ${Kk[e.category]??"border-border-subtle text-text-muted"}`,children:e.category.toUpperCase()}),(t==null?void 0:t.trust)&&s.jsx(zk,{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 ${Pc[p]??Pc.disabled}`,children:Wk[p]??p}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[h&&s.jsx("button",{onClick:b=>{b.stopPropagation(),a(e.type,!m)},disabled:r===`${e.type}.enabled`,className:`machine-btn text-[10px] px-2 py-0.5 ${m?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:m?"Disable":"Enable"}),s.jsx("span",{className:"text-text-muted text-xs",children:c?"▾":"▸"})]})]}),c&&s.jsxs("div",{className:"border-t border-border-subtle px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{className:"grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Type:"})," ",s.jsx("span",{className:"font-mono",children:e.type})]}),(t==null?void 0:t.providerVersion)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Version:"})," ",t.providerVersion]}),(t==null?void 0:t.binary)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Binary:"})," ",s.jsx("span",{className:"font-mono",children:t.binary})]}),(t==null?void 0:t.status)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Status:"})," ",t.status]}),(t==null?void 0:t.details)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Details:"})," ",t.details]}),(t==null?void 0:t.sourceLayer)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Source:"})," ",t.sourceLayer,t.sourceName?` · ${t.sourceName}`:""]}),(t==null?void 0:t.trust)&&(t==null?void 0:t.trustDescription)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Trust:"})," ",t.trustDescription]}),(()=>{const b=t==null?void 0:t.links;if(!b)return null;const g=Object.entries(b).map(([f,w])=>({k:f,href:Hk(w)})).filter(f=>f.href!==null);return g.length===0?null:s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Links:"})," ",g.map(({k:f,href:w})=>s.jsx("a",{href:w,target:"_blank",rel:"noopener noreferrer",className:"text-violet-400 hover:underline mr-2",children:f},f))]})})()]}),h&&s.jsxs("div",{className:"grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Detection:"})," ",Rc(t==null?void 0:t.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Verification:"})," ",Rc(t==null?void 0:t.lastVerification)]})]}),e.schema.length>0&&s.jsx("div",{className:"flex flex-col gap-1.5",children:e.schema.map(b=>s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"text-[11px] font-medium text-text-primary",children:[b.label||b.key,r===`${e.type}.${b.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving…"})]}),b.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:b.description})]}),s.jsx("div",{className:"shrink-0",children:b.type==="boolean"?s.jsx("button",{onClick:()=>void n(e.type,b.key,!(e.values[b.key]??b.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:e.values[b.key]??b.default?"#8b5cf6":"var(--border-subtle)"},children:s.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:e.values[b.key]??b.default?21:3}})}):b.type==="number"?s.jsx("input",{type:"number",value:Number(e.values[b.key]??b.default??0)||0,min:b.min,max:b.max,onChange:g=>{const f=parseInt(g.target.value)||0;b.min!==void 0&&f<b.min||b.max!==void 0&&f>b.max||n(e.type,b.key,f)},className:"machine-input w-20 text-center text-[11px]"}):b.type==="select"&&b.options?s.jsx("select",{value:String(e.values[b.key]??b.default??""),onChange:g=>void n(e.type,b.key,g.target.value),className:"machine-input text-[11px]",children:b.options.map(g=>s.jsx("option",{value:g,children:g},g))}):s.jsx("input",{type:"text",defaultValue:String(e.values[b.key]??b.default??""),onBlur:g=>void n(e.type,b.key,g.target.value),className:"machine-input w-[180px] text-[11px]"})})]},b.key))}),s.jsx("div",{className:"flex gap-1.5 flex-wrap pt-1 border-t border-border-subtle",children:h&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>void o(e.type),disabled:!m||r===`${e.type}.detect`,className:`machine-btn text-[10px] px-2 py-0.5 text-blue-400 border-blue-500/25 ${m?"":"opacity-40 cursor-not-allowed"}`,title:m?"Run detection for the configured executable":"Enable provider before detection",children:"Detect"}),s.jsx("button",{onClick:()=>void i(e.type),className:"machine-btn text-[10px] px-2 py-0.5",children:"Reset command"})]})})]})]})}function jn(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function Vk({machineId:e,sendDaemonCommand:t,onChange:r}){const[n,a]=l.useState([]),[o,i]=l.useState([]),[c,u]=l.useState(!1),[m,d]=l.useState(null),[p,h]=l.useState(!1),[b,g]=l.useState(""),[f,w]=l.useState("main"),[j,y]=l.useState(""),[v,N]=l.useState(!1),[k,x]=l.useState(null),[I,C]=l.useState(null),M=l.useCallback(async()=>{if(e){u(!0),d(null);try{const R=jn(await t(e,"list_provider_sources",{}));if(!(R!=null&&R.success)){d((R==null?void 0:R.error)||"Failed to load sources");return}a(R.sources||[]),i(R.conflicts||[])}catch(R){d((R==null?void 0:R.message)||String(R))}finally{u(!1)}}},[e,t]);l.useEffect(()=>{M()},[M]);const D=async()=>{if(b.trim()){N(!0),d(null);try{const R=jn(await t(e,"add_provider_source",{url:b.trim(),ref:f.trim()||"main",...j.trim()?{name:j.trim()}:{}}));R!=null&&R.success?(h(!1),g(""),w("main"),y(""),await M(),r==null||r()):d((R==null?void 0:R.error)||"Failed to add source")}catch(R){d((R==null?void 0:R.message)||String(R))}finally{N(!1)}}},P=async R=>{if(confirm(`Remove provider source ${R}? This deletes the cloned manifests and clears any active-source entries that pointed here.`)){x(R),d(null);try{const O=jn(await t(e,"remove_provider_source",{name:R}));O!=null&&O.success?(await M(),r==null||r()):d((O==null?void 0:O.error)||"Failed to remove source")}catch(O){d((O==null?void 0:O.message)||String(O))}finally{x(null)}}},T=async(R,O)=>{C(`${R}:${O}`),d(null);try{const K=jn(await t(e,"set_active_provider_source",{type:R,sourceName:O}));K!=null&&K.success?(await M(),r==null||r()):d((K==null?void 0:K.error)||"Failed to set active source")}catch(K){d((K==null?void 0:K.message)||String(K))}finally{C(null)}};return s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-sky-400",children:"External sources"}),s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"3rd-party git URLs you've added. Providers here may ship JavaScript the daemon will execute — activation requires a confirmation."})]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsxs("button",{onClick:()=>void M(),disabled:c,className:"machine-btn text-[10px]",children:[c?"⏳":"↻"," Refresh"]}),s.jsx("button",{onClick:()=>h(!0),className:"machine-btn text-[10px] bg-sky-500/[0.08] border-sky-500/20 text-sky-300 hover:bg-sky-500/[0.14]",children:"+ Add source"})]})]}),m&&s.jsx("div",{className:"mb-2 text-[11px] text-red-400 bg-red-500/10 border border-red-500/20 rounded px-2 py-1",children:m}),n.length===0?s.jsx("div",{className:"text-[11px] text-text-muted italic",children:'No external sources registered. Use "+ Add source" to register a 3rd-party provider git URL.'}):s.jsx("ul",{className:"flex flex-col gap-2",children:n.map(R=>s.jsxs("li",{className:"rounded border border-border-subtle bg-bg-primary/40 px-3 py-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"font-mono text-[12px] text-text-primary",children:R.name}),s.jsxs("div",{className:"text-[10px] text-text-muted truncate",children:[R.url," ",s.jsxs("span",{className:"opacity-60",children:["@ ",R.ref]})]})]}),s.jsx("button",{type:"button",onClick:()=>void P(R.name),disabled:k===R.name,className:"machine-btn text-[10px] text-red-400 hover:bg-red-500/[0.10]",children:k===R.name?"…":"Remove"})]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:Object.entries(R.providers).map(([O,K])=>s.jsxs("span",{className:"mr-3",children:[s.jsxs("span",{className:"text-text-secondary",children:[O,":"]})," ",K.length]},O))})]},R.name))}),o.length>0&&s.jsxs("div",{className:"mt-3 rounded border border-amber-500/30 bg-amber-500/[0.06] px-3 py-2",children:[s.jsx("div",{className:"text-[11px] font-semibold text-amber-300 mb-1.5",children:"Conflicts"}),s.jsx("div",{className:"text-[10px] text-text-muted mb-2",children:"Multiple sources expose the same provider type. Pick which source's copy should be active."}),s.jsx("ul",{className:"flex flex-col gap-1.5",children:o.map(R=>s.jsxs("li",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"font-mono text-[11px]",children:[R.type," ",s.jsxs("span",{className:"text-text-muted",children:["(",R.category,")"]})]}),s.jsx("div",{className:"flex gap-1.5 flex-wrap",children:R.candidates.map(O=>s.jsxs("button",{type:"button",onClick:()=>void T(R.type,O),disabled:I===`${R.type}:${O}`,className:`text-[10px] px-2 py-0.5 rounded border ${R.active===O?"bg-amber-500/[0.18] border-amber-500/40 text-amber-200":"border-border-subtle text-text-secondary hover:bg-amber-500/[0.06]"}`,title:R.active===O?"Active":`Switch active to ${O}`,children:[R.active===O?"● ":"",O]},O))})]},R.type))})]}),p&&s.jsxs("div",{className:"mt-3 rounded border border-sky-500/30 bg-sky-500/[0.06] px-3 py-3",children:[s.jsx("div",{className:"text-[11px] font-semibold text-sky-300 mb-2",children:"Add external source"}),s.jsxs("div",{className:"grid md:grid-cols-3 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1 text-[10px] text-text-secondary md:col-span-3",children:[s.jsx("span",{children:"Git URL"}),s.jsx("input",{type:"text",value:b,onChange:R=>g(R.target.value),placeholder:"https://github.com/vendor/extra-providers",className:"machine-input text-[11px] font-mono"})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[10px] text-text-secondary",children:[s.jsx("span",{children:"Ref (branch/tag)"}),s.jsx("input",{type:"text",value:f,onChange:R=>w(R.target.value),placeholder:"main",className:"machine-input text-[11px]"})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[10px] text-text-secondary md:col-span-2",children:[s.jsx("span",{children:"Name (optional, auto-derived from URL)"}),s.jsx("input",{type:"text",value:j,onChange:R=>y(R.target.value),placeholder:"@vendor-extra-providers",className:"machine-input text-[11px] font-mono"})]})]}),s.jsxs("div",{className:"mt-3 flex items-center justify-end gap-2",children:[s.jsx("button",{type:"button",onClick:()=>h(!1),className:"machine-btn text-[10px]",children:"Cancel"}),s.jsx("button",{type:"button",onClick:()=>void D(),disabled:v||!b.trim(),className:"machine-btn text-[10px] bg-sky-500/[0.10] border-sky-500/30 text-sky-200 hover:bg-sky-500/[0.18]",children:v?"Cloning…":"Clone + register"})]})]})]})}function qk({machineId:e,providers:t,sendDaemonCommand:r}){var A;const[n,a]=l.useState([]),[o,i]=l.useState(!1),[c,u]=l.useState(null),[m,d]=l.useState("all"),[p,h]=l.useState(!1),[b,g]=l.useState(!1),[f,w]=l.useState(!1),[j,y]=l.useState(null),[v,N]=l.useState("normal"),[k,x]=l.useState(""),[I,C]=l.useState(!1),M=l.useCallback(async()=>{if(e)try{const B=await r(e,"get_provider_source_config",{}),L=_c(B);L&&(y(L),N(L.sourceMode),x(L.explicitProviderDir||""))}catch{}},[e,r]),D=l.useCallback(async()=>{if(e){i(!0);try{const B=await r(e,"get_provider_settings",{}),L=$k(B);if(L){const $=Ek(L,t,{filterSchema:F=>F.filter(z=>z.key!=="enabled")});$.sort((F,z)=>F.category.localeCompare(z.category)||F.displayName.localeCompare(z.displayName)),a($)}}catch{}i(!1)}},[e,t,r]);l.useEffect(()=>{n.length===0&&D(),j||M()},[]);const P=async(B,L,$)=>{u(`${B}.${L}`),a(F=>F.map(z=>z.type===B?{...z,values:{...z.values,[L]:$}}:z));try{const F=await r(e,"set_provider_setting",{providerType:B,key:L,value:$});F!=null&&F.success||D()}catch{D()}u(null)},T=async(B,L)=>{await P(B,"enabled",L),await D()},R=async B=>{u(`${B}.detect`);try{await r(e,"detect_provider",{providerType:B})}finally{await D(),u(null)}},O=async B=>{await P(B,"executablePath",""),await P(B,"executableArgs",""),await D()},K=async()=>{C(!0);try{const B=await r(e,"set_provider_source_config",{providerSourceMode:v,providerDir:Bk(k)}),L=_c(B);L?(y(L),N(L.sourceMode),x(L.explicitProviderDir||"")):await M(),await D()}catch{await M()}C(!1)},S=n.filter(B=>m==="all"||B.category===m);return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[s.jsxs("div",{className:"flex gap-1 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(B=>s.jsx("button",{onClick:()=>d(B),className:`machine-btn text-[10px] px-2 py-0.5 ${m===B?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:B.toUpperCase()},B))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>g(B=>!B),className:`machine-btn text-[10px] ${b?"bg-sky-500/[0.10] border-sky-500/30 text-sky-300":""}`,title:"Manage 3rd-party provider sources",children:"🌐 Sources"}),s.jsx("button",{onClick:()=>h(!0),className:"machine-btn text-[10px]",title:"Create a new provider from an existing one",children:"✨ Create"}),s.jsxs("button",{onClick:D,disabled:o,className:"machine-btn text-[10px]",children:[o?"⏳":"↻"," Refresh"]}),s.jsx("button",{onClick:()=>w(B=>!B),className:"machine-btn text-[10px]",title:"Show source configuration (advanced)",children:"⚙ Advanced"})]})]}),b&&s.jsx(Vk,{machineId:e,sendDaemonCommand:r,onChange:()=>{D()}}),f&&s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Where the daemon looks for provider manifests. Affects resolution and reloads."})]}),s.jsx("button",{onClick: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:v,onChange:B=>N(B.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:B=>x(B.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void K(),disabled:I,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:I?"Applying…":"Apply + Reload"})]}),s.jsxs("div",{className:"mt-3 grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"User root:"})," ",(j==null?void 0:j.userDir)||"—"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Upstream root:"})," ",(j==null?void 0:j.upstreamDir)||"—"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Provider roots:"})," ",((A=j==null?void 0:j.providerRoots)==null?void 0:A.join(" → "))||"—"]})]})]}),o&&n.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings…"}):S.length===0?s.jsx("div",{className:"px-4.5 py-8 rounded-xl border border-border-subtle bg-bg-secondary text-center",children:s.jsx("div",{className:"text-[12px] text-text-muted",children:m==="all"?'No providers installed yet. Open "Add provider" above to install one.':`No ${m.toUpperCase()} providers installed.`})}):s.jsx("div",{className:"flex flex-col gap-1.5",children:S.map(B=>s.jsx(Gk,{prov:B,providerInfo:t.find(L=>L.type===B.type),savingKey:c,onSetSetting:P,onEnableToggle:T,onDetect:R,onResetCommand:O},B.type))}),p&&s.jsx(Fk,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>h(!1),onCreated:()=>{h(!1),D()}})]})}const Yk=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Jk({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function Xk(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function Qk(e){return e.trim().toLowerCase()}function ba(e,t){const r=Qk(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function Ri(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Gs(e,t=220){const r=Ri(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function Zk(e){const t=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(t))return{kind:t.length>0?"structured":"empty",entries:t.map(r=>{const n=r;return{timestamp:Number(n.ts)||0,level:n.level||"info",message:`[${String(n.category||"daemon")}] ${String(n.message||"")}`.trim()}}),rawText:""};if(typeof t=="string"){const r=t.trim();return{kind:r?"text":"empty",entries:[],rawText:r}}return{kind:"empty",entries:[],rawText:""}}function e1(e,t){return e.filter(r=>ba([r.level,r.message],t))}function Dc(e){return`${e.timestamp}:${e.level}:${e.message}`}function t1(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const i of e.entries)n.set(Dc(i),i);for(const i of t.entries)n.set(Dc(i),i);const a=Array.from(n.values()).sort((i,c)=>i.timestamp-c.timestamp).slice(-r),o=a.reduce((i,c)=>Math.max(i,Number(c.timestamp||0)),e.lastTs);return{entries:a,kind:"structured",rawText:"",lastTs:o}}return t.kind==="text"?e.entries.length>0?e:{entries:[],kind:"text",rawText:t.rawText,lastTs:e.lastTs}:e.entries.length>0||e.rawText?e:{entries:[],kind:"empty",rawText:"",lastTs:e.lastTs}}function s1(e,t,r=120){if(t.length===0)return e;const n=new Map;for(const a of e)n.set(a.id,a);for(const a of t)n.set(a.id,a);return Array.from(n.values()).sort((a,o)=>a.ts-o.ts).slice(-r)}function r1(e,t){return e.split(`
91
+ `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>ba([r],t))}function n1(e,t){return e.filter(r=>ba([r.level,r.category,r.stage,r.interactionId,Ri(r.payload)],t))}function a1(e,t){return e.filter(r=>ba([r.kind,r.topic,r.interactionId,Ri(r.payload)],t))}function $c(e){return e==="warn"||e==="error"}function o1({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){return{all:e.length+t.length+r.length+n.length,info:e.filter(a=>a.level!=="debug").length+r.filter(a=>a.level!=="debug").length+n.length,issues:e.filter(a=>$c(a.level)).length+r.filter(a=>$c(a.level)).length}}function i1({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(o=>`${new Date(o.timestamp).toISOString()} ${o.level.toUpperCase()} ${o.message}`)].join(`
92
+ `)):t.length>0&&a.push(["[daemon logs]",...t].join(`
93
+ `)),r.length>0&&a.push(["[trace]",...r.map(o=>`${new Date(o.ts).toISOString()} ${o.level.toUpperCase()} ${o.category}.${o.stage} ${Gs(o.payload,500)}`.trim())].join(`
94
+ `)),n.length>0&&a.push(["[browser events]",...n.map(o=>`${new Date(o.ts).toISOString()} ${o.kind}${o.topic?` topic=${o.topic}`:""} ${Gs(o.payload,500)}`.trim())].join(`
95
+ `)),a.join(`
96
+
97
+ `)}function l1({machineId:e,sendDaemonCommand:t}){const[r,n]=l.useState([]),[a,o]=l.useState("empty"),[i,c]=l.useState(""),[u,m]=l.useState([]),[d,p]=l.useState([]),[h,b]=l.useState(null),[g,f]=l.useState(!0),[w,j]=l.useState("info"),[y,v]=l.useState("all"),[N,k]=l.useState(!0),[x,I]=l.useState(!0),[C,M]=l.useState(""),[D,P]=l.useState(""),[T,R]=l.useState(0),O=l.useRef(0),K=l.useRef(0),S=l.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),A=l.useRef([]),B=l.useCallback(()=>{const Y={entries:[],kind:"empty",rawText:"",lastTs:0};S.current=Y,O.current=0,n([]),c(""),o("empty"),k(!0)},[]),L=l.useCallback(()=>{A.current=[],K.current=0,m([]),I(!0)},[]),$=l.useCallback(Y=>{Y!==w&&(B(),j(Y))},[w,B]),F=l.useCallback(Y=>{v(se=>se===Y?se:Y)},[]),z=l.useCallback(()=>{B(),L(),p([]),b(null),M(""),P(""),Bs.clear()},[B,L]),re=l.useCallback(()=>{R(Y=>Y+1)},[]),J=l.useCallback(async()=>{if(!e)return;const Y=O.current,se=K.current,[fe,be]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:w,since:Y}),t(e,"get_debug_trace",Jk({count:120,since:se,category:y}))]);if(fe.status==="fulfilled"){const X=fe.value,Q=(X==null?void 0:X.result)||X,we=Zk(Q),ve=t1(S.current,we,300);S.current=ve,O.current=ve.lastTs,k(!1),M((X==null?void 0:X.success)===!1?String((X==null?void 0:X.error)||"Could not load daemon logs"):""),o(ve.kind),c(ve.rawText),n(ve.entries)}else k(!1),M(fe.reason instanceof Error?fe.reason.message:"Could not load daemon logs");if(be.status==="fulfilled"){const X=be.value,Q=(X==null?void 0:X.result)||X;if((X==null?void 0:X.success)===!1)P(String((X==null?void 0:X.error)||"Could not load daemon trace"));else if(Array.isArray(Q==null?void 0:Q.trace)){const we=Q.trace,ve=s1(A.current,we,120),xe=we.reduce((Ne,ae)=>Math.max(Ne,Number(ae.ts||0)),se);A.current=ve,xe>se&&(K.current=xe),P(""),m(ve)}else P("");I(!1)}else I(!1),P(be.reason instanceof Error?be.reason.message:"Could not load daemon trace");p(Bs.list({limit:120})),b(Date.now())},[w,e,t,y]);return l.useEffect(()=>{L()},[L,y]),l.useEffect(()=>{if(!e||(J(),!g))return;const Y=setInterval(()=>{J()},3e3);return()=>clearInterval(Y)},[g,J,e,T]),{daemonLogs:r,daemonLogKind:a,daemonRawText:i,debugTrace:u,webEvents:d,lastUpdatedAt:h,autoRefresh:g,logLevel:w,traceCategory:y,daemonLoading:N,traceLoading:x,daemonFetchError:C,traceFetchError:D,setAutoRefresh:f,setLogLevel:$,setTraceCategory:F,refresh:re,clear:z}}function c1({daemonLoading:e,traceLoading:t,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:o,daemonRawLineCount:i,traceCount:c,webEventCount:u}){return[{id:"daemon_logs",label:"Daemon logs",status:r?"error":e?"loading":o>0||i>0?"ok":"empty",detail:r||(a==="text"?`${i} raw file-fallback line(s)`:`${o} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:n?"error":t?"loading":c>0?"ok":"empty",detail:n||`${c} trace event(s)`},{id:"browser_events",label:"Browser debug events",status:u>0?"ok":"empty",detail:u>0?`${u} local browser event(s)`:"No browser events captured"}]}function Ec(e){return e==="warn"||e==="error"}function d1(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 u1(e,t){const r=e.match(/\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z\b/);if(r){const n=Date.parse(r[0]);if(Number.isFinite(n))return n}return Number.MAX_SAFE_INTEGER-1e5+t}function Bc(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function m1(e){const t=Gs(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function p1(e){const t=Gs(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function h1({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.forEach((o,i)=>{a.push({id:`daemon-log-${o.timestamp}-${i}`,source:"daemon_log",ts:Number(o.timestamp||0),severity:o.level,message:o.message,raw:o.message})}),n.forEach(o=>{a.push({id:`browser-event-${o.id}`,source:"browser_event",ts:Number(o.ts||0),severity:"info",message:p1(o),topic:o.topic,interactionId:o.interactionId,payload:o.payload})}),r.forEach(o=>{a.push({id:`daemon-trace-${o.id}`,source:"daemon_trace",ts:Number(o.ts||0),severity:o.level,message:m1(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:u1(o,i),severity:d1(o),message:o,raw:o})}),a.sort((o,i)=>o.ts!==i.ts?o.ts-i.ts:Bc(o.source)-Bc(i.source))}function f1(e){return`${e.source}:${e.severity}:${e.message}`}function x1(e){const t=e.filter(n=>Ec(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!Ec(n.severity))continue;const a=f1(n),o=r.get(a);o?(o.count+=1,o.firstTs=Math.min(o.firstTs,n.ts),o.lastTs=Math.max(o.lastTs,n.ts)):r.set(a,{key:a,source:n.source,severity:n.severity,message:n.message,count:1,firstTs:n.ts,lastTs:n.ts})}return{totalCount:e.length,issueCount:t.length,latestIssue:t[0]||null,repeatedPatterns:Array.from(r.values()).filter(n=>n.count>1).sort((n,a)=>a.count!==n.count?a.count-n.count:a.lastTs-n.lastTs).slice(0,5)}}function b1(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function Fc(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${b1(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function g1({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
98
+ `)),a.push(["[source status]",...r.map(i=>`${i.label}: ${i.status} - ${i.detail}`)].join(`
99
+ `)),t.latestIssue&&a.push(["[latest issue]",Fc(t.latestIssue)].join(`
100
+ `)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.repeatedPatterns.map(i=>`${i.count}x ${i.severity.toUpperCase()} ${i.source} ${i.message}`)].join(`
101
+ `));const o=e.slice(-n);return a.push(["[timeline]",...o.length>0?o.map(Fc):["No diagnostic events captured."]].join(`
102
+ `)),a.join(`
103
+
104
+ `)}function y1(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function v1(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function w1({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:i,searchQuery:c,daemonLoading:u,traceLoading:m,daemonFetchError:d,traceFetchError:p}){const h=Xk(n,o),b=e1(e,c),g=r1(t,c),f=n1(h,c),w=a1(a,c),j=y1(b,i),y=i==="all"?g:[],v=v1(f,i),N=i==="issues"?[]:w,k=o1({daemonLogs:b,daemonRawLines:g,trace:f,webEvents:w}),x=h1({daemonLogs:j,daemonRawLines:y,trace:v,webEvents:N}),I=x1(x),C=c1({daemonLoading:u,traceLoading:m,daemonFetchError:d,traceFetchError:p,daemonLogKind:r,daemonLogsCount:b.length,daemonRawLineCount:g.length,traceCount:f.length,webEventCount:w.length});return{filteredDaemonLogs:b,filteredDaemonRawLines:g,filteredTraceEntries:f,filteredWebEvents:w,visibleDaemonLogs:j,visibleDaemonRawLines:y,visibleTraceEntries:v,visibleWebEvents:N,quickFilterCounts:k,diagnosticEvents:x,diagnosticsSummary:I,sourceStates:C}}function j1(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Hm(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function Fo(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 ao(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 Di(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function k1({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Fo(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Hm(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:Di(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 N1({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:i,onCopyVisible:c,onToggleAutoRefresh:u,onRefresh:m,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(p=>s.jsx("button",{type:"button",onClick:()=>a(p.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===p.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:p.label},p.id))}),s.jsx("input",{value:r,onChange:p=>o(p.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:i,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:u,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:m,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:d,className:"machine-btn",children:"Clear"})]})]})}function S1({logLevel:e,traceCategory:t,onLogLevelChange:r,onTraceCategoryChange:n}){return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary p-3",children:s.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(a=>s.jsxs("button",{onClick:()=>r(a),className:`machine-btn text-[10px] px-2 py-0.5 ${e===a?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:["Daemon ",a.toUpperCase(),"+"]},a))]}),s.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:Yk.map(a=>s.jsx("button",{onClick:()=>n(a.value),className:`machine-btn text-[10px] px-2 py-0.5 ${t===a.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:a.label},a.value))})]})})}function C1({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:i,traceFetchError:c}){var d,p;const u=((d=e.latestIssue)==null?void 0:d.severity)==="error"?"danger":((p=e.latestIssue)==null?void 0:p.severity)==="warn"?"warning":"good",m=i||c?"danger":o?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${ao(e.issueCount>0?"warning":"good")}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[t," visible event(s) · ",e.issueCount," issue signal(s)"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:n.trim()?`Filtered by “${n.trim()}”`:"Daemon, trace, and browser signals merged by time"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${ao(u)}`,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:[Di(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:Hm(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 ${ao(m)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:i||c?"Needs attention":o?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",j1(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(h=>s.jsxs("div",{children:[h.label,": ",h.status]},h.id))})]})]})}function I1({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()," · ",Di(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function M1({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:i,visibleWebEvents:c,quickFilter:u,searchQuery:m}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(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:[n.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(d=>s.jsx(k1,{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:()=>r(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:u==="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,p)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:d},`raw-${p}`)),e.daemonLogKind!=="text"&&a.map((d,p)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Fo(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-${p}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(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:m.trim()?"No trace entries match the current search.":e.traceCategory==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),i.map(d=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Fo(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:Gs(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:()=>r(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:[c.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[c.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:m.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),c.map(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:Gs(d.payload,360)||"No payload"})]},d.id))]})]})]})}function A1({machineId:e,sendDaemonCommand:t}){const r=l1({machineId:e,sendDaemonCommand:t}),[n,a]=l.useState("info"),[o,i]=l.useState(""),[c,u]=l.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=l.useRef(null),d=l.useRef(!1),p=l.useMemo(()=>w1({daemonLogs:r.daemonLogs,daemonRawText:r.daemonRawText,daemonLogKind:r.daemonLogKind,debugTrace:r.debugTrace,webEvents:r.webEvents,traceCategory:r.traceCategory,quickFilter:n,searchQuery:o,daemonLoading:r.daemonLoading,traceLoading:r.traceLoading,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),[n,o,r.daemonFetchError,r.daemonLoading,r.daemonLogKind,r.daemonLogs,r.daemonRawText,r.debugTrace,r.traceCategory,r.traceFetchError,r.traceLoading,r.webEvents]);l.useEffect(()=>{if(r.autoRefresh&&p.diagnosticEvents.length>0){const g=d.current?"smooth":"instant";setTimeout(()=>{var f;(f=m.current)==null||f.scrollIntoView({behavior:g}),d.current=!0},50)}},[p.diagnosticEvents.length,r.autoRefresh]);const h=l.useCallback(async()=>{var f;const g=i1({daemonLogs:p.visibleDaemonLogs,daemonRawLines:p.visibleDaemonRawLines,trace:p.visibleTraceEntries,webEvents:p.visibleWebEvents});if(!g.trim()){tt.showToast("No visible logs to copy.","info");return}try{await((f=navigator.clipboard)==null?void 0:f.writeText(g)),tt.showToast("Copied visible logs to clipboard.","success")}catch(w){tt.showToast(w instanceof Error?w.message:"Could not copy visible logs","warning")}},[p.visibleDaemonLogs,p.visibleDaemonRawLines,p.visibleTraceEntries,p.visibleWebEvents]),b=l.useCallback(async()=>{var f;const g=g1({events:p.diagnosticEvents,summary:p.diagnosticsSummary,sources:p.sourceStates});try{await((f=navigator.clipboard)==null?void 0:f.writeText(g)),tt.showToast("Copied diagnostic bundle to clipboard.","success")}catch(w){tt.showToast(w instanceof Error?w.message:"Could not copy diagnostic bundle","warning")}},[p.diagnosticEvents,p.diagnosticsSummary,p.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(N1,{quickFilter:n,quickFilterCounts:p.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:i,onCopyDiagnostics:()=>{b()},onCopyVisible:()=>{h()},onToggleAutoRefresh:()=>r.setAutoRefresh(g=>!g),onRefresh:r.refresh,onClear:r.clear}),s.jsx(S1,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(C1,{diagnosticsSummary:p.diagnosticsSummary,diagnosticEventsCount:p.diagnosticEvents.length,sourceStates:p.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(I1,{patterns:p.diagnosticsSummary.repeatedPatterns}),s.jsx(M1,{streams:r,sectionsOpen:c,setSectionsOpen:u,diagnosticEvents:p.diagnosticEvents,visibleDaemonLogs:p.visibleDaemonLogs,visibleDaemonRawLines:p.visibleDaemonRawLines,visibleTraceEntries:p.visibleTraceEntries,visibleWebEvents:p.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:m})]})}function T1(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 Wm(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 _1(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const i=String((o==null?void 0:o.lifecycle)||"").trim(),c=Wm((o==null?void 0:o.meta)||void 0),u=((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")&&(u||c)?r.push(o):n.push(o)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function L1(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function oo(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 io(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 Oc(e){if(!e)return"unknown";const t=Date.now()-e,r=Math.max(0,Math.round(t/1e3));if(r<60)return`${r}s ago`;const n=Math.round(r/60);if(n<60)return`${n}m ago`;const a=Math.round(n/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function P1(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function R1(e){switch(e){case"running":return"bg-green-500/[0.08] text-green-500";case"starting":return"bg-sky-500/[0.08] text-sky-400";case"stopping":return"bg-orange-500/[0.08] text-orange-400";case"interrupted":return"bg-amber-500/[0.08] text-amber-400";case"failed":return"bg-red-500/[0.08] text-red-500";default:return"bg-[#ffffff0a] text-text-muted"}}function D1(e){var r;const t=new Map;for(const n of e){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const a=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!a)continue;const o=`${n.providerType}::${n.workspace}::${a}`;t.set(o,(t.get(o)||0)+1)}return Array.from(t.values()).filter(n=>n>1).length}function $1({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=l.useState(""),[o,i]=l.useState(null),[c,u]=l.useState(!1),m=y0(e,{enabled:!!e,includeSessions:!0,limit:jl,intervalMs:Gx}),d=m.diagnostics,p=m.loading,h=m.applyDiagnostics,b=l.useMemo(()=>T1({diagnostics:d,loading:p,refreshing:c,error:n}),[d,p,c,n]),g=l.useMemo(()=>new Map(t.map(P=>[P.sessionId||P.id,P])),[t]),f=l.useCallback(async()=>{if(e){u(!0);try{const P=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:jl}),T=io(P);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Could not load hosted runtime diagnostics");h(T.diagnostics||T.result||null),a("")}catch(P){const T=P instanceof Error?P.message:"Could not load hosted runtime diagnostics";a(T)}finally{u(!1)}}},[h,e,r]);l.useEffect(()=>{!e||d||p||c||f()},[d,p,e,f,c]);const w=l.useCallback(async(P,T)=>{const R=`${P}:${T.sessionId}`;if(!(P==="session_host_stop_session"&&!window.confirm(`Stop ${T.displayName}?
105
+ This will terminate the hosted runtime.`))){i(R);try{const O=await r(e,P,{sessionId:T.sessionId}),K=io(O);if(!(K!=null&&K.success))throw new Error((K==null?void 0:K.error)||"Session host action failed");const S=P==="session_host_resume_session"?"resumed":P==="session_host_restart_session"?"restarted":"stopped";tt.showToast(`Session host ${S}: ${T.displayName}`,"success"),await f()}catch(O){const K=O instanceof Error?O.message:"Session host action failed";tt.showToast(K,"warning"),a(K)}finally{i(O=>O===R?null:O)}}},[e,f,r]),j=l.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
106
+ The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){i("session_host_prune_duplicate_sessions");try{const T=await r(e,"session_host_prune_duplicate_sessions",{}),R=io(T);if(!(R!=null&&R.success))throw new Error((R==null?void 0:R.error)||"Duplicate prune failed");const O=R.result||{},K=Array.isArray(O.prunedSessionIds)?O.prunedSessionIds.length:0,S=typeof O.duplicateGroupCount=="number"?O.duplicateGroupCount:0;tt.showToast(`Pruned ${K} duplicate runtime(s) across ${S} group(s)`,"success"),await f()}catch(T){const R=T instanceof Error?T.message:"Duplicate prune failed";tt.showToast(R,"warning"),a(R)}finally{i(T=>T==="session_host_prune_duplicate_sessions"?null:T)}}},[e,f,r]),y=l.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((P,T)=>(T.lastActivityAt||0)-(P.lastActivityAt||0)),[d==null?void 0:d.sessions]),v=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)||[]}:_1(y),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,y]),N=v.liveRuntimes,k=v.recoverySnapshots,x=v.inactiveRecords,I=l.useMemo(()=>D1(N),[N]),C=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(P=>P.level==="warn"||P.level==="error")||null,[d==null?void 0:d.recentLogs]),D=(P,T)=>{var F;const R=o===`session_host_resume_session:${P.sessionId}`,O=o===`session_host_restart_session:${P.sessionId}`,K=o===`session_host_stop_session:${P.sessionId}`,S=Wm(P.meta),A=g.get(P.sessionId),B=P.attachedClients.length===1?"1 client":`${P.attachedClients.length} clients`,L=T==="recovery"?"Recover":"Resume",$=L1(T);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:P.displayName||(A==null?void 0:A.cliName)||P.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${R1(P.lifecycle)}`,children:P.lifecycle}),S&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:S})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:P.workspaceLabel||(A==null?void 0:A.runtimeWorkspaceLabel)||P.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:P.runtimeKey}),P.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",P.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((F=P.writeOwner)==null?void 0:F.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:P1(P.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(rd,{size:11})," ",B]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Oc(P.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",$]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[T==="recovery"&&(P.lifecycle==="interrupted"||P.lifecycle==="failed"||P.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{w("session_host_resume_session",P)},children:R?`${L}ing…`:L}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{w("session_host_restart_session",P)},children:O?"Restarting…":"Restart"}),T==="live"&&(P.lifecycle==="running"||P.lifecycle==="starting"||P.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{w("session_host_stop_session",P)},children:K?"Stopping…":"Stop"})]})]})},P.sessionId)};return s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(is,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:vg()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[I>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 (${I})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${b.toneClass}`,children:b.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{f()},disabled:p||c,children:[s.jsx(la,{size:13}),p||c?"Refreshing…":"Refresh"]})]})]}),n&&!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(zs,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),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:Oc(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(zs,{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(Yo,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:oo("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(P=>D(P,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(is,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:oo("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(P=>D(P,"recovery"))})]}),x.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:oo("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:x.map(P=>D(P,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),C.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:C.map(P=>{var R;const T=y.find(O=>O.sessionId===P.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(T==null?void 0:T.displayName)||((R=g.get(P.sessionId))==null?void 0:R.cliName)||P.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[P.action,P.lifecycle?` · ${P.lifecycle}`:"",P.detail?` · ${P.detail}`:"",P.error?` · ${P.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${P.success===!1?"text-red-300":"text-text-secondary"}`,children:lo(P.timestamp)})]},`${P.sessionId}:${P.timestamp}:${P.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function E1({machine:e,launchPick:t,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return s.jsx("div",{className:"fixed inset-0 z-[100] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(o=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{a(null),n({cliType:t.cliType,workspaceId:o.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:o.label||o.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:o.path})]},o.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:"Default workspace"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:"Home directory"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function B1(e,t){const r=Eu(e),n=Rs(e,t),a=mi(e,n),o=kr(e,n),i=r==="preview"?"Update to preview":"Update daemon";return a?{visible:!0,showButton:!0,title:o?"Daemon update required":"Version mismatch detected",description:o?"This machine is on an incompatible daemon version. Update it before starting more sessions.":r==="preview"?"This machine can be upgraded to the current preview daemon without opening a remote shell.":"This machine is running a different daemon version than the current app. Update it before starting more sessions.",buttonLabel:i,targetVersion:n,channel:r,required:o,tone:"warn"}:r==="preview"?{visible:!0,showButton:!1,title:n?"Preview daemon is up to date":"Preview update status unknown",description:n?"This machine is already on the current preview daemon target.":"The app is connected to preview, but the server did not report a preview target version yet.",buttonLabel:i,targetVersion:n,channel:r,required:!1,tone:n?"good":"info"}:{visible:!1,showButton:!1,title:"",description:"",buttonLabel:i,targetVersion:n,channel:r,required:!1,tone:"info"}}function co({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 uo({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function F1({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:i}){const c=n.slice(0,6),u=r.slice(0,4),d=B1(e,"0.9.82");return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[c.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(co,{icon:s.jsx(Is,{size:13}),children:"Current Chats"}),s.jsx(uo,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(p=>{const h=Do(p);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(p),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:it(p)}),h>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:ca(h)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Ss(p)})]},p.tabKey)})})})]}),u.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(co,{icon:s.jsx(id,{size:13}),children:"Recent Launches"}),s.jsx(uo,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(p=>{const{metaText:h,updatedLabel:b}=Ju(p);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>o(p),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:p.label}),b&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:b})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:h})]},p.id)})})})]}),d.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(co,{icon:s.jsx(zs,{size:13}),children:"Daemon Update"}),s.jsx(uo,{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(la,{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 O1({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:u,handleWorkspaceRemove:m,handleWorkspaceSetDefault:d}=o,[p,h]=l.useState(!1),[b,g]=l.useState(""),[f,w]=l.useState([]),[j,y]=l.useState(!1),[v,N]=l.useState(""),k=l.useCallback(async I=>{y(!0),N("");try{const C=await vi(i,e,I);g(C.path),w(C.directories)}catch(C){N(C instanceof Error?C.message:"Could not load folder")}finally{y(!1)}},[e,i]),x=l.useCallback(()=>{h(!0);const I=[...r.map(M=>M.workspace),...n.map(M=>M.workspace),...a.map(M=>M.workspace)],C=yi(t.platform,gi(I,t.defaultWorkspacePath,(t.workspaces||[]).map(M=>M.path)));k(C)},[a,n,r,k,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-4 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(Os,{size:14})," Workspaces"]}),s.jsx("button",{type:"button",className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1 rounded transition-colors text-xs",disabled:c,onClick:x,children:"+ Add workspace"})]}),(t.workspaces||[]).length===0?s.jsxs("div",{className:"text-[11px] text-text-muted py-4 text-center",children:["No saved workspaces yet. Click ",s.jsx("span",{className:"text-text-secondary",children:"+ Add workspace"})," to pick a folder."]}):s.jsx("ul",{className:"space-y-1.5 max-h-72 overflow-y-auto",children:(t.workspaces||[]).map(I=>{const C=I.id===t.defaultWorkspaceId;return s.jsxs("li",{className:`flex items-start gap-2 text-[11px] rounded-lg border px-2.5 py-2 transition-colors ${C?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:C?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void d(C?null:I.id),className:`text-base leading-none shrink-0 transition-colors ${C?"text-yellow-400 hover:text-yellow-300":"text-text-muted/40 hover:text-yellow-400"}`,children:"★"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"font-medium text-text-primary truncate",children:Nd(I.path,I.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:I.path,children:I.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void m(I.id),children:"Remove"})]},I.id)})})]}),p&&s.jsx(ji,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:b,directories:f,busy:j,error:v,confirmLabel:"Add workspace",onClose:()=>h(!1),onNavigate:I=>{k(I)},onConfirm:I=>{(async()=>{if(!I)return;await u(I)&&h(!1)})()}})]})}function z1({machine:e,machineId:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:i}){return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspaces"}),s.jsx("div",{className:"text-sm text-text-secondary",children:'Save folders as workspaces on this machine. Use the dashboard "+" button to launch a session.'})]}),i&&s.jsx(O1,{machineId:t,machine:e,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:i})]})}function H1({onNicknameSynced:e}={}){var Ne,ae,ge,me,U,H,q,ne,E,W;const{id:t}=Fp(),r=$r(),n=Ko(),{sendCommand:a}=lt(),o=Or(),i=ju(),c=Xd(),u=c.ides||[],m=c.initialLoaded??!0,d=u.find(_=>_.id===t&&_.type==="adhdev-daemon"),p=u.some(_=>_.type==="adhdev-daemon"),h=t?(Ne=c.connectionRetryStatuses)==null?void 0:Ne[t]:void 0,b=!!(h!=null&&h.blocked),[g,f]=l.useState("workspace"),[w,j]=l.useState(null);l.useCallback((_,ie)=>{j({daemonId:_,workspace:ie})},[]);const[,y]=l.useState("ide"),v=l.useRef(null),[N,k]=l.useState(null),x=l.useRef("__home__"),[I,C]=l.useState("__home__"),[M,D]=l.useState(!1),P=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||g!=="overview")return;const _=d.machine;(typeof(_==null?void 0:_.cpus)!="number"||typeof(_==null?void 0:_.totalMem)!="number"||typeof(_==null?void 0:_.arch)!="string"||typeof(_==null?void 0:_.release)!="string")&&i(t,{minFreshMs:3e4}).catch(()=>{})},[g,i,d,t]),g0(t&&g==="overview"?[t]:[],{enabled:g==="overview",intervalMs:Hx});const T=()=>{if(p){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},R=Rk({machineId:t,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:P});l.useEffect(()=>tt.onToast(ie=>{c.setToasts(ue=>{if(ue.some(Ee=>Ee.message===ie.message&&ie.timestamp-Ee.timestamp<3e3))return ue;const Pe={id:ie.id,message:ie.message,type:ie.type,timestamp:ie.timestamp,targetKey:ie.targetKey,actions:ie.actions};return[...ue.slice(-4),Pe]});const pe=ie.duration||5e3;setTimeout(()=>c.setToasts(ue=>ue.filter(oe=>oe.id!==ie.id)),pe)}),[c]);const O=(d==null?void 0:d.availableProviders)||[],K={};for(const _ of O)K[_.type]=_.icon;const S=d?{id:d.id,hostname:Sd(d,{fallbackId:d.id}),platform:((ae=d.machine)==null?void 0:ae.platform)||"unknown",arch:((ge=d.machine)==null?void 0:ge.arch)||"",cpus:((me=d.machine)==null?void 0:me.cpus)||0,totalMem:((U=d.machine)==null?void 0:U.totalMem)||0,freeMem:(H=d.machine)==null?void 0:H.freeMem,availableMem:(q=d.machine)==null?void 0:q.availableMem,loadavg:(ne=d.machine)==null?void 0:ne.loadavg,uptime:(E=d.machine)==null?void 0:E.uptime,release:((W=d.machine)==null?void 0:W.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,A=u.filter(_=>_.daemonId===t&&_.type!=="adhdev-daemon").filter(_=>!Ar(_)&&!$s(_)).map(_=>({id:_.id,sessionId:_.sessionId,type:_.type,version:_.version||"",instanceId:_.instanceId||"",status:_.status,workspace:_.workspace||null,terminals:_.terminals||0,aiAgents:Rf(_.aiAgents||(_.agents||[]).map(ie=>({id:ie.name,name:ie.name,status:ie.status,version:ie.version}))),activeChat:_.activeChat||null,chats:_.chats||[],childSessions:_.childSessions||[],cdpConnected:_.cdpConnected||!1,daemonId:t,lastMessageAt:_.lastMessageAt})),B=u.filter(_=>_.daemonId===t&&Ar(_)).map(_=>({id:_.id,sessionId:_.sessionId,type:_.type,cliName:_.cliName||_.type,status:_.status,workspace:_.workspace||"",activeChat:_.activeChat||null,providerSessionId:_.providerSessionId,mode:_.mode,runtimeKey:_.runtimeKey,runtimeDisplayName:_.runtimeDisplayName,runtimeWorkspaceLabel:_.runtimeWorkspaceLabel,runtimeWriteOwner:_.runtimeWriteOwner||null,runtimeAttachedClients:_.runtimeAttachedClients||[],daemonId:t,lastMessageAt:_.lastMessageAt})),L=u.filter(_=>_.daemonId===t&&$s(_)).map(_=>({id:_.id,sessionId:_.sessionId,type:_.type,acpName:_.cliName||_.type,status:_.status,workspace:_.workspace||"",activeChat:_.activeChat||null,providerSessionId:_.providerSessionId,daemonId:t,lastMessageAt:_.lastMessageAt})),$=d?Pt(d,{fallbackId:t}):"",F="workspace",z=n.state,re=z==null?void 0:z.initialMachineTab,J=z==null?void 0:z.initialWorkspaceCategory;z==null||z.initialWorkspaceId,z==null||z.initialWorkspacePath;const Y=re==="ides"||re==="clis"||re==="acps"?"workspace":re||F,se=re==="ides"?"ide":re==="clis"?"cli":re==="acps"?"acp":J,fe=[...A.map(_=>{var ie;return{id:`ide:${_.type}:${_.workspace||""}`,label:((ie=_.activeChat)==null?void 0:ie.title)||_.type,kind:"ide",providerType:_.type,subtitle:_.workspace||void 0,workspace:_.workspace||void 0,lastLaunchedAt:_.lastMessageAt||0}}),...B.map(_=>{var ie;return{id:`cli:${_.type}:${_.workspace||""}`,label:((ie=_.activeChat)==null?void 0:ie.title)||_.cliName,kind:"cli",providerType:_.type,providerSessionId:_.providerSessionId,subtitle:_.workspace||void 0,workspace:_.workspace||void 0,lastLaunchedAt:_.lastMessageAt||0}}),...L.map(_=>{var ie;return{id:`acp:${_.type}:${_.workspace||""}`,label:((ie=_.activeChat)==null?void 0:ie.title)||_.acpName,kind:"acp",providerType:_.type,providerSessionId:_.providerSessionId,subtitle:Ns(_.summaryMetadata)||_.workspace||void 0,workspace:_.workspace||void 0,lastLaunchedAt:_.lastMessageAt||0}})].sort((_,ie)=>(ie.lastLaunchedAt||0)-(_.lastLaunchedAt||0)),be=((d==null?void 0:d.recentLaunches)||[]).length>0?((d==null?void 0:d.recentLaunches)||[]).map(_=>({id:_.id,label:_.title||_.providerName||_.providerType,kind:_.kind,providerType:_.providerType,providerSessionId:_.providerSessionId,subtitle:Ns(_.summaryMetadata)||_.workspace||void 0,workspace:_.workspace,summaryMetadata:_.summaryMetadata,lastLaunchedAt:_.lastLaunchedAt})):fe,X=l.useMemo(()=>{var ie;const _=((ie=c.connectionStates)==null?void 0:ie[t||""])||void 0;return u.filter(pe=>pe.daemonId===t&&pe.type!=="adhdev-daemon").flatMap(pe=>ui(pe,{connectionStates:t&&_?{[t]:_}:void 0,defaultConnectionState:_})).filter(pe=>!(pe.transport==="pty"&&pe.mode==="terminal")).sort((pe,ue)=>Do(ue)-Do(pe))},[u,c.connectionStates,t]),Q=l.useCallback(_=>{const ie=Hu(_);ie&&r(Pr(ie))},[r]),we=l.useCallback(()=>{v.current&&(D(!0),v.current().finally(()=>{v.current=null,D(!1),k(null)}))},[]),ve=l.useCallback(_=>{if(!S)return;const{options:ie,selectedKey:pe}=Yu({machine:S,currentWorkspacePath:_.workspace}),ue=async()=>{y(_.kind),f("workspace")};v.current=async()=>{const oe=ie.find($e=>$e.key===x.current),Pe=(oe==null?void 0:oe.workspacePath)??null,Ee=(oe==null?void 0:oe.workspaceId)??null;if(_.kind==="ide"&&_.providerType){await R.handleLaunchIde(_.providerType,Pe?{workspace:Pe}:void 0);return}if((_.kind==="cli"||_.kind==="acp")&&_.providerType){await R.runLaunchCliCore({cliType:_.providerType,dir:Ee?void 0:Pe||"",workspaceId:Ee||void 0,model:_.kind==="acp"&&Id(_.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:_.providerSessionId});return}await ue()},x.current=pe,C(pe),k({title:_.kind==="ide"?qn("restart-ide",_.label):_.providerSessionId?iu(_.label):qn("start-fresh",_.label),description:_.kind==="ide"?Yn("restart-ide"):_.providerSessionId?lu():Yn("start-fresh"),confirmLabel:_.kind==="ide"?Jn("restart-ide"):_.providerSessionId?Vn(!0):Jn("start-fresh"),busyLabel:_.kind==="ide"?Xn("restart-ide"):_.providerSessionId?ci(!0):Xn("start-fresh"),workspaceOptions:ie,details:[{label:"Mode",value:_.kind.toUpperCase()},..._.providerType?[{label:"Provider",value:_.providerType}]:[]]})},[R,S]);if(l.useEffect(()=>{f(Y)},[F,Y,t]),l.useEffect(()=>{se&&y(se)},[se,t]),!S)return m?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:T,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const xe=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ot,{size:14})," Workspace"]}),count:A.length+B.length+L.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(ia,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(vh,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(bh,{size:14})," Logs"]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:T,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[R.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:R.nicknameInput,onChange:_=>R.setNicknameInput(_.target.value),onKeyDown:_=>{_.key==="Enter"&&R.handleSaveNickname(),_.key==="Escape"&&R.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:R.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>R.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{R.setEditingNickname(!0),R.setNicknameInput(S.machineNickname||"")},title:"Click to set nickname",children:$}),b?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),c.retryConnection&&t&&s.jsx("button",{onClick:()=>c.retryConnection(t),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:"Reconnect"})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[S.platform," · ",S.arch]}),s.jsxs("span",{children:[S.cpus," cores"]}),(d==null?void 0:d.version)&&s.jsxs("span",{children:["v",d.version]}),S.p2p.available&&s.jsxs("span",{children:["P2P ",S.p2p.state==="connected"?"connected":S.p2p.state]}),S.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:S.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:xe.map(_=>s.jsxs("button",{onClick:()=>f(_.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${g===_.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[_.label,_.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${g===_.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:_.count})]},_.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[g==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(F1,{machineEntry:d,providers:O,recentLaunches:be,currentConversations:X,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",Bu(d))}catch{}},onOpenRecent:ve,onOpenConversation:Q}),s.jsx(z1,{machine:S,machineId:t,ideSessions:A,cliSessions:B,acpSessions:L,actions:R,sendDaemonCommand:a})]}),g==="providers"&&s.jsx(qk,{machineId:t,providers:O,sendDaemonCommand:a}),g==="overview"&&s.jsx(Dk,{machine:S,ideSessions:A,cliSessions:B,acpSessions:L}),g==="session-host"&&s.jsx($1,{machineId:t,cliSessions:B,sendDaemonCommand:a}),g==="logs"&&s.jsx(A1,{machineId:t,sendDaemonCommand:a})]})})}),R.launchPick&&S&&s.jsx(E1,{machine:S,launchPick:R.launchPick,actions:R}),N&&s.jsx(qu,{title:N.title,description:N.description,details:N.details,workspaceOptions:N.workspaceOptions,selectedWorkspaceKey:I,onWorkspaceChange:_=>{x.current=_,C(_)},confirmLabel:N.confirmLabel,busyLabel:N.busyLabel,busy:M,onConfirm:we,onCancel:()=>{v.current=null,k(null)}}),w&&s.jsx(zm,{daemonId:w.daemonId,workspace:w.workspace,onClose:()=>j(null)}),s.jsx(du,{toasts:c.toasts||[],onDismiss:_=>c.setToasts(ie=>ie.filter(pe=>pe.id!==_)),onClickToast:_=>{_.targetKey&&r(Pr(_.targetKey))}}),s.jsx("style",{children:`
107
+ @keyframes toast-in {
108
+ from { opacity: 0; transform: translateX(40px); }
109
+ to { opacity: 1; transform: translateX(0); }
110
+ }
111
+ `})]})}const W1={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},Km=l.createContext(null);function K1(){const e=l.useContext(Km);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function na({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 U1({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 G1({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 V1({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 Um({status:e}){const r={online:{color:"#22c55e",label:"Online"},dirty:{color:"#f59e0b",label:"Dirty"},offline:{color:"#6b7280",label:"Offline"},degraded:{color:"#ef4444",label:"Degraded"},enabled:{color:"#22c55e",label:"Enabled"},pending:{color:"#a855f7",label:"Pending"},assigned:{color:"#3b82f6",label:"Assigned"},completed:{color:"#22c55e",label:"Completed"},failed:{color:"#ef4444",label:"Failed"},unknown:{color:"#6b7280",label:"Unknown"}}[e]||{color:"#6b7280",label:e};return s.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 rounded-md",style:{background:r.color+"15",color:r.color,border:`1px solid ${r.color}25`},children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:r.color}}),r.label]})}function q1(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function Y1({meshes:e,loading:t,error:r,onDismissError:n,daemons:a,features:o,showCreate:i,onToggleCreate:c,createName:u,onCreateNameChange:m,createRepoIdentity:d,onCreateRepoIdentityChange:p,createRepoRemoteUrl:h,onCreateRepoRemoteUrlChange:b,newMeshDaemonId:g,onNewMeshDaemonIdChange:f,newMeshWorkspace:w,onNewMeshWorkspaceChange:j,createPickerWorkspaces:y,onSelectMesh:v,onCreate:N,onCancelCreate:k}){return s.jsxs(Kr,{icon:s.jsx(Qt,{}),title:"Repo Meshes",subtitle:`${e.length} mesh${e.length!==1?"es":""}`,widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,children:"+ Create Mesh"}),children:[r&&s.jsx(os,{variant:"error",onDismiss:n,className:"mb-4",children:r}),i&&s.jsxs(ut,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:[s.jsx("h3",{className:"text-base font-bold mb-4",children:"Create Repo Mesh"}),o.createDaemonPicker&&s.jsx(jt,{label:"Create on machine",hint:"Mesh setup is stored by the selected daemon.",children:s.jsx("select",{className:"input w-full",value:g,onChange:x=>f(x.target.value),disabled:!a.length,children:a.length===0?s.jsx("option",{value:"",children:"No connected daemon"}):a.map(x=>s.jsx("option",{value:x.id,children:q1(x)},x.id))})}),o.createDaemonPicker&&s.jsx(jt,{label:"Workspace",hint:"Choose from workspaces registered by the selected daemon.",children:s.jsx("select",{className:"input w-full",value:w,onChange:x=>j(x.target.value),disabled:!g||!y.length,children:g?y.length===0?s.jsx("option",{value:"",children:"No registered workspaces"}):y.map(x=>s.jsx("option",{value:x.path,children:x.label?`${x.label} · ${x.path}`:x.path},x.id||x.path)):s.jsx("option",{value:"",children:"Select a machine first"})})}),s.jsx(jt,{label:"Name",children:s.jsx(jr,{value:u,onChange:x=>m(x.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(jt,{label:"Repo remote URL (optional)",hint:"Provide a remote URL OR a stable identity.",children:s.jsx(jr,{value:h,onChange:x=>b(x.target.value),placeholder:"https://github.com/user/repo"})}),s.jsx(jt,{label:"Repo identity (optional)",hint:"Provide a remote URL OR a stable identity.",children:s.jsx(jr,{value:d,onChange:x=>p(x.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:N,disabled:!u.trim()||!h.trim()&&!d.trim()||o.createDaemonPicker&&(!g||!w),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:k,children:"Cancel"})]})]}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):e.length===0?s.jsx(ha,{icon:s.jsx(Qt,{}),title:"No Repo Meshes",description:a.length>0?"Create a mesh to get started.":"Connect an ADHDev daemon first.",action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!a.length,onClick:c,children:"Create First Mesh"})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(x=>{var I;return s.jsx("button",{type:"button",onClick:()=>v(x.id),className:"w-full text-left bg-bg-glass border border-border-subtle rounded-xl px-5 py-4 transition-colors hover:border-border-default hover:bg-bg-secondary/70",children:s.jsxs("div",{className:"flex justify-between items-start",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(Qt,{size:16}),s.jsx("span",{className:"font-bold text-sm",children:x.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:x.repoIdentity||x.repo_identity||"No repo identity"}),(x.defaultBranch||x.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(U1,{size:11}),x.defaultBranch||x.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(x.createdAt||x.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((I=x.nodes)==null?void 0:I.length)??x.nodeCount??0," node(s)"]})]})]})},x.id)})})]})}function zc(e){if(e.status!=="completed"&&e.status!=="failed")return null;const t=e.dispatchTimestamp?new Date(e.dispatchTimestamp).getTime():NaN,r=e.updatedAt?new Date(e.updatedAt).getTime():NaN;if(!Number.isFinite(t)||!Number.isFinite(r)||r<t)return null;const n=Math.round((r-t)/1e3);if(n<60)return`${n}s`;const a=Math.floor(n/60);return a<60?`${a}m ${n%60}s`:`${Math.floor(a/60)}h ${a%60}m`}function J1({queueSummary:e,queueLoading:t,queueError:r,activeDaemonId:n,onRefresh:a}){return s.jsxs(ut,{title:"Queue",description:"Inspect active queue work separately from historical completed, failed, and cancelled task records.",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-7 gap-2 flex-1 min-w-[260px]",children:[["Active",(e==null?void 0:e.active)??0,"text-accent-primary"],["Pending",(e==null?void 0:e.activeCounts.pending)??(e==null?void 0:e.counts.pending)??0,"text-text-primary"],["Assigned",(e==null?void 0:e.activeCounts.assigned)??(e==null?void 0:e.counts.assigned)??0,"text-blue-400"],["Stale",(e==null?void 0:e.staleAssignedCount)??0,"text-amber-400"],["Historical",(e==null?void 0:e.historical)??0,"text-text-muted"],["Completed",(e==null?void 0:e.historicalCounts.completed)??(e==null?void 0:e.counts.completed)??0,"text-green-400"],["Failed",(e==null?void 0:e.historicalCounts.failed)??(e==null?void 0:e.counts.failed)??0,"text-red-400"]].map(([o,i,c])=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wide text-text-muted",children:o}),s.jsx("div",{className:`text-lg font-bold ${c}`,children:i})]},String(o)))}),s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:a,disabled:t||!n,children:[s.jsx(na,{size:13}),t?"Loading...":"Refresh Queue"]})]}),r&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:r}),e?e.recent.length===0?s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:"Queue is empty."}):s.jsx("div",{className:"flex flex-col gap-2",children:e.recent.map(o=>{var i;return s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"font-mono text-[11px] text-text-muted",children:o.id.slice(0,12)}),s.jsx(Um,{status:o.status}),o.staleAssigned&&s.jsx("span",{className:"text-[10px] text-amber-300 bg-amber-500/10 border border-amber-500/20 rounded-full px-2 py-0.5",title:o.staleReason||"Stale assignment",children:"stale"}),(((i=o.waitingOn)==null?void 0:i.length)??0)>0&&s.jsxs("span",{className:"text-[10px] text-sky-300 bg-sky-500/10 border border-sky-500/20 rounded-full px-2 py-0.5",title:`Waiting on: ${o.waitingOn.join(", ")}`,children:["waits on ",o.waitingOn.length," task",o.waitingOn.length>1?"s":""]}),o.blockedReason&&s.jsx("span",{className:"text-[10px] text-red-300 bg-red-500/10 border border-red-500/20 rounded-full px-2 py-0.5",title:o.blockedReason,children:"blocked"}),zc(o)&&s.jsxs("span",{className:"text-[10px] text-text-muted bg-bg-tertiary border border-border-subtle rounded-full px-2 py-0.5",title:"Dispatched → terminal wall clock",children:[zc(o),(o.requeueCount??0)>0?` · ${o.requeueCount} retr${o.requeueCount===1?"y":"ies"}`:""]})]}),o.message&&s.jsx("div",{className:"text-[12px] text-text-primary truncate",children:o.message})]}),s.jsxs("div",{className:"text-right text-[10px] text-text-muted shrink-0",children:[o.nodeId&&s.jsxs("div",{children:["node ",o.nodeId.slice(0,10)]}),o.sessionId&&s.jsxs("div",{children:["session ",o.sessionId.slice(0,10)]}),o.updatedAt&&s.jsx("div",{children:new Date(o.updatedAt).toLocaleTimeString()})]})]})},o.id)})}):s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:"Refresh the queue to view host-owned task counts and recent assignments."})]})}function X1(e){return e==="refine_blocked_review"?{label:"Blocked review",color:"text-amber-400 bg-amber-500/10 border-amber-500/20"}:{label:"Merge candidate",color:"text-blue-400 bg-blue-500/10 border-blue-500/20"}}function Q1(e){if(!e)return null;const t=typeof e.stage=="string"?e.stage:null,r=e.passed===!0;if(!t)return null;const n={ran:r?"text-green-400 bg-green-500/10 border-green-500/20":"text-red-400 bg-red-500/10 border-red-500/20",cached:"text-blue-400 bg-blue-500/10 border-blue-500/20",failed:"text-red-400 bg-red-500/10 border-red-500/20",skipped:"text-text-muted bg-bg-secondary border-border-subtle",legacy:"text-text-muted bg-bg-secondary border-border-subtle",not_configured:"text-text-muted bg-bg-secondary border-border-subtle"};return{label:`bootstrap: ${t}`,color:n[t]??"text-text-muted bg-bg-secondary border-border-subtle"}}function Z1({file:e}){const r={added:"text-green-400",deleted:"text-red-400",modified:"text-amber-400",renamed:"text-blue-400"}[e.status??""]??"text-text-muted";return s.jsxs("div",{className:"flex items-center justify-between gap-2 py-0.5",children:[s.jsx("span",{className:`text-[11px] font-mono truncate flex-1 ${r}`,children:e.path}),(e.insertions!=null||e.deletions!=null)&&s.jsxs("span",{className:"text-[10px] text-text-muted shrink-0",children:[e.insertions!=null&&s.jsxs("span",{className:"text-green-400",children:["+",e.insertions]}),e.deletions!=null&&s.jsxs("span",{className:"text-red-400 ml-1",children:["-",e.deletions]})]})]})}function eN({item:e,activeDaemonId:t,sendCommand:r,onDismiss:n,onRefineNode:a,onRequeueLast:o}){var N,k,x;const[i,c]=l.useState(null),[u,m]=l.useState(null),[d,p]=l.useState(!1),[h,b]=l.useState(null),{label:g,color:f}=X1(e.reviewReason),w=Q1(e.evidence.bootstrap),j=((N=e.diffSummary)==null?void 0:N.files)??[],y=((k=e.diffSummary)==null?void 0:k.baseRef)??null,v=l.useCallback(async I=>{if(!(!e.workspace||!t)){if(i===I){c(null),m(null);return}c(I),m(null),p(!0),b(null);try{const C=await r(t,"git_diff_file",{workspace:e.workspace,path:I,...y?{base:y}:{}});(C==null?void 0:C.success)!==!1&&typeof(C==null?void 0:C.diff)=="string"?m(C.diff):(C==null?void 0:C.diff)!=null?m(String(C.diff)):b((C==null?void 0:C.error)||"No diff available")}catch(C){b((C==null?void 0:C.message)||"Failed to load diff")}finally{p(!1)}}},[e.workspace,t,r,i,y]);return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary p-4 space-y-3",children:[s.jsxs("div",{className:"flex flex-wrap items-start gap-2 justify-between",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2 min-w-0",children:[s.jsx("span",{className:"text-[12px] font-semibold text-text-primary font-mono truncate max-w-[240px]",children:e.branch??e.nodeId}),s.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${f}`,children:g}),w&&s.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${w.color}`,children:w.label}),e.activeRefineJob&&s.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded border text-blue-400 bg-blue-500/10 border-blue-500/20",children:"refine running"})]}),s.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[s.jsx("button",{className:"btn btn-primary btn-sm text-[11px]",onClick:()=>a(e.nodeId),disabled:!!e.activeRefineJob,children:"Refine"}),s.jsx("button",{className:"btn btn-secondary btn-sm text-[11px]",onClick:()=>o(e.nodeId),children:"Requeue"}),s.jsx("button",{className:"btn btn-secondary btn-sm text-[11px]",onClick:()=>n(e.nodeId),children:"Dismiss"})]})]}),e.workspace&&s.jsx("div",{className:"text-[10px] text-text-muted font-mono truncate",children:e.workspace}),e.evidence.available&&s.jsxs("div",{className:"text-[11px] text-text-secondary space-y-0.5",children:[e.evidence.source==="task_completion"&&e.evidence.worker&&s.jsxs("span",{children:["Last task: ",s.jsx("span",{className:e.evidence.worker.status==="success"?"text-green-400":"text-red-400",children:e.evidence.worker.status}),e.evidence.worker.classification&&s.jsxs("span",{className:"text-text-muted ml-1",children:["(",e.evidence.worker.classification,")"]}),e.evidence.worker.errors.length>0&&s.jsxs("span",{className:"text-red-400 ml-1",children:["· ",e.evidence.worker.errors[0]]})]}),e.evidence.source==="refine_job"&&s.jsxs("span",{children:["Refinery: ",s.jsx("span",{className:"text-amber-400",children:e.convergence.status}),e.convergence.nextStep&&s.jsxs("span",{className:"text-text-muted ml-1",children:["→ ",e.convergence.nextStep]})]})]}),e.diffSummary&&e.diffSummary.files.length>0&&s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-3",children:[s.jsxs("span",{children:[e.diffSummary.totalFiles," file",e.diffSummary.totalFiles!==1?"s":""]}),s.jsxs("span",{className:"text-green-400",children:["+",e.diffSummary.totalInsertions]}),s.jsxs("span",{className:"text-red-400",children:["-",e.diffSummary.totalDeletions]}),e.diffSummary.truncated&&s.jsx("span",{className:"text-amber-400",children:"truncated"}),y&&s.jsxs("span",{className:"font-mono",children:["vs ",y]})]}),s.jsxs("div",{className:"border border-border-subtle rounded px-2 py-1 bg-bg-primary space-y-0.5",children:[j.slice(0,20).map(I=>s.jsxs("div",{children:[s.jsx("button",{className:"w-full text-left hover:bg-bg-secondary rounded px-1 transition-colors",onClick:()=>v(I.path),children:s.jsx(Z1,{file:I})}),i===I.path&&s.jsx("div",{className:"mt-1 mb-1",children:s.jsx(Om,{diff:u??"",loading:d,error:h??void 0,truncated:!1,className:"text-[10px]"})})]},I.path)),j.length>20&&s.jsxs("div",{className:"text-[10px] text-text-muted px-1 pt-0.5",children:["+",j.length-20," more files"]})]})]}),((x=e.diffSummary)==null?void 0:x.error)&&s.jsxs("div",{className:"text-[11px] text-amber-400",children:["Diff probe: ",e.diffSummary.error]})]})}function tN({items:e,loading:t,error:r,remoteNodesExcluded:n,meshId:a,activeDaemonId:o,onRefresh:i,onDismiss:c,onRefineNode:u,onRequeueLast:m,sendCommand:d}){return s.jsxs(ut,{title:"Review Inbox",description:"Local worktree nodes that need review: merge candidates and Refinery-blocked results. Click a file to preview its diff.",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[e.length>0&&s.jsxs("span",{className:"text-[12px] font-semibold text-accent-primary",children:[e.length," item",e.length!==1?"s":""]}),n&&s.jsx("span",{className:"text-[10px] text-text-muted px-1.5 py-0.5 rounded border border-border-subtle bg-bg-secondary",children:"remote nodes excluded"})]}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:i,disabled:t,children:[s.jsx(na,{size:12}),t?"Loading...":"Refresh"]})]}),r&&s.jsx("div",{className:"mb-3 text-[12px] text-red-400 bg-red-500/10 border border-red-500/20 rounded-lg px-3 py-2",children:r}),!t&&!r&&e.length===0&&s.jsxs("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:["No local nodes require review.",n&&" Remote nodes are excluded in this view."]}),s.jsx("div",{className:"space-y-3",children:e.map(p=>s.jsx(eN,{item:p,activeDaemonId:o,sendCommand:d,onDismiss:c,onRefineNode:u,onRequeueLast:m},p.nodeId))})]})}function sN(e,t){return t.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function rN(e){const t=e.assignedSessionId||e.sessionId||"unassigned session",r=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${t}: ${r}`}function Gm(e){var n;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],r=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>r.has(a)?!1:(r.add(a),!0))}function nN(e){const t=Gm(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"launch not ready unless an explicit provider is selected"}}function aN(e){return e.isLocalWorktree===!0}function oN(e,t){const r=t;return[...Array.isArray(r==null?void 0:r.cliSessions)?r.cliSessions:[],...Array.isArray(r==null?void 0:r.acpSessions)?r.acpSessions:[],...Array.isArray(r==null?void 0:r.sessions)?r.sessions:[]].filter(a=>{var o;return((o=a==null?void 0:a.settings)==null?void 0:o.meshNodeId)===e.id||(a==null?void 0:a.workspace)===e.workspace}).map(a=>{var o;return{id:a.sessionId||a.id||a.instanceId||"unknown",provider:a.providerType||a.cliType||a.acpType||a.type||"unknown",status:a.status||((o=a.activeChat)==null?void 0:o.status)||"unknown"}})}function Hc(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function iN(e,t){var r;return(e==null?void 0:e.ownerName)||(e==null?void 0:e.userName)||((r=e==null?void 0:e.user)==null?void 0:r.name)||t||"You"}function lN({nodes:e,meshQueue:t,activeDaemon:r,daemons:n,selectedMeshId:a,userName:o,features:i,coordinatorDaemonId:c,nodeProviderPriorityDrafts:u,onNodeProviderPriorityDraftChange:m,availableCliProviders:d,savingNodePolicyId:p,onUpdateNodeProviderPriority:h,nodeSystemPromptDrafts:b,onNodeSystemPromptDraftChange:g,savingNodeSystemPromptId:f,onSaveNodeSystemPrompt:w,selectedNodeId:j,onSelectNode:y,showAddNode:v,onShowAddNode:N,onCancelAddNode:k,nodeWorkspace:x,onNodeWorkspaceChange:I,nodeProviderPriority:C,onNodeProviderPriorityChange:M,nodeDaemonId:D,onNodeDaemonIdChange:P,nodeCustomPath:T,onNodeCustomPathChange:R,nodePickerWorkspaces:O,nodePickerProviders:K,attachableDaemons:S,onAddNode:A,onRemoveNode:B}){return s.jsxs(ut,{title:i.addNodeDaemonPicker?`Attached machine daemons (${e.length})`:"Nodes",description:i.addNodeDaemonPicker?"Setup inventory only. Live graph, git, session, queue, and node detail truth is owned by the Mesh Host status above.":"Workspaces participating in this mesh.",children:[i.addNodeDaemonPicker&&s.jsxs("div",{className:"mb-4 rounded-xl border border-border-subtle bg-bg-secondary/60 p-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Machine daemon candidates"}),s.jsx("div",{className:"text-[12px] text-text-muted",children:"Choose connected daemons to attach to the selected Mesh Host setup."})]}),s.jsxs("span",{className:"text-[11px] text-text-muted",children:[S.length," available"]})]}),n.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:"No connected machine daemons are currently available."}):S.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:"All connected machine daemons are already attached."}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:S.map(L=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors ${L.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{P(L.id),I(""),R(!1),M(Lr(_r(L.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:Hc(L)}),L.id===c&&s.jsx("span",{className:"text-[10px] text-accent-primary",children:"selected host"})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:L.id}),s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted",children:[(L.workspaces||[]).length," workspace(s) detected"]})]},L.id))})]}),!v&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:N,children:[s.jsx(V1,{size:13})," ",i.addNodeDaemonPicker?"Attach Machine Daemon":"+ Add Node"]}),v&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass animate-[fadeIn_0.3s_ease-out]",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:i.addNodeDaemonPicker?"Attach Machine Daemon":"Add Node"}),s.jsx("button",{onClick:()=>{k(),P(""),R(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(vt,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(jt,{label:"Machine",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:D,onChange:L=>{var $;P(L.target.value),I(""),R(!1),M(Lr(_r((($=n.find(F=>F.id===L.target.value))==null?void 0:$.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:"Select a machine..."}),n.map(L=>s.jsx("option",{value:L.id,children:Hc(L)},L.id))]})}),(i.addNodeDaemonPicker?D:!0)&&s.jsx(jt,{label:"Workspace Path",children:i.addNodeDaemonPicker&&!T&&O.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:O.map(L=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${x===L.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:()=>I(L.path),children:[s.jsx("span",{className:"font-medium block truncate",children:L.label||L.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:L.path})]},L.id||L.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{R(!0),I("")},children:"Or enter a custom path →"})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(jr,{value:x,onChange:L=>I(L.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:L=>{L.key==="Enter"&&A()}}),O.length>0&&s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{R(!1),I("")},children:"← Pick from saved workspaces"})]}):(()=>{var F;const L=Array.isArray(r==null?void 0:r.workspaces)?r.workspaces:[],$=`mesh-add-node-workspaces-${a||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(jr,{value:x,onChange:z=>I(z.target.value),placeholder:((F=L[0])==null?void 0:F.path)||"/Users/dev/projects/myapp",list:L.length>0?$:void 0,autoFocus:!0}),L.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:$,children:L.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:L.slice(0,6).map(z=>s.jsx("button",{type:"button",onClick:()=>I(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(jt,{label:i.addNodeDaemonPicker?"Default CLI providers":"Provider Priority",hint:"Order used when launching without an explicit provider.",children:s.jsx(El,{value:C,availableProviders:i.addNodeDaemonPicker?K:d,onChange:M})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:A,disabled:!x.trim()||i.addNodeDaemonPicker&&!D,className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>{k(),P(""),R(!1)},className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-300 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:"Setup inventory only — live git/session/branch detail is shown in the graph popup after direct aggregate mesh_status truth is available from the Mesh Host."}),e.length===0?s.jsx(ha,{icon:s.jsx(Os,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:e.map(L=>{const $=nN(L),F=sN(L,t),z=oN(L,r),re=j===L.id,J=aN(L),Y=L.status||L.machine_status||(F.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 ${re?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:i.addNodeDaemonPicker?void 0:"button",tabIndex:i.addNodeDaemonPicker?void 0:0,onClick:i.addNodeDaemonPicker?void 0:()=>y(re?null:L.id),onKeyDown:i.addNodeDaemonPicker?void 0:se=>{(se.key==="Enter"||se.key===" ")&&(se.preventDefault(),y(re?null:L.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:L.machine_label||L.machine_nickname||L.hostname||L.workspace}):s.jsx("span",{className:"text-sm font-medium",children:L.workspace.split("/").pop()}),i.addNodeDaemonPicker&&s.jsx(Um,{status:Y}),F.length>0&&!i.addNodeDaemonPicker&&s.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-orange-500/15 text-orange-300 border border-orange-500/25",children:[F.length," active task",F.length===1?"":"s"]}),J&&s.jsx("span",{className:`text-[10px] px-2 py-0.5 rounded-full ${i.addNodeDaemonPicker?"bg-cyan-400/10 text-cyan-300 border border-cyan-400/30":"bg-cyan-500/15 text-cyan-300 border border-cyan-500/25"}`,children:"worktree"}),i.addNodeDaemonPicker&&s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:"setup inventory"})]}),i.addNodeDaemonPicker&&s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Owner: ",iN(n.find(se=>se.id===String(L.daemon_id||"")),o)," · Machine: ",L.machine_label||L.daemon_id||L.workspace]}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:L.workspace}),J&&s.jsxs("div",{className:`mt-2 rounded-lg px-3 py-2 text-[11px] ${i.addNodeDaemonPicker?"border border-cyan-400/20 bg-cyan-400/10 text-cyan-200":"border border-cyan-500/20 bg-cyan-500/10 text-cyan-200"}`,children:["Worktree node",L.worktreeBranch?` · ${L.worktreeBranch}`:"",". Provider priority saved here is node-local and disappears when removed."]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mt-2 text-[11px] text-amber-300",children:"Live branch/git/session detail is graph-owned; use the node popup in the live graph above."}),s.jsxs("div",{className:`mt-3 max-w-2xl ${i.addNodeDaemonPicker,""}`,onClick:se=>se.stopPropagation(),children:[s.jsxs(jt,{label:i.addNodeDaemonPicker?"Default CLI providers":"Provider priority",hint:J?"Worktree-local launch defaults. Configure the source node for durable defaults.":i.addNodeDaemonPicker?"Used for coordinator/session launches when no provider is selected explicitly.":"Used when launches omit an explicit provider.",children:[s.jsx(El,{value:u[L.id]??Gm(L),availableProviders:d,onChange:se=>m(L.id,se),disabled:p===L.id,saveButton:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:se=>{se.stopPropagation(),h(L)},disabled:p===L.id,children:p===L.id?"Saving...":i.addNodeDaemonPicker?"Save defaults":"Save policy"})}),s.jsxs("div",{className:"mt-2 text-[12px]",children:[s.jsx("span",{className:"text-text-muted",children:i.addNodeDaemonPicker?"Saved default order: ":"Effective provider priority: "}),s.jsx("span",{className:$.configured?"text-text-primary font-mono":"text-amber-400",children:$.label}),!$.configured&&$.launchBlockedMessage&&s.jsxs("span",{className:"ml-2 text-amber-400",children:["(",$.launchBlockedMessage,")"]})]})]}),i.nodeInstruction&&s.jsxs(jt,{label:"Node instruction (optional)",hint:"Surfaced in the coordinator system prompt as 📌 Node instruction.",children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:3,value:b[L.id]??"",onChange:se=>{const fe=se.target.value;g(L.id,fe)},onClick:se=>se.stopPropagation(),disabled:f===L.id,placeholder:"e.g. 'Run only smoke tests here', 'Use opus on this node'"}),s.jsx("div",{className:"mt-2 flex items-center gap-2",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:se=>{se.stopPropagation(),w(L)},disabled:f===L.id,children:f===L.id?"Saving…":"Save instruction"})})]})]})]}),s.jsx("button",{className:`transition-colors bg-transparent border-none cursor-pointer ${i.addNodeDaemonPicker?"btn btn-sm text-text-muted hover:text-red-400":"text-text-muted hover:text-red-400"}`,onClick:se=>{se.stopPropagation(),B(L.id)},title:"Remove node",children:i.addNodeDaemonPicker?s.jsx(G1,{size:14}):s.jsx(vt,{size:14})})]}),!i.addNodeDaemonPicker&&re&&s.jsxs("div",{className:"mt-3 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[s.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Node ID:"})," ",s.jsx("span",{className:"font-mono",children:L.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",s.jsx("span",{className:$.configured?"text-green-400":"text-amber-400",children:$.configured?"yes":"provider priority not configured"})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Repo root:"})," ",s.jsx("span",{className:"font-mono",children:L.repoRoot||L.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",z.length]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active queue assignments"}),F.length===0?s.jsx("div",{children:"No active assigned queue task for this node."}):s.jsx("ul",{className:"m-0 pl-4",children:F.map(se=>s.jsx("li",{className:"font-mono",children:rN(se)},se.id))})]}),z.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active sessions"}),s.jsx("ul",{className:"m-0 pl-4",children:z.map(se=>s.jsxs("li",{className:"font-mono",children:[se.provider," / ",se.status," / ",se.id]},se.id))})]})]}),i.addNodeDaemonPicker&&s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:[s.jsxs("span",{className:"mr-3",children:["Node ID: ",L.id.slice(0,16),"..."]}),s.jsxs("span",{children:["Added: ",new Date(L.created_at||L.createdAt||Date.now()).toLocaleDateString()]})]})]},L.id)})})]})}function cN(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function dN({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:r,coordinatorCliType:n,onCoordinatorCliTypeChange:a,launchingCoordinator:o,launchResult:i,attachedDaemonIds:c,isHostNodeAttached:u,selectedHostNode:m,onLaunchCoordinator:d,onAttachSelectedHost:p}){return s.jsxs(ut,{title:"Mesh Host daemon",description:"Choose the daemon that will own the coordinator. Host-owned live truth is required before cloud renders status, queue, graph, or node detail.",children:[s.jsxs(os,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:"Start with one host workspace."})," ","Create a mesh on a connected daemon, then attach additional machine workspaces below. Live status, queue, and graph data come from the selected host daemon."]}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-[1fr_180px_auto] items-end",children:[s.jsx(jt,{label:"Mesh Host daemon",hint:"Cloud selects the connected daemon to command over P2P; the host must be attached before it can own a coordinator.",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:t,onChange:h=>r(h.target.value),children:[s.jsx("option",{value:"",children:"Select a Mesh Host..."}),e.map(h=>s.jsxs("option",{value:h.id,children:[cN(h)," · ",c.has(h.id)?"attached":"not attached"]},h.id))]})}),s.jsx(jt,{label:"CLI provider",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:n,onChange:h=>a(h.target.value),children:[s.jsx("option",{value:"",children:"Use node provider priority"}),s.jsx("option",{value:"claude-cli",children:"Claude Code"}),s.jsx("option",{value:"codex-cli",children:"Codex"}),s.jsx("option",{value:"gemini-cli",children:"Gemini"}),s.jsx("option",{value:"hermes-cli",children:"Hermes"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm",onClick:d,disabled:!t||!u||o,title:!u&&t?"Attach this Mesh Host daemon first.":void 0,children:o?"Launching...":"Launch Host Coordinator"})]}),s.jsx("div",{className:"mt-3 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:t?u?s.jsxs(s.Fragment,{children:["Host setup node: ",s.jsx("span",{className:"font-mono text-text-primary",children:m==null?void 0:m.workspace}),". Live graph/status/detail renders only from this daemon."]}):s.jsx(s.Fragment,{children:"Selected host is not attached yet. Attach one of its workspaces below before launching."}):"Select a connected daemon to become the Mesh Host."}),!u&&t&&s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm mt-3",onClick:p,children:"Attach selected host daemon"}),i&&s.jsx("div",{className:"mt-3 text-[12px] text-green-400 bg-green-500/10 border border-green-500/20 rounded-lg px-3 py-2",children:i})]})}function uN({meshId:e,availableCliAgents:t}){const r=t.find(a=>{const o=a.id.toLowerCase();return o==="hermes-cli"||o.includes("hermes")||a.name.toLowerCase().includes("hermes")}),n=zu(r==null?void 0:r.meshCoordinator,{meshId:e});return n?s.jsx(ut,{title:"Hermes MCP Config",description:"Hermes does not auto-import repo-local .mcp.json. Add this YAML under mcp_servers in Hermes config, then start a fresh Hermes session.",children:s.jsx(dm,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}const mo=[{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."}],mN={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,sessionCleanupOnNodeRemove:"preserve"};function Oo(e){return{...mN,...(e==null?void 0:e.policy)||{}}}function pN({selectedMesh:e,error:t,onDismissError:r,onBack:n,onDelete:a,displayedMeshStatus:o,graphLoading:i,graphError:c,graphProvenance:u,graphBootstrapFallback:m=!1,onRefreshGraph:d,queueSummary:p,queueLoading:h,queueError:b,onLoadQueue:g,savingPolicy:f,onUpdatePolicy:w,coordinatorPromptDraft:j,onCoordinatorPromptDraftChange:y,savingCoordinatorPrompt:v,onSaveCoordinatorPrompt:N,daemons:k,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:I,coordinatorCliType:C,onCoordinatorCliTypeChange:M,launchingCoordinator:D,launchResult:P,attachedDaemonIds:T,isHostNodeAttached:R,selectedHostNode:O,onLaunchCoordinator:K,activeDaemon:S,activeDaemonId:A,meshQueue:B,userName:L,nodeProviderPriorityDrafts:$,onNodeProviderPriorityDraftChange:F,availableCliProviders:z,savingNodePolicyId:re,onUpdateNodeProviderPriority:J,nodeSystemPromptDrafts:Y,onNodeSystemPromptDraftChange:se,savingNodeSystemPromptId:fe,onSaveNodeSystemPrompt:be,selectedNodeId:X,onSelectNode:Q,showAddNode:we,onShowAddNode:ve,onCancelAddNode:xe,nodeWorkspace:Ne,onNodeWorkspaceChange:ae,nodeProviderPriority:ge,onNodeProviderPriorityChange:me,nodeDaemonId:U,onNodeDaemonIdChange:H,nodeCustomPath:q,onNodeCustomPathChange:ne,nodePickerWorkspaces:E,nodePickerProviders:W,attachableDaemons:_,onAddNode:ie,onRemoveNode:pe,availableCliAgents:ue,features:oe,reviewInboxItems:Pe,reviewInboxLoading:Ee,reviewInboxError:$e,reviewInboxRemoteNodesExcluded:He,onLoadReviewInbox:Xe,onDismissReviewInboxItem:Je,onRefineNode:nt,onRequeueLast:et,sendCommand:ct}){var Me;const st=Oo(e),ft=e.nodes||[];return s.jsxs(Kr,{icon:s.jsx(Qt,{}),title:e.name,subtitle:e.repoIdentity||e.repo_identity||"Repo Mesh",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:n,children:"← Back"}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>d(!0),disabled:i,children:[s.jsx(na,{size:13}),i?"Probing...":"Refresh"]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>a(e.id),children:"Delete"})]}),children:[t&&s.jsx(os,{variant:"error",onDismiss:r,className:"mb-4",children:t}),s.jsxs(ut,{title:"Policy",description:"Coordinator safety defaults and session cleanup behavior.",children:[s.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[[{label:"Checkpoint before task",key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:Se=>Se?"yes":"no",parse:Se=>Se==="yes"},{label:"Checkpoint after task",key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:Se=>Se?"yes":"no",parse:Se=>Se==="yes"},{label:"Push approval",key:"requireApprovalForPush",opts:[["required","Require approval before push"],["not_required","Do not require approval"]],val:Se=>Se?"required":"not_required",parse:Se=>Se==="required"},{label:"Submodule main auto-publish",key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled","Require explicit approval"],["enabled","Allow Refinery non-force publish"]],val:Se=>Se?"enabled":"disabled",parse:Se=>Se==="enabled"},{label:"Destructive git approval",key:"requireApprovalForDestructiveGit",opts:[["required","Require approval"],["not_required","Do not require approval"]],val:Se=>Se?"required":"not_required",parse:Se=>Se==="required"},{label:"Dirty workspace behavior",key:"dirtyWorkspaceBehavior",opts:[["warn","Warn and continue"],["block","Block task"],["checkpoint_then_continue","Checkpoint then continue"]],val:Se=>Se||"warn",parse:Se=>Se}].map(({label:Se,key:Qe,opts:Ge,val:bt,parse:V})=>s.jsx(jt,{label:Se,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:bt(st[Qe]),onChange:G=>w({[Qe]:V(G.target.value)}),disabled:f,children:Ge.map(([G,te])=>s.jsx("option",{value:G,children:te},G))})},Qe)),s.jsx(jt,{label:"Max parallel tasks",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:String(st.maxParallelTasks??2),onChange:Se=>w({maxParallelTasks:Number(Se.target.value)}),disabled:f,children:[1,2,3,4,5,6,7,8].map(Se=>s.jsx("option",{value:Se,children:Se},Se))})})]}),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(jt,{label:"Node removal session cleanup",hint:"Separate transcript cleanup from runtime/process cleanup.",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:st.sessionCleanupOnNodeRemove||"preserve",onChange:Se=>w({sessionCleanupOnNodeRemove:Se.target.value}),disabled:f,children:mo.map(Se=>s.jsx("option",{value:Se.value,children:Se.label},Se.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((Me=mo.find(Se=>Se.value===st.sessionCleanupOnNodeRemove))==null?void 0:Me.description)||mo[0].description})]}),f&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving policy..."})]}),oe.coordinatorPrompt&&s.jsxs(ut,{title:"Coordinator prompt",description:"Customize the system prompt for coordinator sessions. Supports placeholders: {{meshName}}, {{repo}}, {{defaultBranch}}, {{cliType}}, {{nodes}}, {{policy}}, {{tools}}, {{workflow}}, {{rules}}, {{toolExposurePreflight}}.",children:[s.jsx(jt,{label:"Override (replaces default)",hint:"When set, replaces the daemon's default base prompt. Leave empty to keep the default.",children:s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:6,value:j.override,onChange:Se=>y({...j,override:Se.target.value}),disabled:v,placeholder:"(empty — daemon default applies)"})}),s.jsx(jt,{label:"Append (added after the base)",hint:"Always added after whichever base prompt wins.",children:s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:4,value:j.append,onChange:Se=>y({...j,append:Se.target.value}),disabled:v,placeholder:"(empty — nothing appended)"})}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:N,disabled:v,children:v?"Saving…":"Save coordinator prompt"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>y({override:"",append:""}),disabled:v,title:"Clear both fields. Click Save to commit.",children:"Clear"})]})]}),oe.meshHostDaemonSection&&s.jsx(dN,{daemons:k,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:Se=>{I(Se),d()},coordinatorCliType:C,onCoordinatorCliTypeChange:M,launchingCoordinator:D,launchResult:P,attachedDaemonIds:T,isHostNodeAttached:R,selectedHostNode:O,onLaunchCoordinator:K,onAttachSelectedHost:()=>{H(x),ve()}}),oe.queueSection&&s.jsx(J1,{queueSummary:p,queueLoading:h,queueError:b,activeDaemonId:A,onRefresh:g}),s.jsxs(ut,{title:"Visualization",description:"Live mesh topology: branches, worktrees, sessions, and orphan detection.",children:[s.jsxs("div",{className:"mb-4 flex flex-wrap items-center justify-between gap-3",children:[s.jsx("div",{className:"text-[12px] text-text-muted max-w-2xl",children:oe.meshHostDaemonSection?s.jsxs(s.Fragment,{children:["Direct aggregate mesh_status from the selected Mesh Host is preferred. Refresh asks the host for the latest peer git provenance.",u==="settling"&&s.jsx("span",{className:"ml-1 text-amber-300",children:"Refreshing peer provenance..."})]}):s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500"}),"healthy"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-amber-500"}),"dirty"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-red-500"}),"error"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-gray-500"}),"offline"]})]})}),s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>d(!0),disabled:i||oe.meshHostDaemonSection&&!A,children:[s.jsx(na,{size:13}),i?"Loading...":"Refresh Graph"]})]}),m&&s.jsxs("div",{className:"mb-3 flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2.5 text-[12px] text-amber-200",children:[s.jsx("span",{className:"mt-0.5 shrink-0 text-amber-400","aria-hidden":!0,children:"⚠"}),s.jsx("span",{children:"Connecting to coordinator — showing setup inventory. Live data will appear shortly."})]}),c&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:c}),o?s.jsx($m,{status:o,emptyMessage:oe.meshHostDaemonSection?"No mesh graph data is available yet. Refresh after the selected Mesh Host is reachable.":"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology.",daemonId:A,sendDaemonCommand:ct,bootstrapFallback:m}):s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:i?"Loading graph...":oe.meshHostDaemonSection?"No mesh graph data is available yet. Refresh after the selected Mesh Host is reachable.":"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology."})]}),oe.reviewInbox&&s.jsx(tN,{items:Pe,loading:Ee,error:$e,remoteNodesExcluded:He,meshId:e.id,activeDaemonId:A,onRefresh:Xe,onDismiss:Je,onRefineNode:nt,onRequeueLast:et,sendCommand:ct}),s.jsx(lN,{nodes:ft,meshQueue:B,activeDaemon:S,daemons:k,selectedMeshId:e.id,userName:L,features:{addNodeDaemonPicker:oe.addNodeDaemonPicker,nodeInstruction:oe.nodeInstruction},coordinatorDaemonId:x,nodeProviderPriorityDrafts:$,onNodeProviderPriorityDraftChange:F,availableCliProviders:z,savingNodePolicyId:re,onUpdateNodeProviderPriority:J,nodeSystemPromptDrafts:Y,onNodeSystemPromptDraftChange:se,savingNodeSystemPromptId:fe,onSaveNodeSystemPrompt:be,selectedNodeId:X,onSelectNode:Q,showAddNode:we,onShowAddNode:ve,onCancelAddNode:xe,nodeWorkspace:Ne,onNodeWorkspaceChange:ae,nodeProviderPriority:ge,onNodeProviderPriorityChange:me,nodeDaemonId:U,onNodeDaemonIdChange:H,nodeCustomPath:q,onNodeCustomPathChange:ne,nodePickerWorkspaces:E,nodePickerProviders:W,attachableDaemons:_,onAddNode:ie,onRemoveNode:pe}),oe.hermesMcpConfig&&s.jsx(uN,{meshId:e.id,availableCliAgents:ue}),oe.meshHostDaemonSection&&s.jsxs(os,{variant:"info",className:"mt-4",children:[s.jsx("strong",{children:"MCP Mode:"})," ",s.jsxs("code",{className:"bg-bg-secondary px-1 rounded text-xs",children:["adhdev mcp --repo-mesh ",e.id]})," · The mesh MCP server can be used directly from your CLI agent."]})]})}function hN({daemons:e,primaryDaemonId:t,sendCommand:r,unwrapResult:n,normalizeMesh:a,features:o}){const[i,c]=l.useState([]),[u,m]=l.useState(null),[d,p]=l.useState(!0),[h,b]=l.useState(null),[g,f]=l.useState(!1),[w,j]=l.useState(""),[y,v]=l.useState(""),[N,k]=l.useState(""),[x,I]=l.useState(""),[C,M]=l.useState(""),D=l.useMemo(()=>e.find(A=>A.id===x),[e,x]),P=(D==null?void 0:D.workspaces)||[],T=l.useMemo(()=>_r((D==null?void 0:D.availableProviders)||[]),[D]),R=l.useCallback(async()=>{p(!0);try{if(o.createDaemonPicker){const A=await Promise.allSettled(e.map(async L=>{if(!L.id)return[];const $=await r(L.id,"list_meshes",{}),F=n($);if((F==null?void 0:F.success)===!1)throw new Error(F.error||"Failed to load meshes");return(Array.isArray(F==null?void 0:F.meshes)?F.meshes:[]).map(z=>a(z,L.id)).filter(z=>z.id)})),B=new Map;for(const L of A)if(L.status==="fulfilled")for(const $ of L.value)B.has($.id)||B.set($.id,$);c(Array.from(B.values()))}else{if(!t)return;const A=await r(t,"list_meshes");A!=null&&A.success?(c((A.meshes||[]).map(B=>a(B,t))),b(null)):b((A==null?void 0:A.error)||"Failed to load meshes")}}catch(A){b((A==null?void 0:A.message)||"Failed to load meshes")}finally{p(!1)}},[e,t,r,n,a,o.createDaemonPicker]);async function O(){var $,F;const A=o.createDaemonPicker?x:t;if(!A||!w.trim())return;const B=N.trim(),L=y.trim();if(!(!B&&!L))try{const z={name:w.trim()};B&&(z.repoRemoteUrl=B),L&&(z.repoIdentity=L);const re=await r(A,"create_mesh",z),J=n(re);if((J==null?void 0:J.success)===!1)throw new Error(J.error||"Create failed");const Y=typeof(($=J==null?void 0:J.mesh)==null?void 0:$.id)=="string"?J.mesh.id:"";if(Y&&o.createDaemonPicker&&C){const se=await r(A,"add_mesh_node",{meshId:Y,daemonId:A,machineId:D==null?void 0:D.machineId,workspace:C,role:"host",providerPriority:Lr(T)}),fe=n(se);if((fe==null?void 0:fe.success)===!1)throw new Error(fe.error||"Mesh created but failed to attach workspace")}f(!1),j(""),v(""),k(""),M(""),await R(),(F=J==null?void 0:J.mesh)!=null&&F.id&&m(J.mesh.id)}catch(z){b((z==null?void 0:z.message)||"Create failed")}}async function K(A){var L;if(!confirm("Delete this mesh? This cannot be undone."))return;const B=((L=i.find($=>$.id===A))==null?void 0:L.__sourceDaemonId)||t;try{const $=await r(B,"delete_mesh",{meshId:A}),F=n($);if((F==null?void 0:F.success)===!1)throw new Error(F.error||"Failed to delete");u===A&&m(null),await R()}catch($){b(($==null?void 0:$.message)||"Delete failed")}}function S(){f(!1),j(""),v(""),k("")}return{meshes:i,setMeshes:c,selectedMeshId:u,setSelectedMeshId:m,loading:d,error:h,setError:b,showCreate:g,setShowCreate:f,createName:w,setCreateName:j,createRepoIdentity:y,setCreateRepoIdentity:v,createRepoRemoteUrl:N,setCreateRepoRemoteUrl:k,newMeshDaemonId:x,setNewMeshDaemonId:I,newMeshWorkspace:C,setNewMeshWorkspace:M,createPickerWorkspaces:P,createPickerProviders:T,loadMeshes:R,handleCreate:O,handleDelete:K,cancelCreate:S}}function fN({selectedMesh:e,selectedMeshId:t,primaryDaemonId:r,activeDaemonId:n,daemons:a,availableCliProviders:o,sendCommand:i,unwrapResult:c,loadLiveMesh:u,resolveCommandTarget:m,launchCoordinator:d,features:p,loadMeshes:h,loadQueue:b,queueSection:g,setError:f}){const[w,j]=l.useState({}),[y,v]=l.useState(null),[N,k]=l.useState(null),[x,I]=l.useState(!1),[C,M]=l.useState(""),[D,P]=l.useState([]),[T,R]=l.useState(""),[O,K]=l.useState(!1),[S,A]=l.useState(""),[B,L]=l.useState(!1),[$,F]=l.useState(null),[z,re]=l.useState(!1),[J,Y]=l.useState({override:"",append:""}),[se,fe]=l.useState(!1),[be,X]=l.useState({}),[Q,we]=l.useState(null),ve=l.useMemo(()=>a.find(E=>E.id===T),[a,T]),xe=(ve==null?void 0:ve.workspaces)||[],Ne=l.useMemo(()=>_r((ve==null?void 0:ve.availableProviders)||[]),[ve]);async function ae(){const E=(e==null?void 0:e.__sourceDaemonId)||r;if(!t||!E)return;const W=C.trim();if(W)try{const _={meshId:t,workspace:W};p.addNodeDaemonPicker&&T?(_.daemonId=T,_.machineId=ve==null?void 0:ve.machineId,_.providerPriority=In(D,Ne)):_.providerPriority=In(D,o);const ie=await i(E,"add_mesh_node",_),pe=c(ie);if((pe==null?void 0:pe.success)===!1)throw new Error(pe.error||"Add node failed");I(!1),M(""),P([]),R(""),K(!1),await h(),g||await b(t)}catch(_){f((_==null?void 0:_.message)||"Add node failed")}}async function ge(E){var pe;if(!e)return;const W=Oo(e),_=((pe=[{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(ue=>ue.value===W.sessionCleanupOnNodeRemove))==null?void 0:pe.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
112
+
113
+ Node removal cleanup policy: ${_}`))return;const ie=e.__sourceDaemonId||r;try{const ue=await i(ie,"remove_mesh_node",{meshId:e.id,nodeId:E}),oe=c(ue);if((oe==null?void 0:oe.success)===!1)throw new Error(oe.error||"Remove failed");N===E&&k(null),await h(),g||await b(t)}catch(ue){f((ue==null?void 0:ue.message)||"Remove node failed")}}async function me(E){if(!e)return;const W={...Oo(e),...E},_=e.__sourceDaemonId||r;try{re(!0),f(null);const ie=await i(_,"update_mesh",{meshId:e.id,policy:W}),pe=c(ie);if((pe==null?void 0:pe.success)===!1)throw new Error(pe.error||"Policy update failed");await h()}catch(ie){f((ie==null?void 0:ie.message)||"Policy update failed")}finally{re(!1)}}async function U(E){if(!t)return;const W=(e==null?void 0:e.__sourceDaemonId)||r,_=p.addNodeDaemonPicker?Ne:o,ie=w[E.id]||xN(E),pe=_.length>0?In(ie,_):Wr(ie),ue={...E.policy||{}};delete ue.provider_priority,pe.length?ue.providerPriority=pe:delete ue.providerPriority;try{v(E.id),f(null);const oe=await i(W,"update_mesh_node",{meshId:t,nodeId:E.id,policy:ue,providerPriority:pe}),Pe=c(oe);if((Pe==null?void 0:Pe.success)===!1){f(Pe.error||"Node policy update failed");return}await h()}catch(oe){f((oe==null?void 0:oe.message)||"Node policy update failed")}finally{v(null)}}async function H(){if(!r||!t)return;const W={...(e==null?void 0:e.coordinator)||{}};J.override.trim()?W.systemPromptOverride=J.override:delete W.systemPromptOverride,J.append.trim()?W.systemPromptAppend=J.append:delete W.systemPromptAppend,delete W.systemPromptSuffix;try{fe(!0),f(null);const _=await i(r,"update_mesh",{meshId:t,coordinator:W}),ie=c(_);if((ie==null?void 0:ie.success)===!1){f(ie.error||"Coordinator prompt save failed");return}await h()}catch(_){f((_==null?void 0:_.message)||"Coordinator prompt save failed")}finally{fe(!1)}}async function q(E){if(!r||!t)return;const W=(be[E.id]||"").trim();try{we(E.id),f(null);const _=await i(r,"update_mesh_node",{meshId:t,nodeId:E.id,systemPrompt:W}),ie=c(_);if((ie==null?void 0:ie.success)===!1){f(ie.error||"Node instruction save failed");return}await h()}catch(_){f((_==null?void 0:_.message)||"Node instruction save failed")}finally{we(null)}}async function ne(){if(e){f(null),F(null);try{L(!0);const E=u?await u(n,e.id,e):null,W=m(n,e.id,e,e.nodes||[],E);if("error"in W)throw new Error(W.error);const _=await d(W.targetDaemonId,{meshId:e.id,inlineMesh:W.inlineMesh,coordinatorNodeId:W.coordinatorNodeId,cliType:S.trim()||void 0});F(_.message)}catch(E){f((E==null?void 0:E.message)||"Coordinator launch failed")}finally{L(!1)}}}return{nodeProviderPriorityDrafts:w,setNodeProviderPriorityDrafts:j,savingNodePolicyId:y,selectedNodeId:N,setSelectedNodeId:k,showAddNode:x,setShowAddNode:I,nodeWorkspace:C,setNodeWorkspace:M,nodeProviderPriority:D,setNodeProviderPriority:P,nodeDaemonId:T,setNodeDaemonId:R,nodeCustomPath:O,setNodeCustomPath:K,nodePickerWorkspaces:xe,nodePickerProviders:Ne,coordinatorCliType:S,setCoordinatorCliType:A,launchingCoordinator:B,launchResult:$,savingPolicy:z,coordinatorPromptDraft:J,setCoordinatorPromptDraft:Y,savingCoordinatorPrompt:se,nodeSystemPromptDrafts:be,setNodeSystemPromptDrafts:X,savingNodeSystemPromptId:Q,handleAddNode:ae,handleRemoveNode:ge,handleUpdatePolicy:me,handleUpdateNodeProviderPriority:U,handleSaveCoordinatorPrompt:H,handleSaveNodeSystemPrompt:q,handleLaunchCoordinator:ne}}function xN(e){var n;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],r=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>r.has(a)?!1:(r.add(a),!0))}function bN(e){const t=e.filter(n=>n.status==="pending"||n.status==="assigned"),r=e.filter(n=>n.status==="completed"||n.status==="failed"||n.status==="cancelled");return{active:t.length,historical:r.length,activeCounts:{pending:t.filter(n=>n.status==="pending").length,assigned:t.filter(n=>n.status==="assigned").length},historicalCounts:{completed:r.filter(n=>n.status==="completed").length,failed:r.filter(n=>n.status==="failed").length},counts:{pending:e.filter(n=>n.status==="pending").length,assigned:e.filter(n=>n.status==="assigned").length,completed:e.filter(n=>n.status==="completed").length,failed:e.filter(n=>n.status==="failed").length},staleAssignedCount:e.filter(n=>n.staleAssigned).length,recent:e.slice(0,20)}}function gN({primaryDaemonId:e,activeDaemonId:t,sendCommand:r,unwrapResult:n,loadLiveMesh:a,resolveCommandTarget:o}){const[i,c]=l.useState([]),[u,m]=l.useState(null),[d,p]=l.useState(!1),[h,b]=l.useState(null),g=l.useCallback(async w=>{if(!e||!w){c([]);return}try{const j=await r(e,"get_mesh_queue",{meshId:w});c(j!=null&&j.success?Array.isArray(j.queue)?j.queue:[]:[])}catch{c([])}},[e,r]);async function f(w){var j,y;if(w){p(!0),b(null);try{const v=a?await a(t,w.id,w):null,N=o(t,w.id,w,w.nodes||[],v);if("error"in N)throw new Error(N.error);const k=await r(N.targetDaemonId,"get_mesh_queue",{meshId:w.id}),x=n(k);if((x==null?void 0:x.success)===!1)throw new Error(x.error||"Queue load failed");const I=Array.isArray(((j=x==null?void 0:x.result)==null?void 0:j.rows)??(x==null?void 0:x.rows)??(x==null?void 0:x.queue))?((y=x==null?void 0:x.result)==null?void 0:y.rows)??(x==null?void 0:x.rows)??(x==null?void 0:x.queue):[];m(bN(I))}catch(v){b((v==null?void 0:v.message)||"Queue load failed")}finally{p(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:u,queueLoading:d,queueError:h,loadQueue:g,handleLoadQueue:f}}function yN(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}function vN({selectedMeshId:e,loadMeshStatus:t,extractStatus:r,normalizeNode:n}){const[a,o]=l.useState(null),[i,c]=l.useState(!1),[u,m]=l.useState(null),[d,p]=l.useState("idle"),[h,b]=l.useState(!1);async function g(f,w=e,j=!1){if(!(!f||!w))try{c(!j&&a===null),p(j?"settling":"first_paint"),m(null);const y=await t(f,w,{refresh:j,retryProfile:j?"settled":"interactive"});b(yN(y));const v=r(y),N=n&&v?{...v,nodes:(v.nodes??[]).map(k=>n(k,v.meshId??w,""))}:v;N?(o(N),p("settled")):(o(null),m("mesh_status returned an unexpected payload."),p("idle"))}catch(y){a||o(null),m((y==null?void 0:y.message)||"Failed to load mesh graph"),p("idle")}finally{c(!1)}}return{meshGraphStatus:a,setMeshGraphStatus:o,graphLoading:i,graphError:u,setGraphError:m,graphProvenance:d,graphBootstrapFallback:h,loadGraph:g}}function wN({primaryDaemonId:e,sendCommand:t}){const[r,n]=l.useState([]),[a,o]=l.useState(!1),[i,c]=l.useState(null),[u,m]=l.useState(!1),[d,p]=l.useState(new Set),h=l.useCallback(async f=>{if(!e||!f){n([]);return}o(!0),c(null);try{const w=await t(e,"get_mesh_review_inbox",{meshId:f});w!=null&&w.success?(n(Array.isArray(w.inbox)?w.inbox:[]),m(w.remoteNodesExcluded===!0)):(c((w==null?void 0:w.error)||"Failed to load review inbox"),n([]))}catch(w){c((w==null?void 0:w.message)||"Failed to load review inbox"),n([])}finally{o(!1)}},[e,t]),b=l.useCallback(f=>{p(w=>new Set([...w,f]))},[]);return{items:r.filter(f=>!d.has(f.nodeId)),allItems:r,loading:a,error:i,remoteNodesExcluded:u,dismissedNodeIds:d,loadInbox:h,dismissItem:b}}function jN(){const e=K1(),{sendCommand:t,sendData:r,daemons:n,userName:a,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:u,unwrapResult:m,normalizeMesh:d,normalizeNode:p,resolveCommandTarget:h,features:b}=e,g=n[0],f=(g==null?void 0:g.id)||"",w=l.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(Ve=>Ve.category==="cli").map(Ve=>({id:Ve.type||Ve.id,name:Ve.displayName||Ve.name||Ve.type,meshCoordinator:Ve.meshCoordinator})),[g]),j=l.useMemo(()=>_r((g==null?void 0:g.availableProviders)||[]),[g]),{meshes:y,selectedMeshId:v,setSelectedMeshId:N,loading:k,error:x,setError:I,showCreate:C,setShowCreate:M,createName:D,setCreateName:P,createRepoIdentity:T,setCreateRepoIdentity:R,createRepoRemoteUrl:O,setCreateRepoRemoteUrl:K,newMeshDaemonId:S,setNewMeshDaemonId:A,newMeshWorkspace:B,setNewMeshWorkspace:L,createPickerWorkspaces:$,loadMeshes:F,handleCreate:z,handleDelete:re,cancelCreate:J}=hN({daemons:n,primaryDaemonId:f,sendCommand:t,unwrapResult:m,normalizeMesh:d,features:b}),Y=y.find(_e=>_e.id===v)||null,{meshGraphStatus:se,setMeshGraphStatus:fe,graphLoading:be,graphError:X,setGraphError:Q,graphProvenance:we,graphBootstrapFallback:ve,loadGraph:xe}=vN({selectedMeshId:v,loadMeshStatus:o,extractStatus:u,normalizeNode:p}),[Ne,ae]=l.useState(""),ge=b.meshHostDaemonSection&&Ne||f,{meshQueue:me,queueSummary:U,queueLoading:H,queueError:q,loadQueue:ne,handleLoadQueue:E}=gN({primaryDaemonId:f,activeDaemonId:ge,sendCommand:t,unwrapResult:m,loadLiveMesh:c,resolveCommandTarget:h}),{items:W,loading:_,error:ie,remoteNodesExcluded:pe,loadInbox:ue,dismissItem:oe}=wN({primaryDaemonId:f,sendCommand:t}),{nodeProviderPriorityDrafts:Pe,setNodeProviderPriorityDrafts:Ee,savingNodePolicyId:$e,selectedNodeId:He,setSelectedNodeId:Xe,showAddNode:Je,setShowAddNode:nt,nodeWorkspace:et,setNodeWorkspace:ct,nodeProviderPriority:st,setNodeProviderPriority:ft,nodeDaemonId:Me,setNodeDaemonId:Se,nodeCustomPath:Qe,setNodeCustomPath:Ge,nodePickerWorkspaces:bt,nodePickerProviders:V,coordinatorCliType:G,setCoordinatorCliType:te,launchingCoordinator:de,launchResult:ye,savingPolicy:je,coordinatorPromptDraft:Z,setCoordinatorPromptDraft:ee,savingCoordinatorPrompt:he,nodeSystemPromptDrafts:Ce,setNodeSystemPromptDrafts:Te,savingNodeSystemPromptId:Ie,handleAddNode:Le,handleRemoveNode:Be,handleUpdatePolicy:Ae,handleUpdateNodeProviderPriority:We,handleSaveCoordinatorPrompt:qe,handleSaveNodeSystemPrompt:mt,handleLaunchCoordinator:gt}=fN({selectedMesh:Y,selectedMeshId:v,primaryDaemonId:f,activeDaemonId:ge,daemons:n,availableCliProviders:j,sendCommand:t,unwrapResult:m,loadLiveMesh:c,resolveCommandTarget:h,launchCoordinator:i,features:{addNodeDaemonPicker:b.addNodeDaemonPicker},loadMeshes:F,loadQueue:ne,queueSection:b.queueSection,setError:I}),ht=l.useMemo(()=>n.find(_e=>_e.id===ge)||g,[n,ge,g]),ot=l.useMemo(()=>new Set(((Y==null?void 0:Y.nodes)||[]).map(_e=>String(_e.daemon_id||_e.daemonId||""))),[Y]),ze=l.useMemo(()=>n.filter(_e=>_e.id&&!ot.has(_e.id)),[n,ot]),At=(Y==null?void 0:Y.nodes)||[],le=l.useMemo(()=>At.find(_e=>String(_e.daemon_id||_e.daemonId||"")===Ne),[At,Ne]),De=b.meshHostDaemonSection?!!le:!0,ce=l.useMemo(()=>se?[...new Set((se.nodes??[]).map(_e=>String(_e.daemonId||_e.daemon_id||"")).filter(Boolean))]:[],[se]),Re=Bm({status:se,daemonId:ge||null,extraDaemonIds:ce,meshId:v,sendData:r});return l.useEffect(()=>{Ee(Object.fromEntries(((Y==null?void 0:Y.nodes)||[]).map(_e=>[_e.id,kN(_e)])))},[Y]),l.useEffect(()=>{const _e=(Y==null?void 0:Y.coordinator)||{};ee({override:typeof _e.systemPromptOverride=="string"?_e.systemPromptOverride:"",append:typeof _e.systemPromptAppend=="string"?_e.systemPromptAppend:typeof _e.systemPromptSuffix=="string"?_e.systemPromptSuffix:""}),Te(Object.fromEntries(((Y==null?void 0:Y.nodes)||[]).map(Ve=>[Ve.id,typeof Ve.systemPrompt=="string"?Ve.systemPrompt:""])))},[Y]),l.useEffect(()=>{const _e=b.addNodeDaemonPicker?Lr(V):Lr(j);Je&&st.length===0&&_e.length>0&&ft(_e)},[Je,j,V,st.length,b.addNodeDaemonPicker]),l.useEffect(()=>{const _e=new Set(((Y==null?void 0:Y.nodes)||[]).map(Ve=>Ve.id));He&&!_e.has(He)&&Xe(null)},[Y,He]),l.useEffect(()=>{if(b.meshHostDaemonSection){if(!n.length){ae("");return}(!Ne||!n.some(_e=>_e.id===Ne))&&ae(n[0].id)}},[n,Ne,b.meshHostDaemonSection]),l.useEffect(()=>{if(b.createDaemonPicker){if(!n.length){A("");return}(!S||!n.some(_e=>_e.id===S))&&A(n[0].id)}},[n,S,b.createDaemonPicker]),l.useEffect(()=>{var _e;if(!b.createDaemonPicker||!S){L("");return}if(!$.length){L("");return}$.some(Ve=>Ve.path===B)||L(((_e=$[0])==null?void 0:_e.path)||"")},[S,B,$,b.createDaemonPicker]),l.useEffect(()=>{v&&(fe(null),Q(null),xe(ge,v))},[v,ge]),l.useEffect(()=>{b.queueSection||ne(v)},[v,b.queueSection]),l.useEffect(()=>{!b.reviewInbox||!v||ue(v)},[v,b.reviewInbox]),l.useEffect(()=>{F()},[F]),f?Y?s.jsx(pN,{selectedMesh:Y,error:x,onDismissError:()=>I(null),onBack:()=>{N(null),fe(null)},onDelete:re,displayedMeshStatus:Re,graphLoading:be,graphError:X,graphProvenance:we,graphBootstrapFallback:ve,onRefreshGraph:()=>xe(ge,v,!0),queueSummary:U,queueLoading:H,queueError:q,onLoadQueue:()=>E(Y),savingPolicy:je,onUpdatePolicy:Ae,coordinatorPromptDraft:Z,onCoordinatorPromptDraftChange:ee,savingCoordinatorPrompt:he,onSaveCoordinatorPrompt:qe,daemons:n,coordinatorDaemonId:Ne,onCoordinatorDaemonIdChange:_e=>{ae(_e),fe(null)},coordinatorCliType:G,onCoordinatorCliTypeChange:te,launchingCoordinator:de,launchResult:ye,attachedDaemonIds:ot,isHostNodeAttached:De,selectedHostNode:le,onLaunchCoordinator:gt,activeDaemon:ht,activeDaemonId:ge,meshQueue:me,userName:a,nodeProviderPriorityDrafts:Pe,onNodeProviderPriorityDraftChange:(_e,Ve)=>Ee(zt=>({...zt,[_e]:Ve})),availableCliProviders:j,savingNodePolicyId:$e,onUpdateNodeProviderPriority:We,nodeSystemPromptDrafts:Ce,onNodeSystemPromptDraftChange:(_e,Ve)=>Te(zt=>({...zt,[_e]:Ve})),savingNodeSystemPromptId:Ie,onSaveNodeSystemPrompt:mt,selectedNodeId:He,onSelectNode:Xe,showAddNode:Je,onShowAddNode:()=>nt(!0),onCancelAddNode:()=>nt(!1),nodeWorkspace:et,onNodeWorkspaceChange:ct,nodeProviderPriority:st,onNodeProviderPriorityChange:ft,nodeDaemonId:Me,onNodeDaemonIdChange:Se,nodeCustomPath:Qe,onNodeCustomPathChange:Ge,nodePickerWorkspaces:bt,nodePickerProviders:V,attachableDaemons:ze,onAddNode:Le,onRemoveNode:Be,availableCliAgents:w,features:{coordinatorPrompt:b.coordinatorPrompt,meshHostDaemonSection:b.meshHostDaemonSection,queueSection:b.queueSection,hermesMcpConfig:b.hermesMcpConfig,addNodeDaemonPicker:b.addNodeDaemonPicker,nodeInstruction:b.nodeInstruction,reviewInbox:b.reviewInbox??!1},reviewInboxItems:W,reviewInboxLoading:_,reviewInboxError:ie,reviewInboxRemoteNodesExcluded:pe,onLoadReviewInbox:()=>v&&void ue(v),onDismissReviewInboxItem:oe,onRefineNode:async _e=>{v&&(await t(ge,"refine_mesh_node",{meshId:v,nodeId:_e,inlineMesh:Y}),ue(v))},onRequeueLast:async _e=>{v&&(await t(ge,"requeue_mesh_queue_task",{meshId:v,nodeId:_e}),ue(v))},sendCommand:t}):s.jsx(Y1,{meshes:y,loading:k,error:x,onDismissError:()=>I(null),daemons:n,features:{createDaemonPicker:b.createDaemonPicker},showCreate:C,onToggleCreate:()=>M(!C),createName:D,onCreateNameChange:P,createRepoIdentity:T,onCreateRepoIdentityChange:R,createRepoRemoteUrl:O,onCreateRepoRemoteUrlChange:K,newMeshDaemonId:S,onNewMeshDaemonIdChange:A,newMeshWorkspace:B,onNewMeshWorkspaceChange:L,createPickerWorkspaces:$,onSelectMesh:N,onCreate:z,onCancelCreate:J}):s.jsx(Kr,{icon:s.jsx(Qt,{}),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 kN(e){var n;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],r=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>r.has(a)?!1:(r.add(a),!0))}function NN({children:e}){const{sendCommand:t,sendData:r}=lt(),{ides:n}=Yt(),a=l.useMemo(()=>n.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[n]),o=l.useMemo(()=>({sendCommand:t,sendData:r,daemons:a,userName:void 0,loadMeshStatus:async(i,c)=>t(i,"mesh_status",{meshId:c}),launchCoordinator:async(i,c)=>{var h;const u={meshId:c.meshId};c.cliType&&(u.cliType=c.cliType);const m=await t(i,"launch_mesh_coordinator",u),d=(m==null?void 0:m.result)??m;if((d==null?void 0:d.success)===!1)throw new Error(d.error||"Coordinator launch failed");const p=(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:p,message:p?`Coordinator launched (${p})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:Mm,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,u)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:W1}),[t,r,a]);return s.jsx(Km.Provider,{value:o,children:e})}function $i(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function SN(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=$i();return r&&!t.searchParams.has("token")&&t.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Kt(e,t){return await fetch(SN(e),{credentials:"same-origin",...t})}function Vm(){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 CN{constructor(){Ue(this,"adapters",new Map);Ue(this,"states",new Map);Ue(this,"runtimeListeners",new Map);Ue(this,"screenshotCallbacks",new Map);Ue(this,"statusCallbacks",new Set);Ue(this,"stateChangeCallbacks",new Set);Ue(this,"ptyInputSender",null)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(t,r){this.adapters.set(t,r),this.states.set(t,r.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,r){this.states.set(t,r);const n=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(a=>a(n,r))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const r=this.resolveDaemonId(t);return r?this.adapters.get(r):void 0}getState(t){const r=this.resolveDaemonId(t);return r&&this.states.get(r)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,r){return!1}sendPtyInput(t,r,n){return this.ptyInputSender?this.ptyInputSender(t,r,n):!1}onScreenshot(t,r){return this.screenshotCallbacks.set(t,r),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,r){this.screenshotCallbacks.forEach(n=>n(t,r))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,r){this.statusCallbacks.forEach(n=>n(t,r))}emitRuntimeSnapshot(t,r,n=0,a=!1,o,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:o,rows:i})}emitSessionOutput(t,r,n){!t||typeof r!="string"||!r||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(t,r){const n=this.runtimeListeners.get(t)||new Set;return n.add(r),this.runtimeListeners.set(t,n),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,r,n){if(!r)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`,window.location.origin);typeof(n==null?void 0:n.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(n.sinceSeq));const o=await Kt(`${a.pathname}${a.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const u=await o.json();u!=null&&u.error&&(c=u.error)}catch{}return{success:!1,error:c}}const i=await o.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof i.seq=="number"?i.seq:0,text:typeof i.text=="string"?i.text:"",truncated:!!i.truncated,cols:typeof i.cols=="number"?i.cols:void 0,rows:typeof i.rows=="number"?i.rows:void 0,force:!!(n!=null&&n.force)}),{success:!0}}emitRuntimeEvent(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const Wt=new CN;function IN(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=$i();return r?`${t}?token=${encodeURIComponent(r)}`:t}const kn=IN(),Wc=3e3,MN=3e4;let Et=null,AN=0;const aa=new Map;let hs=null,Sr=null;function Kc(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function mr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function TN(e){return e==="connected"?"connected":e}async function Cr(e,t,r){const n=hu(e,r||{}),a=Et;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++AN}_${Date.now()}`;return new Promise((i,c)=>{const u=setTimeout(()=>{aa.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);aa.set(o,{resolve:m=>{clearTimeout(u),i(m)},reject:m=>{clearTimeout(u),c(m)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function zo(e,t){const r=Et;if(!r||r.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(t)),!0}catch{return!1}}function qm(e,t,r){const n=Et;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=hu(e,{sessionId:t,targetSessionId:t,data:r});try{return n.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}Wt.registerPtyInputSender(qm);class _N{constructor(t){Ue(this,"daemonId");Ue(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Et==null?void 0:Et.readyState)===WebSocket.OPEN}get connectionState(){return(Et==null?void 0:Et.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return Cr(this.daemonId,t,r)}async sendInput(t,r){return Cr(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,hs&&(clearInterval(hs),hs=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Cr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(o=>o.blob());Wt.emitScreenshot(this.daemonId,a)}}catch{}};r(),hs=setInterval(r,2e3)}stopScreenshots(t){hs&&(clearInterval(hs),hs=null)}}let _t=null;function LN(e){return(!_t||_t.daemonId!==e)&&(_t=new _N(e)),_t}function PN({children:e}){const t=l.useRef(Mr()),r=Mr();t.current=r;const{setUserName:n}=Yt(),a=l.useRef(n);a.current=n;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),u=l.useCallback((f,w)=>{c(f),Sr==null||Sr(f,w)},[]),m=l.useRef(null),d=l.useRef(),p=l.useRef(Wc),h=l.useRef(!0),b=l.useRef(!1),g=l.useRef("initial_connect");return l.useEffect(()=>{h.current=!0,b.current=!1;function f(){var y,v;if(!h.current||((y=m.current)==null?void 0:y.readyState)===WebSocket.OPEN||((v=m.current)==null?void 0:v.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${kn}...`),mr("connect_attempt",{url:kn,reason:g.current,delayMs:p.current});let j;try{j=new WebSocket(kn)}catch(N){console.error("[Standalone WS] Failed to create WebSocket:",N),w();return}m.current=j,j.onopen=()=>{if(!h.current){j.close();return}u("connected"),p.current=Wc,mr("open",{url:kn,reason:g.current}),qt.resubscribeAll({sendData:zo}),console.log("[Standalone WS] Connected")},Et=j,j.onmessage=N=>{var k,x;try{const I=JSON.parse(N.data);if((I.type==="command_result"||I.type==="error")&&I.requestId){const C=aa.get(I.requestId);C&&(aa.delete(I.requestId),I.type==="error"?C.reject(new Error(((k=I.data)==null?void 0:k.message)||"Command failed")):C.resolve(I.data));return}if(I.type==="session_output"){const C=I.sessionId||I.cliId||I.cliType;C&&Wt.emitSessionOutput(C,typeof I.data=="string"?I.data:"",typeof I.seq=="number"?I.seq:void 0);return}if(I.type==="runtime_snapshot"){Wt.emitRuntimeSnapshot(I.sessionId,typeof I.text=="string"?I.text:"",typeof I.seq=="number"?I.seq:0,!!I.truncated,typeof I.cols=="number"?I.cols:void 0,typeof I.rows=="number"?I.rows:void 0);return}if(I.type==="topic_update"){const C=I.update;C&&qt.publish(C);return}if(I.type==="status"||I.type==="initial_state"){const C=I.data;if(!C)return;const{injectEntries:M,markLoaded:D,getIdes:P}=t.current,T=C.instanceId||"standalone",R=P().find(S=>S.id===T),O=LN(T);Wt.register(T,O),Wt.setState(T,"connected"),u("connected",T),Wt.emitStatus(T,C);const K=Kn(C,{daemonId:T,existingDaemon:R,existingEntries:P()});Kc("ws_status",{type:I.type,daemonId:T,sessions:(C.sessions||[]).map(S=>({id:S.id,parentId:S.parentId,providerType:S.providerType,kind:S.kind,transport:S.transport,unread:S.unread,inboxBucket:S.inboxBucket,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,title:S.title})),recentLaunches:(C.recentLaunches||[]).map(S=>({id:S.id,providerType:S.providerType,kind:S.kind,workspace:S.workspace,lastLaunchedAt:S.lastLaunchedAt}))}),Kc("entries",{daemonId:T,entries:K.filter(S=>S.type!=="adhdev-daemon").map(S=>({id:S.id,type:S.type,unread:S.unread,inboxBucket:S.inboxBucket,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,sessionId:S.sessionId}))}),K.length>0&&M(K,{authoritativeDaemonIds:[T]}),D(),i.current!==T&&((x=o.current)==null||x.call(o),i.current=T,o.current=qt.subscribe({sendData:zo},T,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${T}`,params:{includeSessions:!0}},S=>{if(S.topic!=="daemon.metadata")return;const A=t.current.getIdes(),B=A.find($=>$.id===T),L=Kn(S.status,{daemonId:T,existingDaemon:B,existingEntries:A,timestamp:S.timestamp});L.length>0&&t.current.injectEntries(L,{authoritativeDaemonIds:[T]}),S.userName&&a.current&&a.current(S.userName)}))}}catch(I){console.error("[Standalone WS] Parse error:",I)}},j.onclose=N=>{h.current&&(_t==null||_t.stopScreenshots(),_t&&Wt.setState(_t.daemonId,"disconnected"),u("disconnected"),m.current=null,g.current=`close:${N.code}${N.wasClean?":clean":":unclean"}`,mr("close",{code:N.code,reason:N.reason||"",wasClean:N.wasClean}),w())},j.onerror=N=>{b.current||!h.current||(g.current="error",mr("error",{message:N instanceof Event?"event":String(N),readyState:j.readyState}),console.warn("[Standalone WS] Error, will reconnect:",N))}}function w(){if(!h.current)return;clearTimeout(d.current);const j=p.current;console.log(`[Standalone WS] Reconnecting in ${j}ms...`),mr("schedule_reconnect",{reason:g.current,delayMs:j}),d.current=setTimeout(()=>{p.current=Math.min(p.current*1.5,MN),f()},j)}return f(),()=>{var j;h.current=!1,b.current=!0,(j=o.current)==null||j.call(o),o.current=null,i.current=null,clearTimeout(d.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,Et=null),_t&&(_t.stopScreenshots(),Wt.unregister(_t.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function RN({children:e}){const[t,r]=l.useState("disconnected"),[n,a]=l.useState(null);l.useEffect(()=>(Sr=(i,c)=>{r(i),c&&a(c)},()=>{Sr=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=TN(t),u={};return n&&(u[n]=c),u.standalone=c,{wsStatus:t,isConnected:i,connectionStates:u}},[t,n]);return s.jsx(sh,{connectionOverrides:o,children:s.jsx(PN,{children:e})})}const Ym="adhdev_standalone_font_preferences",ks={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},ga=[{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"}],Dr=[{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"}],DN=new Set(ga.map(e=>e.id)),$N=new Set(Dr.map(e=>e.id));function Gt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:En("chat",t.chat),code:En("code",t.code),terminal:En("terminal",t.terminal)}}function En(e,t){const r=ks[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof n.preset=="string"?n.preset.trim():"",o=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?DN:$N).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function Bn(e,t){var a;const r=En(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?ga:Dr;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function EN(e){const t=Gt(e),r=Bn("chat",t.chat),n=Bn("code",t.code),a=Bn("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function xs(e,t=document.documentElement){const r=Gt(e),n=EN(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function Ho(e){const t=Gt(e);try{localStorage.setItem(Ym,JSON.stringify(t))}catch{}return t}function BN(){try{const e=localStorage.getItem(Ym);if(e)return Gt(JSON.parse(e))}catch{}return ks}function FN(){return xs(BN())}function pr(e,t){var n;const r=e==="chat"?ga:Dr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const ON=[{id:"dashboard",path:"/dashboard",icon:s.jsx(sd,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(is,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(Hs,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(ia,{}),label:"Settings"}];function zN({children:e}){const t=$r(),r=Ko(),n=l.useMemo(()=>ON.map(o=>({...o,active:r.pathname.startsWith(o.path),onSelect:()=>t(o.path)})),[r.pathname,t]),a=l.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Docs"}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(nd,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(ad,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Hg,{brand:({collapsed:o})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!o&&s.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:o})=>o?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.82"]}),footerActions:({collapsed:o,toggleCollapsed:i})=>s.jsxs("div",{className:`nav-item cursor-pointer ${o?"justify-center py-2.5 px-0":"mt-1"}`,onClick:i,title:o?"Expand sidebar":"Collapse sidebar",children:[s.jsx("span",{className:"nav-icon text-base",children:o?"›":"‹"}),!o&&s.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const HN=[{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(Is,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(od,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Ot,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Hs,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(nd,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],WN=[{icon:s.jsx(jh,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(sd,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Er,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(xh,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(rd,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(gh,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],KN=[{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 UN(){return s.jsxs(Kr,{icon:s.jsx(ad,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.9.82"]}),children:[s.jsx(ut,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:"Keep the same dashboard experience, with the runtime fully on-device."}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers."})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"Docs ↗"}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"GitHub ↗"}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:"Try Cloud ↗"})]})]})}),s.jsx(ut,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:HN.map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(ut,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:fu.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:bu.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:xu.map(e=>`${e.icon} ${e.name}`)}].map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(t=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:t},t))})]},e.label))})}),s.jsx(ut,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:WN.map(e=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(ut,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),s.jsx("tbody",{children:KN.map((e,t)=>s.jsxs("tr",{className:t%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),s.jsx(ha,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:"Cloud is optional, not required",description:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",action:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(_h,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function po(e,t,r){return{...e,[t]:r}}function ho({surface:e,title:t,description:r,value:n,options:a,onChange:o}){return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:i=>{const c=i.target.value;o(c==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:c})},children:a.map(i=>s.jsx("option",{value:i.id,children:i.label},i.id))}),n.preset==="custom"&&s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:i=>o({preset:"custom",customFamily:i.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",s.jsx("span",{className:"font-mono break-all",children:Bn(e,n)})]})]})]})}function GN({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:u}){const m=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&s.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&s.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(ho,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:ga,onChange:d=>o(po(e,"chat",d))}),s.jsx(ho,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Dr,onChange:d=>o(po(e,"code",d))}),s.jsx(ho,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Dr,onChange:d=>o(po(e,"terminal",d))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",pr("chat",e.chat.preset)," · Code: ",pr("code",e.code.preset)," · Terminal: ",pr("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",pr("chat",ks.chat.preset)," / ",pr("code",ks.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:i,disabled:r||!m,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),s.jsx("button",{type:"button",onClick:c,disabled:r||!m,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),s.jsx("button",{type:"button",onClick:u,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function VN(){const{ides:e}=Yt(),t=e.find(X=>X.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=lt(),{userName:a}=Yt(),[o,i]=l.useState(a||""),[c,u]=l.useState(null),[m,d]=l.useState(null),[p,h]=l.useState(ks),[b,g]=l.useState(!1),[f,w]=l.useState(""),[j,y]=l.useState(""),[v,N]=l.useState("127.0.0.1"),[k,x]=l.useState(""),[I,C]=l.useState(""),[M,D]=l.useState(""),[P,T]=l.useState(""),[R,O]=l.useState(""),[K,S]=l.useState(!1),A=async()=>{const Q=await(await Kt("/auth/session")).json();u(Q)},B=async()=>{const Q=await(await Kt("/api/v1/standalone/preferences")).json();d(Q),N(Q.standaloneBindHost);const we=Gt(Q.standaloneFontPreferences);h(we),xs(we),Ho(we)};l.useEffect(()=>{a!==void 0&&i(a)},[a]),l.useEffect(()=>{Promise.all([A(),B()]).catch(X=>{T(X instanceof Error?X.message:String(X))})},[]),l.useEffect(()=>{xs(p)},[p]);const L=X=>{const Q=X.target.value.trim();t!=null&&t.id&&Q!==a&&n(t.id,"set_user_name",{userName:Q}).catch(console.error)},[$,F]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),z=X=>{F(X);try{localStorage.setItem("adhdev_sound",X?"1":"0")}catch{}},re=async()=>{w(""),y(""),g(!0);try{const X=Gt(p),Q=await Kt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:X})}),we=await Q.json();if(!Q.ok)throw new Error((we==null?void 0:we.error)||"Failed to save standalone font preferences");const ve=Gt(we.standaloneFontPreferences);d(we),h(ve),xs(ve),Ho(ve),y("Standalone chat fonts saved for this self-hosted dashboard.")}catch(X){w(X instanceof Error?X.message:String(X))}finally{g(!1)}},J=()=>{const X=Gt(m==null?void 0:m.standaloneFontPreferences);w(""),y(""),h(X),xs(X)},Y=()=>{w(""),y(""),h(ks),xs(ks)},se=async()=>{T(""),O(""),S(!0);try{const X=await Kt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:v})}),Q=await X.json();if(!X.ok)throw new Error((Q==null?void 0:Q.error)||"Failed to save standalone network preference");d(Q),N(Q.standaloneBindHost),O(Q.standaloneBindHost==="0.0.0.0"?"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.":"Default standalone network mode set to localhost only. Restart standalone to apply it.")}catch(X){T(X instanceof Error?X.message:String(X))}finally{S(!1)}},fe=async()=>{if(T(""),O(""),I.trim().length<4){T("Password must be at least 4 characters.");return}if(I!==M){T("New password and confirmation do not match.");return}S(!0);try{const X=await Kt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,newPassword:I})}),Q=await X.json();if(!X.ok)throw new Error((Q==null?void 0:Q.error)||"Failed to save password");u(Q),await B(),x(""),C(""),D(""),O(c!=null&&c.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Vm()}catch(X){T(X instanceof Error?X.message:String(X))}finally{S(!1)}},be=async()=>{T(""),O(""),S(!0);try{const X=await Kt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,clear:!0})}),Q=await X.json();if(!X.ok)throw new Error((Q==null?void 0:Q.error)||"Failed to clear password");u(Q),await B(),x(""),C(""),D(""),O("Standalone password disabled.")}catch(X){T(X instanceof Error?X.message:String(X))}finally{S(!1)}};return s.jsxs(Kr,{icon:s.jsx(ia,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(os,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint."}),(c==null?void 0:c.publicHostWarning)&&s.jsx(os,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),s.jsx(ut,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:"Version"}),s.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.82"]}),s.jsx("span",{className:"text-text-muted",children:"Status"}),s.jsx("span",{className:t?"text-green-400":"text-yellow-400",children:t?"● Running":"○ Not connected"}),s.jsx("span",{className:"text-text-muted",children:"Current bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.currentBindHost)||(c==null?void 0:c.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Default bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:c!=null&&c.hasPasswordAuth?"Password enabled":c!=null&&c.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(ut,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:v==="127.0.0.1",onChange:()=>N("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:v==="0.0.0.0",onChange:()=>N("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points."})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:()=>{se()},disabled:K,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:K?"Saving…":"Save default network mode"}),s.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(m==null?void 0:m.currentBindHost)||(c==null?void 0:c.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(ut,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:c!=null&&c.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),P&&s.jsx(os,{variant:"error",children:P}),R&&s.jsx(os,{variant:"success",children:R}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:c!=null&&c.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:k,onChange:X=>x(X.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:c!=null&&c.hasPasswordAuth?"New password":"New standalone password",value:I,onChange:X=>C(X.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:M,onChange:X=>D(X.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{fe()},disabled:K,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:K?"Saving…":c!=null&&c.hasPasswordAuth?"Update password":"Enable password"}),(c==null?void 0:c.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{be()},disabled:K,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),s.jsx(ut,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(X=>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 ${X.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:X.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:X.type})]},X.type))})}),s.jsx(ut,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(Xg,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(ut,{title:"Coordinator prompts",description:"User-level overrides for the mesh coordinator system prompt. Per-mesh overrides live in the Repo Mesh page.",children:s.jsx(t0,{daemonId:t==null?void 0:t.id})}),s.jsx(ut,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),s.jsx(r0,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI."}),s.jsx(u0,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Fonts"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),s.jsx(GN,{value:p,savedValue:Gt(m==null?void 0:m.standaloneFontPreferences),saving:b,error:f,notice:j,onChange:h,onSave:()=>{re()},onResetToSaved:J,onResetToDefaults:Y})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout."}),s.jsx(h0,{})]})]})}),s.jsx(ut,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(qg,{}),s.jsx(fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Th,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:$,onChange:z})]})}),s.jsx(ut,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(fh,{size:16,className:"text-text-secondary"})," Display Name"]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:o,onChange:X=>i(X.target.value),onBlur:L,onKeyDown:X=>{X.key==="Enter"&&X.currentTarget.blur()}})]})})})]})}const qN=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],br="adhdev_onboarding_done",YN=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],JN={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function XN({onDone:e}){const[t,r]=l.useState([]),[n,a]=l.useState(new Set(qN)),[o,i]=l.useState(!0),[c,u]=l.useState(null),[m,d]=l.useState(!1),[p,h]=l.useState(null),[b,g]=l.useState("all");l.useEffect(()=>{let k=!1;const x=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${x}/providers?sort=popular&limit=100`).then(I=>{if(!I.ok)throw new Error(`HTTP ${I.status}`);return I.json()}).then(I=>{k||r(I.providers??[])}).catch(I=>{k||u(I instanceof Error?I.message:String(I))}).finally(()=>{k||i(!1)}),()=>{k=!0}},[]);const f=t.filter(k=>b==="all"||k.category===b),w=["cli","ide","extension","acp"].map(k=>({category:k,items:f.filter(x=>x.category===k)})).filter(k=>k.items.length>0),j=l.useCallback(k=>{a(x=>{const I=new Set(x);return I.has(k)?I.delete(k):I.add(k),I})},[]),y=l.useCallback(async()=>{if(n.size===0){localStorage.setItem(br,"1"),e();return}d(!0);const k=[];for(const x of n)try{const C=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:x})})).json().catch(()=>({}));k.push({type:x,ok:!!C.success,error:C.error})}catch(I){k.push({type:x,ok:!1,error:I instanceof Error?I.message:String(I)})}h(k),d(!1),k.every(x=>x.ok)&&localStorage.setItem(br,"1")},[n,e]),v=l.useCallback(()=>{localStorage.setItem(br,"1"),e()},[e]),N=l.useCallback(()=>{p&&p.every(k=>k.ok)?e():m||v()},[p,m,e,v]);return s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60",onClick:N,children:s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-2xl max-w-2xl w-full p-6 flex flex-col gap-5 max-h-[85vh] overflow-y-auto",onClick:k=>k.stopPropagation(),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Welcome to ADHDev"}),s.jsxs("div",{className:"text-[12px] text-text-muted mt-1",children:["Pick the providers you want to use. Defaults to the four officially supported CLI providers; you can install IDE, ACP, or extension providers from the tabs below or later from ",s.jsx("span",{className:"text-text-secondary",children:"Burrow → Providers → Add provider"}),"."]})]}),!o&&!c&&t.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:YN.map(k=>{const x=k.key==="all"?t.length:t.filter(I=>I.category===k.key).length;return x===0&&k.key!=="all"?null:s.jsxs("button",{onClick:()=>g(k.key),className:`machine-btn text-[10px] px-2 py-0.5 ${b===k.key?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:[k.label," ",s.jsxs("span",{className:"opacity-60",children:["(",x,")"]})]},k.key)})}),o&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:"Loading registry…"}),!o&&c&&s.jsxs("div",{className:"rounded-xl border border-red-500/30 bg-red-500/5 px-3 py-2 text-[12px] text-red-400",children:["Failed to load registry: ",c]}),!o&&!c&&f.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:"No providers in this category."}),!o&&!c&&f.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:w.map(k=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:JN[k.category]??k.category}),s.jsx("div",{className:"grid gap-1.5",children:k.items.map(x=>{var P,T;const I=n.has(x.type),C=p==null?void 0:p.find(R=>R.type===x.type),M=((P=x.manifest)==null?void 0:P.icon)??"📦",D=((T=x.manifest)==null?void 0:T.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${I?"bg-violet-500/[0.06] border-violet-500/30":"bg-bg-glass border-border-subtle hover:bg-bg-glass-hover"}`,children:[s.jsx("input",{type:"checkbox",checked:I,onChange:()=>j(x.type),disabled:m,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:M}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:x.displayName}),D&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:D})]}),C&&s.jsx("span",{className:`text-[10px] font-semibold ${C.ok?"text-green-400":"text-red-400"}`,children:C.ok?"✓ installed":`✗ ${C.error??"failed"}`})]},x.type)})})]},k.category))}),s.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-border-subtle",children:[s.jsxs("div",{className:"text-[11px] text-text-muted",children:[n.size," provider",n.size!==1?"s":""," selected"]}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx("button",{onClick:v,disabled:m,className:"machine-btn text-[11px] px-3 py-1",children:"Skip"}),s.jsx("button",{onClick:()=>{p?(localStorage.setItem(br,"1"),e()):y()},disabled:m||!p&&n.size===0,className:"machine-btn text-[11px] px-3 py-1 bg-violet-500/15 border-violet-500/40 text-violet-400 hover:bg-violet-500/25",children:m?"Installing…":p?"Done":`Install ${n.size}`})]})]})]})})}function QN(){try{return localStorage.getItem(br)==="1"}catch{return!1}}Og();c0();FN();const ZN=Qc({baseUrl:"",getToken:$i});function eS({children:e}){const[t,r]=l.useState(null),[n,a]=l.useState(!0),[o,i]=l.useState(""),[c,u]=l.useState(""),[m,d]=l.useState(!1),p=async()=>{a(!0),u("");try{const g=await(await Kt("/auth/session")).json();r(g)}catch(b){u(b instanceof Error?b.message:String(b))}finally{a(!1)}};l.useEffect(()=>{p()},[]),l.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let b=!1;return(async()=>{try{const g=await Kt("/api/v1/standalone/preferences");if(!g.ok)return;const f=await g.json();if(b)return;const w=Gt(f.standaloneFontPreferences);xs(w),Ho(w)}catch{}})(),()=>{b=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const h=async b=>{b.preventDefault(),d(!0),u("");try{const g=await Kt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),f=await g.json();if(!g.ok)throw new Error((f==null?void 0:f.error)||"Login failed");r(f),i(""),Vm()}catch(g){u(g instanceof Error?g.message:String(g))}finally{d(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:h,children:[s.jsx("input",{type:"password",value:o,onChange:b=>i(b.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.jsx("button",{type:"submit",disabled:m||!o,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:m?"Signing in…":"Unlock dashboard"})]}):s.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),c&&s.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:c})]})}):s.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",c||"unknown error"]})}function Uc(){const{ides:e,initialLoaded:t}=Yt();if(!t)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?s.jsx(bo,{to:`/machines/${r.id}`,replace:!0}):s.jsx(bo,{to:"/dashboard",replace:!0})}function tS(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let r=!1;if(!QN())return fetch("/api/v1/providers/installed").then(n=>n.ok?n.json():{providers:[]}).then(n=>{r||(n.providers??[]).length===0&&t(!0)}).catch(()=>{}),()=>{r=!0}},[]),e?s.jsx(XN,{onDone:()=>t(!1)}):null}function sS(){const{ides:e}=Yt(),t=l.useMemo(()=>{for(const m of e)if(m.activeInteractivePrompt)return m.instanceId??m.id;return null},[e]),{promptSession:r,hasActivePrompt:n,responseError:a,isSubmitting:o,submit:i,cancel:c,reopen:u}=Iu(t);return n?s.jsxs("div",{className:"relative",children:[!r&&s.jsx("button",{type:"button",onClick:u,className:"fixed bottom-4 right-4 z-[79] btn btn-primary btn-sm shadow-lg",children:"Awaiting your input ↑"}),s.jsx(wd,{promptSession:r,isSubmitting:o,error:a,onSubmit:i,onCancel:c})]}):null}function rS(){const e=l.useMemo(()=>({sendCommand:Cr,sendData:zo,sendPtyInput:qm}),[]);return s.jsx(Op,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(ah,{client:ZN,children:s.jsx(eS,{children:s.jsx(RN,{children:s.jsx(ih,{value:e,children:s.jsxs(uh,{sendDaemonCommand:Cr,children:[s.jsx(sS,{}),s.jsxs(zN,{children:[s.jsx(tS,{}),s.jsxs(zp,{children:[s.jsx(ss,{path:"/dashboard",element:s.jsx(Pk,{})}),s.jsx(ss,{path:"/machine",element:s.jsx(Uc,{})}),s.jsx(ss,{path:"/machines/:id",element:s.jsx(H1,{})}),s.jsx(ss,{path:"/machines",element:s.jsx(Uc,{})}),s.jsx(ss,{path:"/about",element:s.jsx(UN,{})}),s.jsx(ss,{path:"/settings",element:s.jsx(VN,{})}),s.jsx(ss,{path:"/mesh",element:s.jsx(NN,{children:s.jsx(jN,{})})}),s.jsx(ss,{path:"*",element:s.jsx(bo,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}Fb({connectionManager:Wt});Hp(document.getElementById("root")).render(s.jsx(rS,{}));