@adhdev/daemon-standalone 0.9.82-rc.32 → 0.9.82-rc.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-
|
|
2
|
-
var om=Object.defineProperty;var im=(e,t,r)=>t in e?om(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ze=(e,t,r)=>im(e,typeof t!="symbol"?t+"":t,r);import{r as i,j as s,M as Io,a as lm,b as cm,c as dm,R as Nt,d as Tr,t as um,e as mm,u as As,D as pm,f as eo,g as to,i as hm,h as fm,C as xm,B as bm,k as gm,l as ym,H as ki,P as Si,m as vm,n as wm,o as To,p as jm,q as km,s as Sm,v as Nm,w as rs,N as so,x as Cm}from"./vendor-CgiI0UIA.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 l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&n(l)}).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 Im(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 Hs=Im();function Ni(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 Tm(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Ci(e){return Array.isArray(e)?[...e]:[]}function lc(e,t){if(!e)return t??null;const r=Object.prototype.hasOwnProperty.call(e,"messages"),n=Object.prototype.hasOwnProperty.call(e,"activeModal");return t?{...t,...e,messages:r?Ci(e.messages):t.messages,activeModal:n?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...r?{messages:Ci(e.messages)}:{},...n?{activeModal:e.activeModal??null}:{}}}function br(e,t){const r=Tm(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:lc(e.activeChat,t==null?void 0:t.activeChat),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 cc(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(l=>l.id===a.id);return o?br(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 Ii(e){return!!e&&typeof e=="object"&&"text"in e}function Mo(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:Ii(o)?String(o.text||""):"").join(r):Ii(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Us(e){return Mo(e,{normalizeWhitespace:!0})}const dc=i.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}),uc=i.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Ti(e){var r,n;let t=0;return e.activeChat!==void 0&&(t+=4),(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 mc(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,l=t.versionMismatch===!0||e.versionMismatch===!0,c=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,d=t.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),o&&(n.serverVersion=o),d&&(n.versionUpdateReason=d),a&&o&&a===o?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((t.versionMismatch===!0||l&&a&&o&&a!==o)&&(n.versionMismatch=!0),c&&(n.versionUpdateRequired=!0),n)}function Mm(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 na(e){if(!e||typeof e!="object")return"";const t=e,r=Mm(Us(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 Am(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=na(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:na(e[0]),last:na(e[e.length-1])}}function ro(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function no(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(ro(e)&&ro(t)){const l=e.messages;Array.isArray(l)&&l===t.messages&&r.add(l)}if(Array.isArray(e)&&Array.isArray(t)){const l=Math.min(e.length,t.length);for(let c=0;c<l;c+=1)no(e[c],t[c],r);return}const n=e,a=t,o=new Set([...Object.keys(n),...Object.keys(a)]);for(const l of o)l!=="messages"&&no(n[l],a[l],r)}function vr(e,t){return Array.isArray(e)?e.map(r=>vr(r,t)):!e||typeof e!="object"?e:ro(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?Am(a,t):vr(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,vr(n,t)]))}function _m(e,t){try{const r=new WeakSet;return no(e,t,r),JSON.stringify(vr(e,r))===JSON.stringify(vr(t,r))}catch{return!1}}function ao(e,t,r){return _m(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function pc(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function Lm(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function Mi(e,t,r,n){var c;const a=(c=t.chats)!=null&&c.length?t.chats:e.chats,o=cc(e.childSessions,t.childSessions,{preserveMissing:n}),l=lc(t.activeChat,e.activeChat);return mc(e,t,{...e,...t,chats:a,childSessions:o,activeChat:l,_lastUpdate:r})}function Rm(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=cc(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((o=e.chats)!=null&&o.length)&&(n.chats=t.chats);for(const l of["title","workspace","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion","versionUpdateReason","versionUpdateRequired","updateCommand","updatePolicy","updateChannel","releaseChannel"])Lm(n,t,l);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function Pm(e,t,r,n){const a=Rm(e,t,n),o=Object.keys(a).length>0?mc(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return ao(e,o,r)}function Dm(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 l=pc(o);l&&r.add(l),l&&o.type!=="adhdev-daemon"&&n.add(l),l&&o.type==="adhdev-daemon"&&o._sessionListAuthoritative&&a.add(l)}return{incomingIds:t,incomingDaemonIds:r,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:a}}function Em(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 $m(e,t,r,n,a){return e.transport?r.has(t)&&!n.has(t)?!0:a.has(t):!1}function Bm(e,t,r){var u,h;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(x=>({...x,_lastUpdate:n}));const o=new Map;for(const x of t)o.set(x.id,x);const{incomingIds:l,incomingDaemonIds:c,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:m}=Dm(e);for(const x of e){const S=o.get(x.id);if(!S){o.set(x.id,{...x,_lastUpdate:n});continue}const b=Ti(x),p=Ti(S),g=pc(x),v=!a.has(g);if(b>p){const I=Mi(S,x,n,v);o.set(x.id,ao(S,I,n));continue}if(b<p){o.set(x.id,Pm(S,x,n,v));continue}const f=x.timestamp||n,T=S._lastUpdate||S.timestamp||0;if(f>=T){const I=Mi(S,x,n,v);o.set(x.id,ao(S,I,n));continue}(u=x.chats)!=null&&u.length&&!((h=S.chats)!=null&&h.length)&&o.set(x.id,{...S,chats:x.chats})}for(const[x,S]of o){const b=S.daemonId||x.split(":")[0];if(!c.has(b))continue;if(a.has(b)&&m.has(b)&&!l.has(x)){o.delete(x);continue}const p=n-(S._lastUpdate||S.timestamp||0);Em(S,b,p,l,a,d)&&o.delete(x)}for(const[x,S]of o){const b=S.daemonId||x.split(":")[0];if($m(S,b,c,d,o))continue;n-(S._lastUpdate||S.timestamp||0)>3e5&&S.status!=="online"&&o.delete(x)}return Array.from(o.values())}function Om(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 Fm({children:e,connectionOverrides:t}){const[r,n]=i.useState([]),[a,o]=i.useState(!1),[l,c]=i.useState([]),[d,m]=i.useState(void 0),u=i.useRef(r);i.useEffect(()=>{u.current=r},[r]);const h=i.useCallback((v,f)=>{n(T=>{let I=!1;const k=T.map(A=>A.id!==v||A.chats===f?A:(I=!0,{...A,chats:f}));return I?k:T})},[]),x=i.useCallback((v,f)=>{n(T=>{const I=T.length===0?v:Bm(v,T,f),k=!Om(T,I);return k&&Hs.record({kind:"dashboard.entries_applied",payload:{incoming:Ni(v),next:Ni(I)}}),k?I:T})},[]),S=i.useCallback(()=>o(!0),[]),b=i.useMemo(()=>({injectEntries:x,markLoaded:S,getIdes:()=>u.current}),[x,S]),p=t,g=i.useMemo(()=>({ides:r,updateRouteChats:h,initialLoaded:a,toasts:l,setToasts:c,wsStatus:(p==null?void 0:p.wsStatus)??"connected",isConnected:(p==null?void 0:p.isConnected)??!0,connectionStates:(p==null?void 0:p.connectionStates)??{},connectionTransports:(p==null?void 0:p.connectionTransports)??{},showReconnected:(p==null?void 0:p.showReconnected)??!1,retryConnection:p==null?void 0:p.retryConnection,retryServerConnection:p==null?void 0:p.retryServerConnection,connectionLoginUrl:p==null?void 0:p.connectionLoginUrl,isP2PActive:(p==null?void 0:p.isP2PActive)??!1,p2pStates:(p==null?void 0:p.p2pStates)??{},userRole:p==null?void 0:p.userRole,connectionRetryStatuses:p==null?void 0:p.connectionRetryStatuses,userName:d,setUserName:m}),[r,h,a,l,p==null?void 0:p.wsStatus,p==null?void 0:p.isConnected,p==null?void 0:p.connectionStates,p==null?void 0:p.connectionTransports,p==null?void 0:p.showReconnected,p==null?void 0:p.retryConnection,p==null?void 0:p.retryServerConnection,p==null?void 0:p.connectionLoginUrl,p==null?void 0:p.isP2PActive,p==null?void 0:p.p2pStates,p==null?void 0:p.userRole,p==null?void 0:p.connectionRetryStatuses,d]);return s.jsx(uc.Provider,{value:b,children:s.jsx(dc.Provider,{value:g,children:e})})}function cs(){return i.useContext(dc)}function Mr(){return i.useContext(uc)}function hc(e){const{baseUrl:t,getToken:r,onUnauthorized:n}=e;function a(c){return c.startsWith("http")?c:`${t}${c.startsWith("/")?"":"/"}${c}`}function o(c){const d=r==null?void 0:r(),m=a(c),u=c.startsWith("http")?new URL(m):new URL(m,typeof window<"u"?window.location.origin:"http://localhost");return d&&u.searchParams.set("token",d),!c.startsWith("http")&&!t?`${u.pathname}${u.search}${u.hash}`:u.toString()}async function l(c,d={}){const m={"Content-Type":"application/json",...d.headers||{}},u=r==null?void 0:r();u&&(m.Authorization=`Bearer ${u}`);const h=a(c),x=new AbortController,S=setTimeout(()=>x.abort(),15e3);try{const b=await fetch(h,{...d,headers:m,signal:x.signal});if(b.status===401)throw n==null||n(),new Error("Unauthorized");if(!b.ok){const p=await b.json().catch(()=>({error:b.statusText}));throw new Error(p.error||`API Error: ${b.status}`)}return b.json()}finally{clearTimeout(S)}}return{getDaemons:()=>l("/api/v1/daemons"),getDaemonStatus:c=>l(`/api/v1/daemons/${c}/status`),sendCommand:(c,d,m={})=>l(`/api/v1/daemons/${c}/command`,{method:"POST",body:JSON.stringify({type:d,payload:m})}),execTerminal:(c,d,m)=>l(`/api/v1/daemons/${c}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:m})}),sendAgentMessage:(c,d,m)=>l(`/api/v1/shortcuts/${c}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:m})}),getAgentStatus:c=>l(`/api/v1/shortcuts/${c}/status`),approveAgent:(c,d,m)=>l(`/api/v1/shortcuts/${c}/approve`,{method:"POST",body:JSON.stringify({agentType:d,action:m?"approve":"reject"})}),getMuxState:c=>l(`/api/v1/mux/${encodeURIComponent(c)}/state`),getMuxSocketInfo:c=>l(`/api/v1/mux/${encodeURIComponent(c)}/socket-info`),controlMux:(c,d,m={})=>l(`/api/v1/mux/${encodeURIComponent(c)}/control`,{method:"POST",body:JSON.stringify({type:d,payload:m})}),getMuxEventsUrl:c=>o(`/api/v1/mux/${encodeURIComponent(c)}/events`),getRuntimeEventsUrl:c=>o(`/api/v1/runtime/${encodeURIComponent(c)}/events`),request:l}}const Wm=hc({baseUrl:"http://localhost:3847"}),Km=i.createContext(Wm);function Hm({client:e,children:t}){return s.jsx(Km.Provider,{value:e,children:t})}const Um={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},fc=i.createContext(Um);function zm({value:e,children:t}){return s.jsx(fc.Provider,{value:e,children:t})}function jt(){return i.useContext(fc)}function Vm(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 Gm(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function qm(e){return e?Vm([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Gm(e.content)]):""}const We={size:18};function xc({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function Ao({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polyline",{points:"15 18 9 12 15 6"})})}function is({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),s.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),s.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),s.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function bc({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"9",cy:"7",r:"4"}),s.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),s.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Ym({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function Xm({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function gc({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),s.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),s.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),s.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function Jm({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),s.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),s.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),s.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),s.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function Kn({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function yc({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),s.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function Qm({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function es({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function _t({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function _o({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),s.jsx("polyline",{points:"14 2 14 8 20 8"}),s.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),s.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Zm({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"11",cy:"11",r:"8"}),s.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function Ns({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function Rr({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function Ar({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),s.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),s.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function zs({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M12 22v-5"}),s.jsx("path",{d:"M9 8V2"}),s.jsx("path",{d:"M15 8V2"}),s.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function as({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"5",r:"2"}),s.jsx("circle",{cx:"5",cy:"19",r:"2"}),s.jsx("circle",{cx:"19",cy:"19",r:"2"}),s.jsx("line",{x1:"12",y1:"7",x2:"5",y2:"17"}),s.jsx("line",{x1:"12",y1:"7",x2:"19",y2:"17"}),s.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"19"})]})}function ep({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"12 2 2 7 12 12 22 7 12 2"}),s.jsx("polyline",{points:"2 12 12 17 22 12"}),s.jsx("polyline",{points:"2 17 12 22 22 17"})]})}function vc({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Lo({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),s.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),s.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function wc({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function tp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),s.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),s.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function Ro({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"4 17 10 11 4 5"}),s.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function sp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Po({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function jc({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function wt({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function rp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),s.jsx("path",{d:"M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),s.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),s.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function np({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),s.jsx("path",{d:"M12 2v6"}),s.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function ap({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function op({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),s.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function Hn({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),s.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function ip({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"5"}),s.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),s.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),s.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),s.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),s.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),s.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),s.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),s.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function lp({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function cp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function dp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),s.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function up({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function mp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),s.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]})}function pp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M9.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M19.35 6.07A16.03 16.03 0 0 0 15 4a.84.84 0 0 0-.46.33 11 11 0 0 0-.74 1.5 15.68 15.68 0 0 0-3.6 0 11.23 11.23 0 0 0-.74-1.5A.84.84 0 0 0 9 4a16.03 16.03 0 0 0-4.35 2.07A16.8 16.8 0 0 0 2 15a16.22 16.22 0 0 0 4 3c.12.08.27.06.37-.04a11.14 11.14 0 0 0 1.2-1.92.35.35 0 0 0-.18-.46 10.4 10.4 0 0 1-1.63-.78.36.36 0 0 1 .03-.6 6.8 6.8 0 0 0 .32-.24.36.36 0 0 1 .37-.04c2.2.98 4.6.98 6.8 0a.36.36 0 0 1 .37.04c.1.08.21.16.32.24a.36.36 0 0 1 .03.6 10.4 10.4 0 0 1-1.63.78.35.35 0 0 0-.18.46c.39.67.8 1.3 1.2 1.92a.37.37 0 0 0 .37.04 16.22 16.22 0 0 0 4-3 16.8 16.8 0 0 0-2.65-8.93z"})]})}function hp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),s.jsx("path",{d:"M13 2h9v9"}),s.jsx("path",{d:"M22 2L13 11"})]})}function fp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"9 14 4 9 9 4"}),s.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function xp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),s.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),s.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),s.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),s.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),s.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),s.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),s.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),s.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),s.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function bp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),s.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function gp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),s.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}const Do="adhdev_chat_activity_visible",Ai=new Set(["hidden","debug","internal"]),_i=new Set(["visible","user","chat"]),yp=new Set(["debug","trace","internal"]),vp=new Set(["tool_call","terminal_command","runtime_activity"]),wp=new Set(["runtime_status","provider_chrome","control"]),jp=new Set(["thought","tool","terminal"]);function kc(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Ps(e){return typeof e=="string"?e.trim().toLowerCase():""}function aa(e,t,r){return e[r]??(t==null?void 0:t[r])}function Li(e,t,r){const n=e;return r.some(a=>n[a]===!0||(t==null?void 0:t[a])===!0)}function kp(e,t){const r=Ps(e.kind);return r||(t==="tool"?"tool":"standard")}function oa(e,t,r){const n=kc(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 Sp(e){const t=e.content;return Array.isArray(t)&&t.some(r=>!!r&&typeof r=="object"&&r.type!=="text")}function Eo(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=kc(e),r=Ps(e.role),n=kp(e,r),a=Ps(aa(e,t,"visibility")),o=Ps(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??a),l=Ps(aa(e,t,"audience")),c=Ps(aa(e,t,"source")),d=Ai.has(a)||Ai.has(o)||yp.has(l)||Li(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),m=_i.has(a)||_i.has(o)||l==="chat"||Li(e,t,["userFacing"]),u=jp.has(n)||vp.has(c);if(d)return{surface:u?"activity":"internal",isUserFacing:!1,isActivityFacing:u,isInternal:!u,role:r,kind:n,label:oa(e,n,c)};if(m)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:oa(e,n,c)};if((r==="system"||n==="system")&&Sp(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:"Chat"};if(wp.has(c)||r==="system"||n==="system")return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:r,kind:n,label:"Internal"};if(u)return{surface:"activity",isUserFacing:!1,isActivityFacing:!0,isInternal:!1,role:r,kind:n,label:oa(e,n,c)};const h=(r==="user"||r==="human"||r==="assistant")&&(n==="standard"||n==="");return{surface:h?"chat":"internal",isUserFacing:h,isActivityFacing:!1,isInternal:!h,role:r,kind:n,label:h?"Chat":"Internal"}}function Np(e){return(Array.isArray(e)?e:[]).filter(t=>Eo(t).isUserFacing)}function Sc(e){return(Array.isArray(e)?e:[]).filter(t=>Eo(t).isActivityFacing)}function Cp(e,t,r){return!r||t.length===0?e:[...e,...t].sort((n,a)=>{const o=Number(n.receivedAt??n.timestamp??0)||0,l=Number(a.receivedAt??a.timestamp??0)||0;if(o!==l)return o-l;const c=Number(n.index??0)||0,d=Number(a.index??0)||0;return c-d})}function Ri(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(Do))==="1"}catch{return!1}}function Ip(e,t=typeof localStorage<"u"?localStorage:void 0){try{t==null||t.setItem(Do,e?"1":"0")}catch{}}const Nc=[lm,{singleTilde:!1}],Cc=[Nc,cm,dm],Tp=[Nc],$o=200,Mp=80,Pi=650,rr=new Map;function Cn(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function Ap(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}:${qm(n)}`}function _p(e,t,r,n){return e||!t?!1:Cn(r,n)}function Lp({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=Mp,bottomThresholdPx:a=$o}){const o=Math.max(0,Number(e)||0),l=Math.max(0,Number(t)||0),c=Math.max(0,Number(r)||0);return Math.max(0,l-c)<=0?{showTop:!1,showBottom:!1}:{showTop:o>n,showBottom:Math.max(0,l-o-c)>a}}function Rp(e){return Lp({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function gr(e,t=$o){return!!e&&e.fromBottom>=t}function Pp(e,t){return Cn(e,t)?!gr(e):!0}function Dp({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function Ep({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function ia(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function Ic(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function $p(e,t,r){return Number(e.receivedAt||r[In(e,t)]||0)||0}function Tc(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Bp(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function nr(e,t){if(!e)return t;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||t}catch{return e.split(/[\\/]/).filter(Boolean).pop()||t}}function la(e){if(typeof e.uri=="string"&&e.uri)return e.uri;if(typeof e.data=="string"&&e.data&&typeof e.mimeType=="string"&&e.mimeType)return`data:${e.mimeType};base64,${e.data}`}function qr(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 Di(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):Tc(e)?s.jsx(Io,{remarkPlugins:Cc,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function ar({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:Di(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=la(r),o=r.alt||r.description||nr(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:qr("Image",o,r.mimeType)},`image-fallback-${n}`)}if(r.type==="audio"){const a=la(r);return a?s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("audio",{controls:!0,src:a,className:"max-w-full"}),r.transcript?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:r.transcript}):null]},`audio-${n}`):s.jsx("div",{children:qr("Audio",nr(r.uri,"audio"),r.transcript||r.mimeType)},`audio-fallback-${n}`)}if(r.type==="video"){const a=la(r),o=r.title||r.name||r.alt||nr(r.uri,"video"),l=[r.transcript,r.description,r.mimeType].filter(Boolean).join(`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-D46M5EWH.js","assets/vendor-CgiI0UIA.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
var im=Object.defineProperty;var lm=(e,t,r)=>t in e?im(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ze=(e,t,r)=>lm(e,typeof t!="symbol"?t+"":t,r);import{r as i,j as s,M as Io,a as cm,b as dm,c as um,R as Nt,d as Tr,t as mm,e as pm,u as As,D as hm,f as eo,g as to,i as fm,h as xm,C as bm,B as gm,k as ym,l as vm,H as ki,P as Si,m as wm,n as jm,o as To,p as km,q as Sm,s as Nm,v as Cm,w as rs,N as so,x as Im}from"./vendor-CgiI0UIA.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 l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&n(l)}).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 Tm(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 Hs=Tm();function Ni(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 Mm(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Ci(e){return Array.isArray(e)?[...e]:[]}function cc(e,t){if(!e)return t??null;const r=Object.prototype.hasOwnProperty.call(e,"messages"),n=Object.prototype.hasOwnProperty.call(e,"activeModal");return t?{...t,...e,messages:r?Ci(e.messages):t.messages,activeModal:n?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...r?{messages:Ci(e.messages)}:{},...n?{activeModal:e.activeModal??null}:{}}}function br(e,t){const r=Mm(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:cc(e.activeChat,t==null?void 0:t.activeChat),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 dc(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(l=>l.id===a.id);return o?br(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 Ii(e){return!!e&&typeof e=="object"&&"text"in e}function Mo(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:Ii(o)?String(o.text||""):"").join(r):Ii(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Us(e){return Mo(e,{normalizeWhitespace:!0})}const uc=i.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}),mc=i.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Ti(e){var r,n;let t=0;return e.activeChat!==void 0&&(t+=4),(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 pc(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,l=t.versionMismatch===!0||e.versionMismatch===!0,c=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,d=t.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),o&&(n.serverVersion=o),d&&(n.versionUpdateReason=d),a&&o&&a===o?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((t.versionMismatch===!0||l&&a&&o&&a!==o)&&(n.versionMismatch=!0),c&&(n.versionUpdateRequired=!0),n)}function Am(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 na(e){if(!e||typeof e!="object")return"";const t=e,r=Am(Us(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 _m(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=na(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:na(e[0]),last:na(e[e.length-1])}}function ro(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function no(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(ro(e)&&ro(t)){const l=e.messages;Array.isArray(l)&&l===t.messages&&r.add(l)}if(Array.isArray(e)&&Array.isArray(t)){const l=Math.min(e.length,t.length);for(let c=0;c<l;c+=1)no(e[c],t[c],r);return}const n=e,a=t,o=new Set([...Object.keys(n),...Object.keys(a)]);for(const l of o)l!=="messages"&&no(n[l],a[l],r)}function vr(e,t){return Array.isArray(e)?e.map(r=>vr(r,t)):!e||typeof e!="object"?e:ro(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?_m(a,t):vr(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,vr(n,t)]))}function Lm(e,t){try{const r=new WeakSet;return no(e,t,r),JSON.stringify(vr(e,r))===JSON.stringify(vr(t,r))}catch{return!1}}function ao(e,t,r){return Lm(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function hc(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function Rm(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function Mi(e,t,r,n){var c;const a=(c=t.chats)!=null&&c.length?t.chats:e.chats,o=dc(e.childSessions,t.childSessions,{preserveMissing:n}),l=cc(t.activeChat,e.activeChat);return pc(e,t,{...e,...t,chats:a,childSessions:o,activeChat:l,_lastUpdate:r})}function Pm(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=dc(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((o=e.chats)!=null&&o.length)&&(n.chats=t.chats);for(const l of["title","workspace","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion","versionUpdateReason","versionUpdateRequired","updateCommand","updatePolicy","updateChannel","releaseChannel"])Rm(n,t,l);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function Dm(e,t,r,n){const a=Pm(e,t,n),o=Object.keys(a).length>0?pc(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return ao(e,o,r)}function Em(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 l=hc(o);l&&r.add(l),l&&o.type!=="adhdev-daemon"&&n.add(l),l&&o.type==="adhdev-daemon"&&o._sessionListAuthoritative&&a.add(l)}return{incomingIds:t,incomingDaemonIds:r,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:a}}function $m(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 Bm(e,t,r,n,a){return e.transport?r.has(t)&&!n.has(t)?!0:a.has(t):!1}function Om(e,t,r){var u,h;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(x=>({...x,_lastUpdate:n}));const o=new Map;for(const x of t)o.set(x.id,x);const{incomingIds:l,incomingDaemonIds:c,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:m}=Em(e);for(const x of e){const S=o.get(x.id);if(!S){o.set(x.id,{...x,_lastUpdate:n});continue}const b=Ti(x),p=Ti(S),g=hc(x),v=!a.has(g);if(b>p){const T=Mi(S,x,n,v);o.set(x.id,ao(S,T,n));continue}if(b<p){o.set(x.id,Dm(S,x,n,v));continue}const f=x.timestamp||n,C=S._lastUpdate||S.timestamp||0;if(f>=C){const T=Mi(S,x,n,v);o.set(x.id,ao(S,T,n));continue}(u=x.chats)!=null&&u.length&&!((h=S.chats)!=null&&h.length)&&o.set(x.id,{...S,chats:x.chats})}for(const[x,S]of o){const b=S.daemonId||x.split(":")[0];if(!c.has(b))continue;if(a.has(b)&&m.has(b)&&!l.has(x)){o.delete(x);continue}const p=n-(S._lastUpdate||S.timestamp||0);$m(S,b,p,l,a,d)&&o.delete(x)}for(const[x,S]of o){const b=S.daemonId||x.split(":")[0];if(Bm(S,b,c,d,o))continue;n-(S._lastUpdate||S.timestamp||0)>3e5&&S.status!=="online"&&o.delete(x)}return Array.from(o.values())}function Fm(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 Wm({children:e,connectionOverrides:t}){const[r,n]=i.useState([]),[a,o]=i.useState(!1),[l,c]=i.useState([]),[d,m]=i.useState(void 0),u=i.useRef(r);i.useEffect(()=>{u.current=r},[r]);const h=i.useCallback((v,f)=>{n(C=>{let T=!1;const k=C.map(A=>A.id!==v||A.chats===f?A:(T=!0,{...A,chats:f}));return T?k:C})},[]),x=i.useCallback((v,f)=>{n(C=>{const T=C.length===0?v:Om(v,C,f),k=!Fm(C,T);return k&&Hs.record({kind:"dashboard.entries_applied",payload:{incoming:Ni(v),next:Ni(T)}}),k?T:C})},[]),S=i.useCallback(()=>o(!0),[]),b=i.useMemo(()=>({injectEntries:x,markLoaded:S,getIdes:()=>u.current}),[x,S]),p=t,g=i.useMemo(()=>({ides:r,updateRouteChats:h,initialLoaded:a,toasts:l,setToasts:c,wsStatus:(p==null?void 0:p.wsStatus)??"connected",isConnected:(p==null?void 0:p.isConnected)??!0,connectionStates:(p==null?void 0:p.connectionStates)??{},connectionTransports:(p==null?void 0:p.connectionTransports)??{},showReconnected:(p==null?void 0:p.showReconnected)??!1,retryConnection:p==null?void 0:p.retryConnection,retryServerConnection:p==null?void 0:p.retryServerConnection,connectionLoginUrl:p==null?void 0:p.connectionLoginUrl,isP2PActive:(p==null?void 0:p.isP2PActive)??!1,p2pStates:(p==null?void 0:p.p2pStates)??{},userRole:p==null?void 0:p.userRole,connectionRetryStatuses:p==null?void 0:p.connectionRetryStatuses,userName:d,setUserName:m}),[r,h,a,l,p==null?void 0:p.wsStatus,p==null?void 0:p.isConnected,p==null?void 0:p.connectionStates,p==null?void 0:p.connectionTransports,p==null?void 0:p.showReconnected,p==null?void 0:p.retryConnection,p==null?void 0:p.retryServerConnection,p==null?void 0:p.connectionLoginUrl,p==null?void 0:p.isP2PActive,p==null?void 0:p.p2pStates,p==null?void 0:p.userRole,p==null?void 0:p.connectionRetryStatuses,d]);return s.jsx(mc.Provider,{value:b,children:s.jsx(uc.Provider,{value:g,children:e})})}function cs(){return i.useContext(uc)}function Mr(){return i.useContext(mc)}function fc(e){const{baseUrl:t,getToken:r,onUnauthorized:n}=e;function a(c){return c.startsWith("http")?c:`${t}${c.startsWith("/")?"":"/"}${c}`}function o(c){const d=r==null?void 0:r(),m=a(c),u=c.startsWith("http")?new URL(m):new URL(m,typeof window<"u"?window.location.origin:"http://localhost");return d&&u.searchParams.set("token",d),!c.startsWith("http")&&!t?`${u.pathname}${u.search}${u.hash}`:u.toString()}async function l(c,d={}){const m={"Content-Type":"application/json",...d.headers||{}},u=r==null?void 0:r();u&&(m.Authorization=`Bearer ${u}`);const h=a(c),x=new AbortController,S=setTimeout(()=>x.abort(),15e3);try{const b=await fetch(h,{...d,headers:m,signal:x.signal});if(b.status===401)throw n==null||n(),new Error("Unauthorized");if(!b.ok){const p=await b.json().catch(()=>({error:b.statusText}));throw new Error(p.error||`API Error: ${b.status}`)}return b.json()}finally{clearTimeout(S)}}return{getDaemons:()=>l("/api/v1/daemons"),getDaemonStatus:c=>l(`/api/v1/daemons/${c}/status`),sendCommand:(c,d,m={})=>l(`/api/v1/daemons/${c}/command`,{method:"POST",body:JSON.stringify({type:d,payload:m})}),execTerminal:(c,d,m)=>l(`/api/v1/daemons/${c}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:m})}),sendAgentMessage:(c,d,m)=>l(`/api/v1/shortcuts/${c}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:m})}),getAgentStatus:c=>l(`/api/v1/shortcuts/${c}/status`),approveAgent:(c,d,m)=>l(`/api/v1/shortcuts/${c}/approve`,{method:"POST",body:JSON.stringify({agentType:d,action:m?"approve":"reject"})}),getMuxState:c=>l(`/api/v1/mux/${encodeURIComponent(c)}/state`),getMuxSocketInfo:c=>l(`/api/v1/mux/${encodeURIComponent(c)}/socket-info`),controlMux:(c,d,m={})=>l(`/api/v1/mux/${encodeURIComponent(c)}/control`,{method:"POST",body:JSON.stringify({type:d,payload:m})}),getMuxEventsUrl:c=>o(`/api/v1/mux/${encodeURIComponent(c)}/events`),getRuntimeEventsUrl:c=>o(`/api/v1/runtime/${encodeURIComponent(c)}/events`),request:l}}const Km=fc({baseUrl:"http://localhost:3847"}),Hm=i.createContext(Km);function Um({client:e,children:t}){return s.jsx(Hm.Provider,{value:e,children:t})}const zm={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},xc=i.createContext(zm);function Vm({value:e,children:t}){return s.jsx(xc.Provider,{value:e,children:t})}function jt(){return i.useContext(xc)}function Gm(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 qm(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Ym(e){return e?Gm([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),qm(e.content)]):""}const We={size:18};function bc({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function Ao({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polyline",{points:"15 18 9 12 15 6"})})}function is({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),s.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),s.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),s.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function gc({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"9",cy:"7",r:"4"}),s.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),s.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Xm({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function Jm({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function yc({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),s.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),s.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),s.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function Qm({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),s.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),s.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),s.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),s.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function Kn({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function vc({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),s.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function Zm({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function es({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function _t({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function _o({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),s.jsx("polyline",{points:"14 2 14 8 20 8"}),s.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),s.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function ep({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"11",cy:"11",r:"8"}),s.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function Ns({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function Rr({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function Ar({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),s.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),s.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function zs({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M12 22v-5"}),s.jsx("path",{d:"M9 8V2"}),s.jsx("path",{d:"M15 8V2"}),s.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function as({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"5",r:"2"}),s.jsx("circle",{cx:"5",cy:"19",r:"2"}),s.jsx("circle",{cx:"19",cy:"19",r:"2"}),s.jsx("line",{x1:"12",y1:"7",x2:"5",y2:"17"}),s.jsx("line",{x1:"12",y1:"7",x2:"19",y2:"17"}),s.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"19"})]})}function tp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"12 2 2 7 12 12 22 7 12 2"}),s.jsx("polyline",{points:"2 12 12 17 22 12"}),s.jsx("polyline",{points:"2 17 12 22 22 17"})]})}function wc({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Lo({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),s.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),s.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function jc({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function sp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),s.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),s.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function Ro({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"4 17 10 11 4 5"}),s.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function rp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Po({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function kc({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function wt({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function np({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),s.jsx("path",{d:"M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),s.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),s.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function ap({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),s.jsx("path",{d:"M12 2v6"}),s.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function op({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function ip({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),s.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function Hn({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),s.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function lp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"5"}),s.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),s.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),s.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),s.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),s.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),s.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),s.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),s.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function cp({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function dp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function up({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),s.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function mp({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function pp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),s.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]})}function hp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M9.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M19.35 6.07A16.03 16.03 0 0 0 15 4a.84.84 0 0 0-.46.33 11 11 0 0 0-.74 1.5 15.68 15.68 0 0 0-3.6 0 11.23 11.23 0 0 0-.74-1.5A.84.84 0 0 0 9 4a16.03 16.03 0 0 0-4.35 2.07A16.8 16.8 0 0 0 2 15a16.22 16.22 0 0 0 4 3c.12.08.27.06.37-.04a11.14 11.14 0 0 0 1.2-1.92.35.35 0 0 0-.18-.46 10.4 10.4 0 0 1-1.63-.78.36.36 0 0 1 .03-.6 6.8 6.8 0 0 0 .32-.24.36.36 0 0 1 .37-.04c2.2.98 4.6.98 6.8 0a.36.36 0 0 1 .37.04c.1.08.21.16.32.24a.36.36 0 0 1 .03.6 10.4 10.4 0 0 1-1.63.78.35.35 0 0 0-.18.46c.39.67.8 1.3 1.2 1.92a.37.37 0 0 0 .37.04 16.22 16.22 0 0 0 4-3 16.8 16.8 0 0 0-2.65-8.93z"})]})}function fp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),s.jsx("path",{d:"M13 2h9v9"}),s.jsx("path",{d:"M22 2L13 11"})]})}function xp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"9 14 4 9 9 4"}),s.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function bp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),s.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),s.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),s.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),s.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),s.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),s.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),s.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),s.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),s.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function gp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),s.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function yp({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),s.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}const Do="adhdev_chat_activity_visible",Ai=new Set(["hidden","debug","internal"]),_i=new Set(["visible","user","chat"]),vp=new Set(["debug","trace","internal"]),wp=new Set(["tool_call","terminal_command","runtime_activity"]),jp=new Set(["runtime_status","provider_chrome","control"]),kp=new Set(["thought","tool","terminal"]);function Sc(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Ps(e){return typeof e=="string"?e.trim().toLowerCase():""}function aa(e,t,r){return e[r]??(t==null?void 0:t[r])}function Li(e,t,r){const n=e;return r.some(a=>n[a]===!0||(t==null?void 0:t[a])===!0)}function Sp(e,t){const r=Ps(e.kind);return r||(t==="tool"?"tool":"standard")}function oa(e,t,r){const n=Sc(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 Np(e){const t=e.content;return Array.isArray(t)&&t.some(r=>!!r&&typeof r=="object"&&r.type!=="text")}function Eo(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=Sc(e),r=Ps(e.role),n=Sp(e,r),a=Ps(aa(e,t,"visibility")),o=Ps(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??a),l=Ps(aa(e,t,"audience")),c=Ps(aa(e,t,"source")),d=Ai.has(a)||Ai.has(o)||vp.has(l)||Li(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),m=_i.has(a)||_i.has(o)||l==="chat"||Li(e,t,["userFacing"]),u=kp.has(n)||wp.has(c);if(d)return{surface:u?"activity":"internal",isUserFacing:!1,isActivityFacing:u,isInternal:!u,role:r,kind:n,label:oa(e,n,c)};if(m)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:oa(e,n,c)};if((r==="system"||n==="system")&&Np(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:"Chat"};if(jp.has(c)||r==="system"||n==="system")return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:r,kind:n,label:"Internal"};if(u)return{surface:"activity",isUserFacing:!1,isActivityFacing:!0,isInternal:!1,role:r,kind:n,label:oa(e,n,c)};const h=(r==="user"||r==="human"||r==="assistant")&&(n==="standard"||n==="");return{surface:h?"chat":"internal",isUserFacing:h,isActivityFacing:!1,isInternal:!h,role:r,kind:n,label:h?"Chat":"Internal"}}function Cp(e){return(Array.isArray(e)?e:[]).filter(t=>Eo(t).isUserFacing)}function Nc(e){return(Array.isArray(e)?e:[]).filter(t=>Eo(t).isActivityFacing)}function Ip(e,t,r){return!r||t.length===0?e:[...e,...t].sort((n,a)=>{const o=Number(n.receivedAt??n.timestamp??0)||0,l=Number(a.receivedAt??a.timestamp??0)||0;if(o!==l)return o-l;const c=Number(n.index??0)||0,d=Number(a.index??0)||0;return c-d})}function Ri(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(Do))==="1"}catch{return!1}}function Tp(e,t=typeof localStorage<"u"?localStorage:void 0){try{t==null||t.setItem(Do,e?"1":"0")}catch{}}const Cc=[cm,{singleTilde:!1}],Ic=[Cc,dm,um],Mp=[Cc],$o=200,Ap=80,Pi=650,rr=new Map;function Cn(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function _p(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}:${Ym(n)}`}function Lp(e,t,r,n){return e||!t?!1:Cn(r,n)}function Rp({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=Ap,bottomThresholdPx:a=$o}){const o=Math.max(0,Number(e)||0),l=Math.max(0,Number(t)||0),c=Math.max(0,Number(r)||0);return Math.max(0,l-c)<=0?{showTop:!1,showBottom:!1}:{showTop:o>n,showBottom:Math.max(0,l-o-c)>a}}function Pp(e){return Rp({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function gr(e,t=$o){return!!e&&e.fromBottom>=t}function Dp(e,t){return Cn(e,t)?!gr(e):!0}function Ep({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function $p({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function ia(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function Tc(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Bp(e,t,r){return Number(e.receivedAt||r[In(e,t)]||0)||0}function Mc(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Op(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function nr(e,t){if(!e)return t;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||t}catch{return e.split(/[\\/]/).filter(Boolean).pop()||t}}function la(e){if(typeof e.uri=="string"&&e.uri)return e.uri;if(typeof e.data=="string"&&e.data&&typeof e.mimeType=="string"&&e.mimeType)return`data:${e.mimeType};base64,${e.data}`}function qr(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 Di(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):Mc(e)?s.jsx(Io,{remarkPlugins:Ic,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function ar({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:Di(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=la(r),o=r.alt||r.description||nr(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:qr("Image",o,r.mimeType)},`image-fallback-${n}`)}if(r.type==="audio"){const a=la(r);return a?s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("audio",{controls:!0,src:a,className:"max-w-full"}),r.transcript?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:r.transcript}):null]},`audio-${n}`):s.jsx("div",{children:qr("Audio",nr(r.uri,"audio"),r.transcript||r.mimeType)},`audio-fallback-${n}`)}if(r.type==="video"){const a=la(r),o=r.title||r.name||r.alt||nr(r.uri,"video"),l=[r.transcript,r.description,r.mimeType].filter(Boolean).join(`
|
|
3
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"}):qr("Video",o,l),a&&l?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:l}):null]},`video-${n}`)}if(r.type==="resource_link"){const a=r.title||r.name||nr(r.uri,"resource"),o=[r.description,r.mimeType].filter(Boolean).join(`
|
|
4
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}):qr("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=nr(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}),Di(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 In(e,t){const r=e,n=Mo(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
|
|
6
|
-
`});if(h.isActivityFacing&&u!=="thought"&&u!=="tool"&&u!=="terminal"){const M=h.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:M})]}),S&&x?s.jsx("div",{className:"chat-msg-activity-body",children:s.jsx(ar,{parts:x,renderAsPreformatted:!1})}):s.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:b})]})}if(u==="thought"){const M=typeof((N=t.meta)==null?void 0:N.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":h.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(ap,{size:13}),s.jsx("span",{children:M})]}),s.jsx("div",{className:"chat-msg-body",children:b})]})}if(u==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":h.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"})]}),S&&x?s.jsx("div",{className:"tool-text w-full",children:s.jsx(ar,{parts:x,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:b})]});if(u==="terminal"){const M=(w=t.meta)!=null&&w.isRunning?"⏳":"✅",j=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":h.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:M}),s.jsx("span",{children:j})]}),S&&x?s.jsx("div",{className:"chat-msg-body",children:s.jsx(ar,{parts:x,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:b})]})}if(u==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:S&&x?s.jsx(ar,{parts:x,renderAsPreformatted:!1}):b.slice(0,100)});const p=t.meta,v=(typeof(p==null?void 0:p.renderMode)=="string"?p.renderMode.trim():"")==="preformatted",f=b,T=!1,I=f,k=v,A=!k&&Tc(I),_=["chat-message-row",m?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return s.jsx("div",{className:_,children:(f||S||m)&&s.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${f||S?"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:Ic(r)})]}),(f||S)&&s.jsx("div",{className:"chat-markdown",children:S&&x?s.jsx(ar,{parts:x,renderAsPreformatted:k}):k?s.jsx("pre",{className:"chat-preformatted",children:I}):A?s.jsx(Io,{remarkPlugins:Cc,children:I}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:I})}),T]})})},(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),Wp=i.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:o=!1,isWorking:l=!1,contextKey:c="",receivedAtMap:d={},lastMessageHash:m,showActivityMessages:u=!1,emptyState:h,onLoadMore:x,isLoadingMore:S,hasMoreHistory:b,hiddenLiveCount:p=0,loadError:g,scrollToBottomRequestNonce:v,isVisible:f=!0},T){const I=i.useRef(null),k=i.useRef(null),A=i.useRef(null),_=i.useRef(0),N=i.useRef(""),w=i.useRef(""),D=i.useRef(!1),M=i.useRef(null),j=i.useRef(!1),W=i.useRef(null),H=i.useRef(!1),[$,C]=i.useState(new Set),[y,F]=i.useState({showTop:!1,showBottom:!1}),P=i.useRef(!1),E=i.useRef(!1),G=i.useRef(f),J=i.useRef(f),ye=i.useRef(null);J.current=f;const he=()=>{const re=I.current;return re?re.scrollHeight-re.scrollTop-re.clientHeight<$o:!0},ne=i.useCallback(()=>{const re=I.current,R=re?Rp(re):{showTop:!1,showBottom:!1};F(q=>q.showTop===R.showTop&&q.showBottom===R.showBottom?q:R)},[]),ue=i.useCallback((re="auto")=>{var q;const R=I.current;R&&(R.scrollTo({top:R.scrollHeight,behavior:re}),(q=R.ownerDocument.defaultView)==null||q.requestAnimationFrame(()=>ne()))},[ne]),Se=i.useCallback((re="auto")=>{var q;const R=I.current;R&&(R.scrollTo({top:0,behavior:re}),(q=R.ownerDocument.defaultView)==null||q.requestAnimationFrame(()=>ne()))},[ne]),ve=i.useCallback(()=>{var Ne;const re=I.current,R=(Ne=window.getSelection)==null?void 0:Ne.call(window);if(!re||!R||R.rangeCount===0||R.isCollapsed){H.current=!1;return}const q=R.anchorNode,ce=R.focusNode;H.current=!!(q&&ce&&re.contains(q)&&re.contains(ce))},[]),X=i.useMemo(()=>{const re=Np(t),R=Sc(t);return Cp(re,R,u)},[t,u]),xe=X.length===t.length?m:void 0,fe=Ap(X,xe),we=i.useCallback(()=>{const re=I.current;if(!re||!c||!J.current)return;const R={top:re.scrollTop,fromBottom:Math.max(0,re.scrollHeight-re.scrollTop-re.clientHeight),messageFingerprint:fe};ye.current={contextKey:c,snapshot:R},rr.set(c,R)},[c,fe]),be=i.useCallback((re="auto")=>{M.current!=null&&cancelAnimationFrame(M.current),M.current=requestAnimationFrame(()=>{M.current=null,ue(re)})},[ue]),Ce=i.useCallback(()=>{P.current=!1,j.current=!0,E.current=!0,W.current!=null&&window.clearTimeout(W.current),W.current=window.setTimeout(()=>{j.current=!1,W.current=null},Pi)},[]);i.useEffect(()=>{const re=!D.current,R=w.current!==c;if(w.current=c,re||R){D.current=!0;const ce=c?rr.get(c):null,Ne=!!ce&&Cn(ce,fe);P.current=Ne?gr(ce):!1,j.current=Pp(ce,fe),H.current||(Ne?requestAnimationFrame(()=>{const je=I.current;je&&(ia(je,ce),P.current=gr(ce),ne(),E.current=!0)}):be("auto")),_.current=X.length,N.current=fe;return}X.length>_.current;const q=fe!==N.current;Dp({hasSelection:H.current,userScrolledUp:P.current,hasChatContentChanged:q})&&be("auto"),_.current=X.length,N.current=fe},[fe,c,X.length,be,ne]),i.useEffect(()=>{v&&(Ce(),H.current||be("auto"))},[Ce,be,v]),i.useEffect(()=>{const re=G.current;re&&!f&&we(),J.current=f,G.current=f;const R=c?rr.get(c):null;if(_p(re,f,R,fe)){if(!R)return;P.current=gr(R),j.current=!1,H.current||requestAnimationFrame(()=>{const q=I.current;q&&(ia(q,R),ne())});return}},[f,c,fe,Ce,we,be,ne]),i.useEffect(()=>()=>{const re=ye.current;re&&rr.set(re.contextKey,re.snapshot),M.current!=null&&cancelAnimationFrame(M.current),W.current!=null&&window.clearTimeout(W.current)},[]),i.useEffect(()=>{const re=k.current,R=I.current;if(!re||!R)return;const q=()=>{W.current!=null&&window.clearTimeout(W.current),W.current=window.setTimeout(()=>{j.current=!1,W.current=null},Pi)},ce=new ResizeObserver(()=>{ne();const Ne=j.current;Ep({hasSelection:H.current,userScrolledUp:P.current,contextAutoScrollActive:Ne})&&(be("auto"),Ne&&q())});return ce.observe(re),R!==re&&ce.observe(R),()=>{ce.disconnect(),W.current!=null&&(window.clearTimeout(W.current),W.current=null)}},[be,c,ne]),i.useImperativeHandle(T,()=>({scrollToBottom:(re="smooth")=>{ue(re)}}),[ue]),i.useEffect(()=>{const re=I.current;if(!re)return;let R;const q=()=>{we(),clearTimeout(R),R=setTimeout(()=>{P.current=!he(),ne()},50)};return re.addEventListener("scroll",q,{passive:!0}),()=>{re.removeEventListener("scroll",q),clearTimeout(R)}},[we,ne]),i.useEffect(()=>(document.addEventListener("selectionchange",ve),()=>document.removeEventListener("selectionchange",ve)),[ve]);const ee=i.useRef(0),me=i.useRef(!1);i.useEffect(()=>{const re=I.current;if(!re||!me.current||ee.current===0)return;const R=re.scrollHeight-ee.current;R>0&&(re.scrollTop=R),ne(),we(),ee.current=0,me.current=!1},[X.length,we,ne]),i.useEffect(()=>{if(E.current||!c)return;const re=rr.get(c),R=I.current;if(!(!re||!R)){if(!Cn(re,fe)){ue("auto"),E.current=!0;return}ia(R,re),P.current=gr(re),ne(),E.current=!0}},[c,fe,X.length,ue,ne]);const ie=()=>{const re=I.current;re&&(ee.current=re.scrollHeight),me.current=!0,x==null||x()},pe=()=>{P.current=!0,Se("smooth"),we()},le=()=>{Ce(),ue("smooth"),we()},B=i.useMemo(()=>{const re=X.map((Ne,je)=>({type:"message",data:Ne,index:je,ts:$p(Ne,je,d)}));if(!r||r.length===0)return re;const R=[...r].sort((Ne,je)=>Ne.timestamp-je.timestamp).map((Ne,je)=>({type:"action",data:Ne,index:je,ts:Ne.timestamp})),q=[];let ce=0;for(const Ne of re){for(;ce<R.length&&Ne.ts>0&&R[ce].ts<Ne.ts;)q.push(R[ce++]);q.push(Ne)}for(;ce<R.length;)q.push(R[ce++]);return q},[X,r,d]),z=p>0||!!b,de=p>0?`↑ Show ${Math.min(p,80)} earlier messages${p>80?` (${p} hidden)`:""}`:g?`↻ ${g}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:I,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:k,className:"chat-container-content",children:[S&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),z&&!S&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:ie,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${g&&p===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:de})}),B.length===0&&!z&&(h||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),B.map(re=>{if(re.type==="action"){const Ie=re.data;return s.jsx(Op,{log:Ie},`action-${re.index}`)}const R=re.data,q=re.index,ce=In(R,q),Ne=R.receivedAt||d[ce],je=`${c}-${ce}`,O=$.has(je);return s.jsx(Fp,{message:R,receivedAt:Ne,agentName:n,userName:a,isCliMode:o,isTextExpanded:O,onToggleTextExpanded:()=>C(Ie=>{const Le=new Set(Ie);return O?Le.delete(je):Le.add(je),Le})},`msg-${ce}`)}),l&&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:A})]})}),(y.showTop||y.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[y.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:pe,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),y.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:le,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),Kp=i.memo(Wp,(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),Hp="modulepreload",Up=function(e){return"/"+e},Ei={},zp=function(t,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),c=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));a=Promise.allSettled(r.map(d=>{if(d=Up(d),d in Ei)return;Ei[d]=!0;const m=d.endsWith(".css"),u=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const h=document.createElement("link");if(h.rel=m?"stylesheet":Hp,m||(h.as="script"),h.crossOrigin="",h.href=d,c&&h.setAttribute("nonce",c),document.head.appendChild(h),m)return new Promise((x,S)=>{h.addEventListener("load",x),h.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return a.then(l=>{for(const c of l||[])c.status==="rejected"&&o(c.reason);return t().catch(o)})};let $i=!1;const Mc=i.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:o="measured"},l)=>{const c=i.useRef(null),[d,m]=i.useState(null),u=i.useRef([]),h=i.useRef(!1),x=i.useRef(!1),S=i.useRef(!1),b=i.useRef(!1),p=()=>{const g=c.current;if(g){h.current&&(g.clear(),h.current=!1);for(const v of u.current)g.write(v.data,v.onProcessed);u.current=[],x.current&&(g.fit(),x.current=!1),S.current&&(g.bumpResize(),S.current=!1),b.current&&(g.scrollToTop(),b.current=!1)}};return i.useImperativeHandle(l,()=>({write:(g,v)=>{c.current?c.current.write(g,v):u.current.push({data:g,onProcessed:v})},clear:()=>{c.current?c.current.clear():(u.current=[],h.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(u.current=[],h.current=!0)},resize:(g,v)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(g,v)},fit:()=>{c.current?c.current.fit():x.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():S.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():b.current=!0},getSelection:()=>{var g,v;return((v=(g=c.current)==null?void 0:g.getSelection)==null?void 0:v.call(g))||""},getVisibleText:()=>{var g,v;return((v=(g=c.current)==null?void 0:g.getVisibleText)==null?void 0:v.call(g))||""}}),[]),i.useEffect(()=>{d&&p()},[d]),i.useEffect(()=>{let g=!1;return zp(()=>import("./terminal-CfAvHQvJ.js"),__vite__mapDeps([0,1,2])).then(v=>{$i||($i=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),g||m(()=>v.GhosttyTerminalView)}).catch(v=>{console.error("[CliTerminal] failed to load terminal renderer",v)}),()=>{g=!0}},[]),d?s.jsx(d,{ref:c,onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n,readOnly:a,sizingMode:o,className:"w-full h-full rounded-lg overflow-hidden"}):s.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});Mc.displayName="CliTerminal";function Yr({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 Bi({value:e,max:t,label:r,color:n="#8b5cf6",detail:a,compact:o=!1}){const l=t>0?Math.min(Math.round(e/t*100),100):0,c=l>85?"#ef4444":l>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:[l,"%"]})]}),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:`${l}%`,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:[l,"%"]})]}),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:`${l}%`,background:`linear-gradient(90deg, ${c}, ${c}cc)`}})}),a&&s.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function Vp({cursorPos:e,viewportRef:t,imgRef:r}){var f;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),o=(f=t.current)==null?void 0:f.getBoundingClientRect();if(!o)return null;const l=n.naturalWidth||a.width,c=n.naturalHeight||a.height,d=l/c,m=a.width/a.height;let u,h,x,S;d>m?(u=a.width,h=a.width/d,x=0,S=(a.height-h)/2):(h=a.height,u=a.height*d,x=(a.width-u)/2,S=0);const b=a.left-o.left+x+u*e.nx,p=a.top-o.top+S+h*e.ny,g=Math.max(8,Math.min(o.width-8,b)),v=Math.max(8,Math.min(o.height-8,p));return s.jsxs("div",{style:{position:"absolute",left:g-8,top:v-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 Gp({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:o,imeText:l,setImeText:c,handleImeSubmit:d,isConnActive:m,zoom:u,isMobile:h,mobileFillZoom:x,onZoomOut:S,onZoomReset:b,onZoomIn:p,transportType:g,screenshotUsage:v,lastActionStatus:f}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:T=>T.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(T=>!T),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:l,autoFocus:!0,onTouchStart:T=>T.stopPropagation(),onChange:T=>c(T.target.value),onKeyDown:T=>{d(T)},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(T=>!T),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"})]}),u>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(u*100),"%"]}),g==="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"}),g==="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"}),v&&v.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:v.budgetExhausted?"#ef4444":"#c4b5fd",background:v.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:v.budgetExhausted?"TURN blocked":`TURN ${v.dailyUsedMinutes}/${v.dailyBudgetMinutes}m`}),f&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:f})]})]}),a&&s.jsxs("div",{onTouchStart:T=>T.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",u<=(h?x:1)+.01?h?"FILL":"FIT":`${Math.round(u*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:T=>{T.stopPropagation(),S()},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:T=>{T.stopPropagation(),b()},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:h?"FILL":"FIT"}),s.jsx("button",{onClick:T=>{T.stopPropagation(),p()},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 qp({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 Yp(){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 Oi(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 Pr(e,t){const r=i.useRef(null),n=i.useRef(0);i.useEffect(()=>{if(!Yp())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(([l,c])=>[l,Oi(c)]))}),r.current=t;return}const o=Object.keys({...a,...t}).filter(l=>!Object.is(a[l],t[l]));o.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:o,snapshot:Object.fromEntries(o.map(l=>[l,Oi(t[l])]))}),r.current=t})}function Xp({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:o,zoomRef:l,panXRef:c,panYRef:d,setPanX:m,setPanY:u,setZoom:h,lastWheelTimeRef:x,onAction:S,setLastActionStatus:b,spawnRippleFromNormalized:p,clampPan:g,isMobile:v,mobileFillZoom:f}){const[T,I]=i.useState(null),k=i.useRef(null),A=i.useRef(null),_=i.useRef(null),N=i.useRef(!1),w=i.useRef(null),D=i.useRef(0),M=i.useRef(null),j=i.useRef(1),W=i.useRef({x:0,y:0}),H=i.useRef(!1),$=i.useRef(n),C=i.useRef(S),y=30,F=550,P=18,E=60,G=400,J=12,ye=()=>{if(k.current)return;const ue={nx:.5,ny:.5};k.current=ue,I(ue)};return i.useEffect(()=>{$.current=n,n==="mouse"&&ye()},[n]),i.useEffect(()=>{C.current=S},[S]),i.useEffect(()=>{const ue=e.current;if(!ue)return;const Se=be=>{if(!r.current)return null;const Ce=r.current.getBoundingClientRect();return!Ce.width||!Ce.height?null:{nx:Math.max(0,Math.min(1,(be.clientX-Ce.left)/Ce.width)),ny:Math.max(0,Math.min(1,(be.clientY-Ce.top)/Ce.height))}},ve=(be,Ce)=>{if(!r.current)return{dnx:0,dny:0};const ee=r.current,me=ee.getBoundingClientRect(),ie=ee.naturalWidth||me.width,pe=ee.naturalHeight||me.height,le=ie/pe,B=me.width/me.height;let z,de;return le>B?(z=me.width,de=me.width/le):(de=me.height,z=me.height*le),{dnx:be/z,dny:Ce/de}},X=(be,Ce,ee)=>{if(ee<=1.05)return;const me=-(be-.5)*100,ie=-(Ce-.5)*100,pe=g(me,ie,ee);(Math.abs(pe.x-c.current)>.1||Math.abs(pe.y-d.current)>.1)&&(m(pe.x),u(pe.y),c.current=pe.x,d.current=pe.y)},xe=be=>{const Ce=t.current;if(Ce&&be.target instanceof Node&&Ce.contains(be.target))be.preventDefault();else return;if(be.touches.length===1){const ee=be.touches[0];A.current={x:ee.clientX,y:ee.clientY,time:Date.now()},_.current={x:ee.clientX,y:ee.clientY},H.current||(N.current=!1),w.current=setTimeout(()=>{if(!N.current&&!H.current)if(N.current=!0,$.current==="mouse"){const me=k.current||{nx:.5,ny:.5};b("Right Click"),p(me.nx,me.ny,"right"),C.current("input_click",{...me,button:"right"}).catch(()=>{})}else{const me=Se(ee);me&&(b("Right Click"),p(me.nx,me.ny,"right"),C.current("input_click",{...me,button:"right"}).catch(()=>{}))}},500);return}if(be.touches.length===2){w.current&&clearTimeout(w.current),N.current=!0,H.current=!0;const ee=be.touches[1].clientX-be.touches[0].clientX,me=be.touches[1].clientY-be.touches[0].clientY;M.current=Math.sqrt(ee*ee+me*me),j.current=l.current,W.current={x:(be.touches[0].clientX+be.touches[1].clientX)/2,y:(be.touches[0].clientY+be.touches[1].clientY)/2}}},fe=be=>{const Ce=t.current;if(Ce&&be.target instanceof Node&&Ce.contains(be.target)&&be.preventDefault(),be.touches.length===1&&_.current){const ee=be.touches[0],me=ee.clientX-_.current.x,ie=ee.clientY-_.current.y;if(!N.current&&A.current){const pe=ee.clientX-A.current.x,le=ee.clientY-A.current.y;Math.sqrt(pe*pe+le*le)>8&&(N.current=!0,w.current&&clearTimeout(w.current))}if(N.current)if($.current==="mouse"){const pe=ve(me,ie),le=k.current||{nx:.5,ny:.5},B=Math.max(0,Math.min(1,le.nx+pe.dnx)),z=Math.max(0,Math.min(1,le.ny+pe.dny));k.current={nx:B,ny:z},I({nx:B,ny:z}),b(`Cursor: ${Math.round(B*100)}%, ${Math.round(z*100)}%`),X(B,z,l.current);const de=Date.now();de-x.current>=30&&(x.current=de,C.current("input_mouseMoved",{nx:B,ny:z}).catch(()=>{}))}else if(l.current>1){const pe=t.current;if(pe){const le=pe.clientWidth,B=pe.clientHeight,z=c.current+me/le*100,de=d.current+ie/B*100,re=g(z,de,l.current);m(re.x),u(re.y),c.current=re.x,d.current=re.y}}else{const pe=Se(ee);if(pe){const le=Date.now();le-x.current>=40&&(x.current=le,b("Scroll"),C.current("input_wheel",{nx:pe.nx,ny:pe.ny,deltaX:Math.round(-me*2.5),deltaY:Math.round(-ie*2.5)}).catch(()=>{}))}}_.current={x:ee.clientX,y:ee.clientY};return}if(be.touches.length===2&&M.current!==null){const ee=be.touches[1].clientX-be.touches[0].clientX,me=be.touches[1].clientY-be.touches[0].clientY,pe=Math.sqrt(ee*ee+me*me)/M.current,le=(be.touches[0].clientX+be.touches[1].clientX)/2,B=(be.touches[0].clientY+be.touches[1].clientY)/2,z=le-W.current.x,de=B-W.current.y,re=Math.abs(pe-1)>.03;if($.current==="mouse"){if(re){const R=Math.max(o,Math.min(5,j.current*pe));h(R),l.current=R}else if(Math.abs(z)>2||Math.abs(de)>2){const R=k.current||{nx:.5,ny:.5},q=Date.now();q-x.current>=30&&(x.current=q,b("Scroll"),C.current("input_wheel",{nx:R.nx,ny:R.ny,deltaX:Math.round(-z*3),deltaY:Math.round(-de*3)}).catch(()=>{}))}}else{const R=Math.max(o,Math.min(5,j.current*pe));h(R),l.current=R;const q=t.current;if(q&&R>1){const ce=q.clientWidth,Ne=q.clientHeight,je=c.current+z/ce*100,O=d.current+de/Ne*100,Ie=g(je,O,R);m(Ie.x),u(Ie.y),c.current=Ie.x,d.current=Ie.y}}W.current={x:le,y:B}}},we=be=>{var Ce;if(w.current&&clearTimeout(w.current),M.current=null,be.touches.length===1&&H.current){const ee=be.touches[0];A.current={x:ee.clientX,y:ee.clientY,time:Date.now()},_.current={x:ee.clientX,y:ee.clientY},N.current=!0;return}if(be.touches.length===0){if(H.current){H.current=!1,N.current=!1;return}if(be.changedTouches.length===1){const ee=be.changedTouches[0],me=Date.now(),ie=me-(((Ce=A.current)==null?void 0:Ce.time)||0),pe=A.current?ee.clientX-A.current.x:0,le=A.current?ee.clientY-A.current.y:0,B=Math.sqrt(pe*pe+le*le);if($.current==="mouse"){if(ie<y||ie>F||B>P){N.current=!1;return}const z=k.current||Se(ee);z&&(b(`Click: ${Math.round(z.nx*100)}%, ${Math.round(z.ny*100)}%`),p(z.nx,z.ny,"left"),C.current("input_click",{...z}).catch(()=>{}))}else{if(N.current){N.current=!1;return}if(ie<E||ie>G||B>J){N.current=!1;return}const z=Se(ee);if(!z)return;me-D.current<300?(b("Double tap"),p(z.nx,z.ny,"double"),C.current("input_click",{...z,clickCount:2}).catch(()=>{}),D.current=0):(b(`Tap: ${Math.round(z.nx*100)}%, ${Math.round(z.ny*100)}%`),p(z.nx,z.ny,"left"),C.current("input_click",{...z}).catch(()=>{}),D.current=me)}}N.current=!1}};return ue.addEventListener("touchstart",xe,{passive:!1}),ue.addEventListener("touchmove",fe,{passive:!1}),ue.addEventListener("touchend",we,{passive:!1}),()=>{ue.removeEventListener("touchstart",xe),ue.removeEventListener("touchmove",fe),ue.removeEventListener("touchend",we),w.current&&clearTimeout(w.current)}},[e,t,r,o,l,c,d,m,u,h,x,b,p,g]),{cursorPos:T,cursorPosRef:k,handleToggleInputMode:()=>{a(ue=>{const Se=ue==="touch"?"mouse":"touch";return Se==="mouse"&&ye(),Se})},handleZoomReset:()=>{const ue=v?f:1;h(ue),l.current=ue,m(0),u(0),c.current=0,d.current=0}}}function Ac({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:o}){const l=i.useRef(null),c=i.useRef(null),d=i.useRef(null),[m,u]=i.useState(null),[h,x]=i.useState(""),[,S]=i.useState(!1),[b,p]=i.useState([]),g=i.useRef(0),[v,f]=i.useState(!1),[T,I]=i.useState(!1),k=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[A,_]=i.useState(k?"mouse":"touch"),[N,w]=i.useState(1),D=i.useRef(!1),[M,j]=i.useState(1),[W,H]=i.useState(0),[$,C]=i.useState(0);Pr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:A,zoom:M,panX:W,panY:$,isMenuOpen:v,isImeOpen:T});const y=i.useRef(0),F=i.useRef(M),P=i.useRef(W),E=i.useRef($);i.useEffect(()=>{F.current=M},[M]),i.useEffect(()=>{P.current=W},[W]),i.useEffect(()=>{E.current=$},[$]),i.useEffect(()=>{var ie;(ie=l.current)==null||ie.focus()},[]);const G=r==="connected",J=n,ye=G?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",he=G?"The remote stream is warming up":"Waiting for the remote stream to catch up";i.useEffect(()=>{if(!k||D.current||!J)return;const ie=d.current,pe=c.current;if(!ie||!pe)return;const le=()=>{const B=pe.clientWidth,z=pe.clientHeight,de=ie.naturalWidth,re=ie.naturalHeight;if(!de||!re||!B||!z)return;const R=Math.min(B/de,z/re),ce=Math.max(B/de,z/re)/R;ce>1.01&&(w(ce),j(ce),F.current=ce),D.current=!0};ie.complete&&ie.naturalWidth?le():ie.addEventListener("load",le,{once:!0})},[J,k]);const ne=.5;i.useEffect(()=>{M<=ne&&(H(0),C(0))},[M,ne]);const ue=(ie,pe,le)=>{if(le<=ne)return{x:0,y:0};const B=(le-1)/(2*le)*100,z=(le-1)/(2*le)*100;return{x:Math.max(-B,Math.min(B,ie)),y:Math.max(-z,Math.min(z,pe))}},Se=(ie,pe)=>{if(!d.current)return null;const le=d.current.getBoundingClientRect();return!le.width||!le.height?null:{nx:Math.max(0,Math.min(1,(ie-le.left)/le.width)),ny:Math.max(0,Math.min(1,(pe-le.top)/le.height))}},ve=(ie,pe,le)=>{const B=c.current;if(!B)return;const z=B.getBoundingClientRect(),de=++g.current;p(re=>[...re,{id:de,x:ie-z.left,y:pe-z.top,type:le}]),setTimeout(()=>p(re=>re.filter(R=>R.id!==de)),600)},X=(ie,pe,le)=>{const B=d.current,z=c.current;if(!B||!z)return;const de=B.getBoundingClientRect(),re=z.getBoundingClientRect(),R=B.naturalWidth||de.width,q=B.naturalHeight||de.height,ce=R/q,Ne=de.width/de.height;let je,O,Ie,Le;ce>Ne?(je=de.width,O=de.width/ce,Ie=0,Le=(de.height-O)/2):(O=de.height,je=de.height*ce,Ie=(de.width-je)/2,Le=0);const He=de.left-re.left+Ie+je*ie,ze=de.top-re.top+Le+O*pe,Xe=++g.current;p(Je=>[...Je,{id:Xe,x:He,y:ze,type:le}]),setTimeout(()=>p(Je=>Je.filter(rt=>rt.id!==Xe)),600)},xe=async ie=>{var le;const pe=Se(ie.clientX,ie.clientY);if(pe){u(`Click: ${Math.round(pe.nx*100)}%, ${Math.round(pe.ny*100)}%`),ve(ie.clientX,ie.clientY,"left"),(le=l.current)==null||le.focus();try{const B=await e("input_click",{nx:pe.nx,ny:pe.ny});B!=null&&B.success||t(`❌ Click failed: ${B==null?void 0:B.error}`)}catch(B){t(`❌ Click error: ${B.message||B}`)}}},fe=async(ie,pe,le,B=0)=>{try{await e("input_key",{type:le?"char":"keyDown",key:ie,code:pe,text:le?ie:void 0,unmodifiedText:le?ie:void 0,modifiers:B})}catch(z){t(`❌ Key error: ${z.message||z}`)}},we=async ie=>{if(ie.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(ie.key)&&ie.preventDefault();let le=0;ie.altKey&&(le|=1),ie.ctrlKey&&(le|=2),ie.metaKey&&(le|=4),ie.shiftKey&&(le|=8),u(`Key: ${ie.key}`),await fe(ie.key,ie.code,ie.key.length===1,le)},be=async ie=>{if(ie.key==="Enter"){if(ie.nativeEvent.isComposing)return;if(h){const pe=h;x(""),u(`IME Sent: ${pe}`);try{const le=await e("input_type",{text:pe});le!=null&&le.success||t(`❌ IME error: ${le==null?void 0:le.error}`)}catch(le){t(`❌ IME error: ${le.message}`)}}else u("Key: Enter"),await fe("Enter","Enter",!1)}};i.useEffect(()=>{const ie=l.current;if(!ie)return;const pe=le=>{var B;if((B=d.current)!=null&&B.contains(le.target)){le.preventDefault();const z=Date.now();if(z-y.current<40)return;y.current=z;const de=Se(le.clientX,le.clientY);if(!de)return;u(`Scroll: ${Math.round(le.deltaY)}`),e("input_wheel",{nx:de.nx,ny:de.ny,deltaX:Math.round(le.deltaX),deltaY:Math.round(le.deltaY)}).catch(()=>{})}};return ie.addEventListener("wheel",pe,{passive:!1}),()=>ie.removeEventListener("wheel",pe)},[e]);const{cursorPos:Ce,handleToggleInputMode:ee,handleZoomReset:me}=Xp({containerRef:l,viewportRef:c,imgRef:d,inputMode:A,setInputMode:_,minZoom:ne,zoomRef:F,panXRef:P,panYRef:E,setPanX:H,setPanY:C,setZoom:j,lastWheelTimeRef:y,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:X,clampPan:ue,isMobile:k,mobileFillZoom:N});return s.jsxs("div",{ref:l,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:we,onContextMenu:ie=>ie.preventDefault(),onFocus:()=>S(!0),onBlur:()=>S(!1),tabIndex:0,children:[s.jsxs("div",{ref:c,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[J?s.jsx("img",{ref:d,src:J,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${M}) translate(${W}%, ${$}%)`,transformOrigin:"center center",cursor:A==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:xe,onContextMenu:ie=>ie.preventDefault(),onDragStart:ie=>ie.preventDefault()}):s.jsx(qp,{waitingLabel:ye,waitingHint:he,transportType:o}),A==="mouse"&&J&&s.jsx(Vp,{cursorPos:Ce,viewportRef:c,imgRef:d}),b.map(ie=>{const le={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[ie.type];return s.jsxs("div",{style:{position:"absolute",left:ie.x,top:ie.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${le}, 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(${le}, 0.9)`,boxShadow:`0 0 12px rgba(${le}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},ie.id)})]}),s.jsx(Gp,{inputMode:A,onToggleInputMode:ee,isImeOpen:T,setIsImeOpen:I,isMenuOpen:v,setIsMenuOpen:f,imeText:h,setImeText:x,handleImeSubmit:be,isConnActive:G,zoom:M,isMobile:k,mobileFillZoom:N,onZoomOut:()=>j(ie=>Math.max(.5,ie-.25)),onZoomReset:me,onZoomIn:()=>j(ie=>Math.min(5,ie+.25)),transportType:o,screenshotUsage:a,lastActionStatus:m}),s.jsx("style",{children:`
|
|
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 Fp=i.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(Io,{remarkPlugins:Mp,children:t.text}),s.jsx("span",{className:"action-time",children:Tc(t.timestamp)})]})},(e,t)=>e.log===t.log),Wp=i.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:o,isTextExpanded:l,onToggleTextExpanded:c}){var N,w,D;const d=(t.role||"").toLowerCase(),m=d==="user"||d==="human",u=t.kind||(d==="tool"?"tool":"standard"),h=Eo(t),x=Op(t.content)?t.content:null,S=!!(x!=null&&x.some(M=>M.type!=="text")),b=Mo(t.content,{joiner:`
|
|
6
|
+
`});if(h.isActivityFacing&&u!=="thought"&&u!=="tool"&&u!=="terminal"){const M=h.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:M})]}),S&&x?s.jsx("div",{className:"chat-msg-activity-body",children:s.jsx(ar,{parts:x,renderAsPreformatted:!1})}):s.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:b})]})}if(u==="thought"){const M=typeof((N=t.meta)==null?void 0:N.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":h.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(op,{size:13}),s.jsx("span",{children:M})]}),s.jsx("div",{className:"chat-msg-body",children:b})]})}if(u==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":h.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"})]}),S&&x?s.jsx("div",{className:"tool-text w-full",children:s.jsx(ar,{parts:x,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:b})]});if(u==="terminal"){const M=(w=t.meta)!=null&&w.isRunning?"⏳":"✅",j=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":h.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:M}),s.jsx("span",{children:j})]}),S&&x?s.jsx("div",{className:"chat-msg-body",children:s.jsx(ar,{parts:x,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:b})]})}if(u==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:S&&x?s.jsx(ar,{parts:x,renderAsPreformatted:!1}):b.slice(0,100)});const p=t.meta,v=(typeof(p==null?void 0:p.renderMode)=="string"?p.renderMode.trim():"")==="preformatted",f=b,C=!1,T=f,k=v,A=!k&&Mc(T),_=["chat-message-row",m?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return s.jsx("div",{className:_,children:(f||S||m)&&s.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${f||S?"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:Tc(r)})]}),(f||S)&&s.jsx("div",{className:"chat-markdown",children:S&&x?s.jsx(ar,{parts:x,renderAsPreformatted:k}):k?s.jsx("pre",{className:"chat-preformatted",children:T}):A?s.jsx(Io,{remarkPlugins:Ic,children:T}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:T})}),C]})})},(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),Kp=i.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:o=!1,isWorking:l=!1,contextKey:c="",receivedAtMap:d={},lastMessageHash:m,showActivityMessages:u=!1,emptyState:h,onLoadMore:x,isLoadingMore:S,hasMoreHistory:b,hiddenLiveCount:p=0,loadError:g,scrollToBottomRequestNonce:v,isVisible:f=!0},C){const T=i.useRef(null),k=i.useRef(null),A=i.useRef(null),_=i.useRef(0),N=i.useRef(""),w=i.useRef(""),D=i.useRef(!1),M=i.useRef(null),j=i.useRef(!1),W=i.useRef(null),H=i.useRef(!1),[$,I]=i.useState(new Set),[y,F]=i.useState({showTop:!1,showBottom:!1}),P=i.useRef(!1),E=i.useRef(!1),G=i.useRef(f),J=i.useRef(f),ye=i.useRef(null);J.current=f;const he=()=>{const re=T.current;return re?re.scrollHeight-re.scrollTop-re.clientHeight<$o:!0},ne=i.useCallback(()=>{const re=T.current,R=re?Pp(re):{showTop:!1,showBottom:!1};F(q=>q.showTop===R.showTop&&q.showBottom===R.showBottom?q:R)},[]),ue=i.useCallback((re="auto")=>{var q;const R=T.current;R&&(R.scrollTo({top:R.scrollHeight,behavior:re}),(q=R.ownerDocument.defaultView)==null||q.requestAnimationFrame(()=>ne()))},[ne]),Se=i.useCallback((re="auto")=>{var q;const R=T.current;R&&(R.scrollTo({top:0,behavior:re}),(q=R.ownerDocument.defaultView)==null||q.requestAnimationFrame(()=>ne()))},[ne]),ve=i.useCallback(()=>{var Ne;const re=T.current,R=(Ne=window.getSelection)==null?void 0:Ne.call(window);if(!re||!R||R.rangeCount===0||R.isCollapsed){H.current=!1;return}const q=R.anchorNode,ce=R.focusNode;H.current=!!(q&&ce&&re.contains(q)&&re.contains(ce))},[]),X=i.useMemo(()=>{const re=Cp(t),R=Nc(t);return Ip(re,R,u)},[t,u]),xe=X.length===t.length?m:void 0,fe=_p(X,xe),we=i.useCallback(()=>{const re=T.current;if(!re||!c||!J.current)return;const R={top:re.scrollTop,fromBottom:Math.max(0,re.scrollHeight-re.scrollTop-re.clientHeight),messageFingerprint:fe};ye.current={contextKey:c,snapshot:R},rr.set(c,R)},[c,fe]),be=i.useCallback((re="auto")=>{M.current!=null&&cancelAnimationFrame(M.current),M.current=requestAnimationFrame(()=>{M.current=null,ue(re)})},[ue]),Ce=i.useCallback(()=>{P.current=!1,j.current=!0,E.current=!0,W.current!=null&&window.clearTimeout(W.current),W.current=window.setTimeout(()=>{j.current=!1,W.current=null},Pi)},[]);i.useEffect(()=>{const re=!D.current,R=w.current!==c;if(w.current=c,re||R){D.current=!0;const ce=c?rr.get(c):null,Ne=!!ce&&Cn(ce,fe);P.current=Ne?gr(ce):!1,j.current=Dp(ce,fe),H.current||(Ne?requestAnimationFrame(()=>{const je=T.current;je&&(ia(je,ce),P.current=gr(ce),ne(),E.current=!0)}):be("auto")),_.current=X.length,N.current=fe;return}X.length>_.current;const q=fe!==N.current;Ep({hasSelection:H.current,userScrolledUp:P.current,hasChatContentChanged:q})&&be("auto"),_.current=X.length,N.current=fe},[fe,c,X.length,be,ne]),i.useEffect(()=>{v&&(Ce(),H.current||be("auto"))},[Ce,be,v]),i.useEffect(()=>{const re=G.current;re&&!f&&we(),J.current=f,G.current=f;const R=c?rr.get(c):null;if(Lp(re,f,R,fe)){if(!R)return;P.current=gr(R),j.current=!1,H.current||requestAnimationFrame(()=>{const q=T.current;q&&(ia(q,R),ne())});return}},[f,c,fe,Ce,we,be,ne]),i.useEffect(()=>()=>{const re=ye.current;re&&rr.set(re.contextKey,re.snapshot),M.current!=null&&cancelAnimationFrame(M.current),W.current!=null&&window.clearTimeout(W.current)},[]),i.useEffect(()=>{const re=k.current,R=T.current;if(!re||!R)return;const q=()=>{W.current!=null&&window.clearTimeout(W.current),W.current=window.setTimeout(()=>{j.current=!1,W.current=null},Pi)},ce=new ResizeObserver(()=>{ne();const Ne=j.current;$p({hasSelection:H.current,userScrolledUp:P.current,contextAutoScrollActive:Ne})&&(be("auto"),Ne&&q())});return ce.observe(re),R!==re&&ce.observe(R),()=>{ce.disconnect(),W.current!=null&&(window.clearTimeout(W.current),W.current=null)}},[be,c,ne]),i.useImperativeHandle(C,()=>({scrollToBottom:(re="smooth")=>{ue(re)}}),[ue]),i.useEffect(()=>{const re=T.current;if(!re)return;let R;const q=()=>{we(),clearTimeout(R),R=setTimeout(()=>{P.current=!he(),ne()},50)};return re.addEventListener("scroll",q,{passive:!0}),()=>{re.removeEventListener("scroll",q),clearTimeout(R)}},[we,ne]),i.useEffect(()=>(document.addEventListener("selectionchange",ve),()=>document.removeEventListener("selectionchange",ve)),[ve]);const ee=i.useRef(0),me=i.useRef(!1);i.useEffect(()=>{const re=T.current;if(!re||!me.current||ee.current===0)return;const R=re.scrollHeight-ee.current;R>0&&(re.scrollTop=R),ne(),we(),ee.current=0,me.current=!1},[X.length,we,ne]),i.useEffect(()=>{if(E.current||!c)return;const re=rr.get(c),R=T.current;if(!(!re||!R)){if(!Cn(re,fe)){ue("auto"),E.current=!0;return}ia(R,re),P.current=gr(re),ne(),E.current=!0}},[c,fe,X.length,ue,ne]);const ie=()=>{const re=T.current;re&&(ee.current=re.scrollHeight),me.current=!0,x==null||x()},pe=()=>{P.current=!0,Se("smooth"),we()},le=()=>{Ce(),ue("smooth"),we()},B=i.useMemo(()=>{const re=X.map((Ne,je)=>({type:"message",data:Ne,index:je,ts:Bp(Ne,je,d)}));if(!r||r.length===0)return re;const R=[...r].sort((Ne,je)=>Ne.timestamp-je.timestamp).map((Ne,je)=>({type:"action",data:Ne,index:je,ts:Ne.timestamp})),q=[];let ce=0;for(const Ne of re){for(;ce<R.length&&Ne.ts>0&&R[ce].ts<Ne.ts;)q.push(R[ce++]);q.push(Ne)}for(;ce<R.length;)q.push(R[ce++]);return q},[X,r,d]),z=p>0||!!b,de=p>0?`↑ Show ${Math.min(p,80)} earlier messages${p>80?` (${p} hidden)`:""}`:g?`↻ ${g}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:T,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:k,className:"chat-container-content",children:[S&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),z&&!S&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:ie,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${g&&p===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:de})}),B.length===0&&!z&&(h||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),B.map(re=>{if(re.type==="action"){const Ie=re.data;return s.jsx(Fp,{log:Ie},`action-${re.index}`)}const R=re.data,q=re.index,ce=In(R,q),Ne=R.receivedAt||d[ce],je=`${c}-${ce}`,O=$.has(je);return s.jsx(Wp,{message:R,receivedAt:Ne,agentName:n,userName:a,isCliMode:o,isTextExpanded:O,onToggleTextExpanded:()=>I(Ie=>{const Le=new Set(Ie);return O?Le.delete(je):Le.add(je),Le})},`msg-${ce}`)}),l&&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:A})]})}),(y.showTop||y.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[y.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:pe,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),y.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:le,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),Hp=i.memo(Kp,(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),Up="modulepreload",zp=function(e){return"/"+e},Ei={},Vp=function(t,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),c=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));a=Promise.allSettled(r.map(d=>{if(d=zp(d),d in Ei)return;Ei[d]=!0;const m=d.endsWith(".css"),u=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const h=document.createElement("link");if(h.rel=m?"stylesheet":Up,m||(h.as="script"),h.crossOrigin="",h.href=d,c&&h.setAttribute("nonce",c),document.head.appendChild(h),m)return new Promise((x,S)=>{h.addEventListener("load",x),h.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return a.then(l=>{for(const c of l||[])c.status==="rejected"&&o(c.reason);return t().catch(o)})};let $i=!1;const Ac=i.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:o="measured"},l)=>{const c=i.useRef(null),[d,m]=i.useState(null),u=i.useRef([]),h=i.useRef(!1),x=i.useRef(!1),S=i.useRef(!1),b=i.useRef(!1),p=()=>{const g=c.current;if(g){h.current&&(g.clear(),h.current=!1);for(const v of u.current)g.write(v.data,v.onProcessed);u.current=[],x.current&&(g.fit(),x.current=!1),S.current&&(g.bumpResize(),S.current=!1),b.current&&(g.scrollToTop(),b.current=!1)}};return i.useImperativeHandle(l,()=>({write:(g,v)=>{c.current?c.current.write(g,v):u.current.push({data:g,onProcessed:v})},clear:()=>{c.current?c.current.clear():(u.current=[],h.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(u.current=[],h.current=!0)},resize:(g,v)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(g,v)},fit:()=>{c.current?c.current.fit():x.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():S.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():b.current=!0},getSelection:()=>{var g,v;return((v=(g=c.current)==null?void 0:g.getSelection)==null?void 0:v.call(g))||""},getVisibleText:()=>{var g,v;return((v=(g=c.current)==null?void 0:g.getVisibleText)==null?void 0:v.call(g))||""}}),[]),i.useEffect(()=>{d&&p()},[d]),i.useEffect(()=>{let g=!1;return Vp(()=>import("./terminal-D46M5EWH.js"),__vite__mapDeps([0,1,2])).then(v=>{$i||($i=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),g||m(()=>v.GhosttyTerminalView)}).catch(v=>{console.error("[CliTerminal] failed to load terminal renderer",v)}),()=>{g=!0}},[]),d?s.jsx(d,{ref:c,onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n,readOnly:a,sizingMode:o,className:"w-full h-full rounded-lg overflow-hidden"}):s.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});Ac.displayName="CliTerminal";function Yr({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 Bi({value:e,max:t,label:r,color:n="#8b5cf6",detail:a,compact:o=!1}){const l=t>0?Math.min(Math.round(e/t*100),100):0,c=l>85?"#ef4444":l>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:[l,"%"]})]}),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:`${l}%`,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:[l,"%"]})]}),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:`${l}%`,background:`linear-gradient(90deg, ${c}, ${c}cc)`}})}),a&&s.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function Gp({cursorPos:e,viewportRef:t,imgRef:r}){var f;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),o=(f=t.current)==null?void 0:f.getBoundingClientRect();if(!o)return null;const l=n.naturalWidth||a.width,c=n.naturalHeight||a.height,d=l/c,m=a.width/a.height;let u,h,x,S;d>m?(u=a.width,h=a.width/d,x=0,S=(a.height-h)/2):(h=a.height,u=a.height*d,x=(a.width-u)/2,S=0);const b=a.left-o.left+x+u*e.nx,p=a.top-o.top+S+h*e.ny,g=Math.max(8,Math.min(o.width-8,b)),v=Math.max(8,Math.min(o.height-8,p));return s.jsxs("div",{style:{position:"absolute",left:g-8,top:v-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 qp({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:o,imeText:l,setImeText:c,handleImeSubmit:d,isConnActive:m,zoom:u,isMobile:h,mobileFillZoom:x,onZoomOut:S,onZoomReset:b,onZoomIn:p,transportType:g,screenshotUsage:v,lastActionStatus:f}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:C=>C.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(C=>!C),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:l,autoFocus:!0,onTouchStart:C=>C.stopPropagation(),onChange:C=>c(C.target.value),onKeyDown:C=>{d(C)},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(C=>!C),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"})]}),u>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(u*100),"%"]}),g==="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"}),g==="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"}),v&&v.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:v.budgetExhausted?"#ef4444":"#c4b5fd",background:v.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:v.budgetExhausted?"TURN blocked":`TURN ${v.dailyUsedMinutes}/${v.dailyBudgetMinutes}m`}),f&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:f})]})]}),a&&s.jsxs("div",{onTouchStart:C=>C.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",u<=(h?x:1)+.01?h?"FILL":"FIT":`${Math.round(u*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:C=>{C.stopPropagation(),S()},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:C=>{C.stopPropagation(),b()},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:h?"FILL":"FIT"}),s.jsx("button",{onClick:C=>{C.stopPropagation(),p()},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 Yp({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 Xp(){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 Oi(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 Pr(e,t){const r=i.useRef(null),n=i.useRef(0);i.useEffect(()=>{if(!Xp())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(([l,c])=>[l,Oi(c)]))}),r.current=t;return}const o=Object.keys({...a,...t}).filter(l=>!Object.is(a[l],t[l]));o.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:o,snapshot:Object.fromEntries(o.map(l=>[l,Oi(t[l])]))}),r.current=t})}function Jp({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:o,zoomRef:l,panXRef:c,panYRef:d,setPanX:m,setPanY:u,setZoom:h,lastWheelTimeRef:x,onAction:S,setLastActionStatus:b,spawnRippleFromNormalized:p,clampPan:g,isMobile:v,mobileFillZoom:f}){const[C,T]=i.useState(null),k=i.useRef(null),A=i.useRef(null),_=i.useRef(null),N=i.useRef(!1),w=i.useRef(null),D=i.useRef(0),M=i.useRef(null),j=i.useRef(1),W=i.useRef({x:0,y:0}),H=i.useRef(!1),$=i.useRef(n),I=i.useRef(S),y=30,F=550,P=18,E=60,G=400,J=12,ye=()=>{if(k.current)return;const ue={nx:.5,ny:.5};k.current=ue,T(ue)};return i.useEffect(()=>{$.current=n,n==="mouse"&&ye()},[n]),i.useEffect(()=>{I.current=S},[S]),i.useEffect(()=>{const ue=e.current;if(!ue)return;const Se=be=>{if(!r.current)return null;const Ce=r.current.getBoundingClientRect();return!Ce.width||!Ce.height?null:{nx:Math.max(0,Math.min(1,(be.clientX-Ce.left)/Ce.width)),ny:Math.max(0,Math.min(1,(be.clientY-Ce.top)/Ce.height))}},ve=(be,Ce)=>{if(!r.current)return{dnx:0,dny:0};const ee=r.current,me=ee.getBoundingClientRect(),ie=ee.naturalWidth||me.width,pe=ee.naturalHeight||me.height,le=ie/pe,B=me.width/me.height;let z,de;return le>B?(z=me.width,de=me.width/le):(de=me.height,z=me.height*le),{dnx:be/z,dny:Ce/de}},X=(be,Ce,ee)=>{if(ee<=1.05)return;const me=-(be-.5)*100,ie=-(Ce-.5)*100,pe=g(me,ie,ee);(Math.abs(pe.x-c.current)>.1||Math.abs(pe.y-d.current)>.1)&&(m(pe.x),u(pe.y),c.current=pe.x,d.current=pe.y)},xe=be=>{const Ce=t.current;if(Ce&&be.target instanceof Node&&Ce.contains(be.target))be.preventDefault();else return;if(be.touches.length===1){const ee=be.touches[0];A.current={x:ee.clientX,y:ee.clientY,time:Date.now()},_.current={x:ee.clientX,y:ee.clientY},H.current||(N.current=!1),w.current=setTimeout(()=>{if(!N.current&&!H.current)if(N.current=!0,$.current==="mouse"){const me=k.current||{nx:.5,ny:.5};b("Right Click"),p(me.nx,me.ny,"right"),I.current("input_click",{...me,button:"right"}).catch(()=>{})}else{const me=Se(ee);me&&(b("Right Click"),p(me.nx,me.ny,"right"),I.current("input_click",{...me,button:"right"}).catch(()=>{}))}},500);return}if(be.touches.length===2){w.current&&clearTimeout(w.current),N.current=!0,H.current=!0;const ee=be.touches[1].clientX-be.touches[0].clientX,me=be.touches[1].clientY-be.touches[0].clientY;M.current=Math.sqrt(ee*ee+me*me),j.current=l.current,W.current={x:(be.touches[0].clientX+be.touches[1].clientX)/2,y:(be.touches[0].clientY+be.touches[1].clientY)/2}}},fe=be=>{const Ce=t.current;if(Ce&&be.target instanceof Node&&Ce.contains(be.target)&&be.preventDefault(),be.touches.length===1&&_.current){const ee=be.touches[0],me=ee.clientX-_.current.x,ie=ee.clientY-_.current.y;if(!N.current&&A.current){const pe=ee.clientX-A.current.x,le=ee.clientY-A.current.y;Math.sqrt(pe*pe+le*le)>8&&(N.current=!0,w.current&&clearTimeout(w.current))}if(N.current)if($.current==="mouse"){const pe=ve(me,ie),le=k.current||{nx:.5,ny:.5},B=Math.max(0,Math.min(1,le.nx+pe.dnx)),z=Math.max(0,Math.min(1,le.ny+pe.dny));k.current={nx:B,ny:z},T({nx:B,ny:z}),b(`Cursor: ${Math.round(B*100)}%, ${Math.round(z*100)}%`),X(B,z,l.current);const de=Date.now();de-x.current>=30&&(x.current=de,I.current("input_mouseMoved",{nx:B,ny:z}).catch(()=>{}))}else if(l.current>1){const pe=t.current;if(pe){const le=pe.clientWidth,B=pe.clientHeight,z=c.current+me/le*100,de=d.current+ie/B*100,re=g(z,de,l.current);m(re.x),u(re.y),c.current=re.x,d.current=re.y}}else{const pe=Se(ee);if(pe){const le=Date.now();le-x.current>=40&&(x.current=le,b("Scroll"),I.current("input_wheel",{nx:pe.nx,ny:pe.ny,deltaX:Math.round(-me*2.5),deltaY:Math.round(-ie*2.5)}).catch(()=>{}))}}_.current={x:ee.clientX,y:ee.clientY};return}if(be.touches.length===2&&M.current!==null){const ee=be.touches[1].clientX-be.touches[0].clientX,me=be.touches[1].clientY-be.touches[0].clientY,pe=Math.sqrt(ee*ee+me*me)/M.current,le=(be.touches[0].clientX+be.touches[1].clientX)/2,B=(be.touches[0].clientY+be.touches[1].clientY)/2,z=le-W.current.x,de=B-W.current.y,re=Math.abs(pe-1)>.03;if($.current==="mouse"){if(re){const R=Math.max(o,Math.min(5,j.current*pe));h(R),l.current=R}else if(Math.abs(z)>2||Math.abs(de)>2){const R=k.current||{nx:.5,ny:.5},q=Date.now();q-x.current>=30&&(x.current=q,b("Scroll"),I.current("input_wheel",{nx:R.nx,ny:R.ny,deltaX:Math.round(-z*3),deltaY:Math.round(-de*3)}).catch(()=>{}))}}else{const R=Math.max(o,Math.min(5,j.current*pe));h(R),l.current=R;const q=t.current;if(q&&R>1){const ce=q.clientWidth,Ne=q.clientHeight,je=c.current+z/ce*100,O=d.current+de/Ne*100,Ie=g(je,O,R);m(Ie.x),u(Ie.y),c.current=Ie.x,d.current=Ie.y}}W.current={x:le,y:B}}},we=be=>{var Ce;if(w.current&&clearTimeout(w.current),M.current=null,be.touches.length===1&&H.current){const ee=be.touches[0];A.current={x:ee.clientX,y:ee.clientY,time:Date.now()},_.current={x:ee.clientX,y:ee.clientY},N.current=!0;return}if(be.touches.length===0){if(H.current){H.current=!1,N.current=!1;return}if(be.changedTouches.length===1){const ee=be.changedTouches[0],me=Date.now(),ie=me-(((Ce=A.current)==null?void 0:Ce.time)||0),pe=A.current?ee.clientX-A.current.x:0,le=A.current?ee.clientY-A.current.y:0,B=Math.sqrt(pe*pe+le*le);if($.current==="mouse"){if(ie<y||ie>F||B>P){N.current=!1;return}const z=k.current||Se(ee);z&&(b(`Click: ${Math.round(z.nx*100)}%, ${Math.round(z.ny*100)}%`),p(z.nx,z.ny,"left"),I.current("input_click",{...z}).catch(()=>{}))}else{if(N.current){N.current=!1;return}if(ie<E||ie>G||B>J){N.current=!1;return}const z=Se(ee);if(!z)return;me-D.current<300?(b("Double tap"),p(z.nx,z.ny,"double"),I.current("input_click",{...z,clickCount:2}).catch(()=>{}),D.current=0):(b(`Tap: ${Math.round(z.nx*100)}%, ${Math.round(z.ny*100)}%`),p(z.nx,z.ny,"left"),I.current("input_click",{...z}).catch(()=>{}),D.current=me)}}N.current=!1}};return ue.addEventListener("touchstart",xe,{passive:!1}),ue.addEventListener("touchmove",fe,{passive:!1}),ue.addEventListener("touchend",we,{passive:!1}),()=>{ue.removeEventListener("touchstart",xe),ue.removeEventListener("touchmove",fe),ue.removeEventListener("touchend",we),w.current&&clearTimeout(w.current)}},[e,t,r,o,l,c,d,m,u,h,x,b,p,g]),{cursorPos:C,cursorPosRef:k,handleToggleInputMode:()=>{a(ue=>{const Se=ue==="touch"?"mouse":"touch";return Se==="mouse"&&ye(),Se})},handleZoomReset:()=>{const ue=v?f:1;h(ue),l.current=ue,m(0),u(0),c.current=0,d.current=0}}}function _c({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:o}){const l=i.useRef(null),c=i.useRef(null),d=i.useRef(null),[m,u]=i.useState(null),[h,x]=i.useState(""),[,S]=i.useState(!1),[b,p]=i.useState([]),g=i.useRef(0),[v,f]=i.useState(!1),[C,T]=i.useState(!1),k=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[A,_]=i.useState(k?"mouse":"touch"),[N,w]=i.useState(1),D=i.useRef(!1),[M,j]=i.useState(1),[W,H]=i.useState(0),[$,I]=i.useState(0);Pr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:A,zoom:M,panX:W,panY:$,isMenuOpen:v,isImeOpen:C});const y=i.useRef(0),F=i.useRef(M),P=i.useRef(W),E=i.useRef($);i.useEffect(()=>{F.current=M},[M]),i.useEffect(()=>{P.current=W},[W]),i.useEffect(()=>{E.current=$},[$]),i.useEffect(()=>{var ie;(ie=l.current)==null||ie.focus()},[]);const G=r==="connected",J=n,ye=G?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",he=G?"The remote stream is warming up":"Waiting for the remote stream to catch up";i.useEffect(()=>{if(!k||D.current||!J)return;const ie=d.current,pe=c.current;if(!ie||!pe)return;const le=()=>{const B=pe.clientWidth,z=pe.clientHeight,de=ie.naturalWidth,re=ie.naturalHeight;if(!de||!re||!B||!z)return;const R=Math.min(B/de,z/re),ce=Math.max(B/de,z/re)/R;ce>1.01&&(w(ce),j(ce),F.current=ce),D.current=!0};ie.complete&&ie.naturalWidth?le():ie.addEventListener("load",le,{once:!0})},[J,k]);const ne=.5;i.useEffect(()=>{M<=ne&&(H(0),I(0))},[M,ne]);const ue=(ie,pe,le)=>{if(le<=ne)return{x:0,y:0};const B=(le-1)/(2*le)*100,z=(le-1)/(2*le)*100;return{x:Math.max(-B,Math.min(B,ie)),y:Math.max(-z,Math.min(z,pe))}},Se=(ie,pe)=>{if(!d.current)return null;const le=d.current.getBoundingClientRect();return!le.width||!le.height?null:{nx:Math.max(0,Math.min(1,(ie-le.left)/le.width)),ny:Math.max(0,Math.min(1,(pe-le.top)/le.height))}},ve=(ie,pe,le)=>{const B=c.current;if(!B)return;const z=B.getBoundingClientRect(),de=++g.current;p(re=>[...re,{id:de,x:ie-z.left,y:pe-z.top,type:le}]),setTimeout(()=>p(re=>re.filter(R=>R.id!==de)),600)},X=(ie,pe,le)=>{const B=d.current,z=c.current;if(!B||!z)return;const de=B.getBoundingClientRect(),re=z.getBoundingClientRect(),R=B.naturalWidth||de.width,q=B.naturalHeight||de.height,ce=R/q,Ne=de.width/de.height;let je,O,Ie,Le;ce>Ne?(je=de.width,O=de.width/ce,Ie=0,Le=(de.height-O)/2):(O=de.height,je=de.height*ce,Ie=(de.width-je)/2,Le=0);const He=de.left-re.left+Ie+je*ie,ze=de.top-re.top+Le+O*pe,Xe=++g.current;p(Je=>[...Je,{id:Xe,x:He,y:ze,type:le}]),setTimeout(()=>p(Je=>Je.filter(rt=>rt.id!==Xe)),600)},xe=async ie=>{var le;const pe=Se(ie.clientX,ie.clientY);if(pe){u(`Click: ${Math.round(pe.nx*100)}%, ${Math.round(pe.ny*100)}%`),ve(ie.clientX,ie.clientY,"left"),(le=l.current)==null||le.focus();try{const B=await e("input_click",{nx:pe.nx,ny:pe.ny});B!=null&&B.success||t(`❌ Click failed: ${B==null?void 0:B.error}`)}catch(B){t(`❌ Click error: ${B.message||B}`)}}},fe=async(ie,pe,le,B=0)=>{try{await e("input_key",{type:le?"char":"keyDown",key:ie,code:pe,text:le?ie:void 0,unmodifiedText:le?ie:void 0,modifiers:B})}catch(z){t(`❌ Key error: ${z.message||z}`)}},we=async ie=>{if(ie.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(ie.key)&&ie.preventDefault();let le=0;ie.altKey&&(le|=1),ie.ctrlKey&&(le|=2),ie.metaKey&&(le|=4),ie.shiftKey&&(le|=8),u(`Key: ${ie.key}`),await fe(ie.key,ie.code,ie.key.length===1,le)},be=async ie=>{if(ie.key==="Enter"){if(ie.nativeEvent.isComposing)return;if(h){const pe=h;x(""),u(`IME Sent: ${pe}`);try{const le=await e("input_type",{text:pe});le!=null&&le.success||t(`❌ IME error: ${le==null?void 0:le.error}`)}catch(le){t(`❌ IME error: ${le.message}`)}}else u("Key: Enter"),await fe("Enter","Enter",!1)}};i.useEffect(()=>{const ie=l.current;if(!ie)return;const pe=le=>{var B;if((B=d.current)!=null&&B.contains(le.target)){le.preventDefault();const z=Date.now();if(z-y.current<40)return;y.current=z;const de=Se(le.clientX,le.clientY);if(!de)return;u(`Scroll: ${Math.round(le.deltaY)}`),e("input_wheel",{nx:de.nx,ny:de.ny,deltaX:Math.round(le.deltaX),deltaY:Math.round(le.deltaY)}).catch(()=>{})}};return ie.addEventListener("wheel",pe,{passive:!1}),()=>ie.removeEventListener("wheel",pe)},[e]);const{cursorPos:Ce,handleToggleInputMode:ee,handleZoomReset:me}=Jp({containerRef:l,viewportRef:c,imgRef:d,inputMode:A,setInputMode:_,minZoom:ne,zoomRef:F,panXRef:P,panYRef:E,setPanX:H,setPanY:I,setZoom:j,lastWheelTimeRef:y,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:X,clampPan:ue,isMobile:k,mobileFillZoom:N});return s.jsxs("div",{ref:l,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:we,onContextMenu:ie=>ie.preventDefault(),onFocus:()=>S(!0),onBlur:()=>S(!1),tabIndex:0,children:[s.jsxs("div",{ref:c,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[J?s.jsx("img",{ref:d,src:J,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${M}) translate(${W}%, ${$}%)`,transformOrigin:"center center",cursor:A==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:xe,onContextMenu:ie=>ie.preventDefault(),onDragStart:ie=>ie.preventDefault()}):s.jsx(Yp,{waitingLabel:ye,waitingHint:he,transportType:o}),A==="mouse"&&J&&s.jsx(Gp,{cursorPos:Ce,viewportRef:c,imgRef:d}),b.map(ie=>{const le={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[ie.type];return s.jsxs("div",{style:{position:"absolute",left:ie.x,top:ie.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${le}, 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(${le}, 0.9)`,boxShadow:`0 0 12px rgba(${le}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},ie.id)})]}),s.jsx(qp,{inputMode:A,onToggleInputMode:ee,isImeOpen:C,setIsImeOpen:T,isMenuOpen:v,setIsMenuOpen:f,imeText:h,setImeText:x,handleImeSubmit:be,isConnActive:G,zoom:M,isMobile:k,mobileFillZoom:N,onZoomOut:()=>j(ie=>Math.max(.5,ie-.25)),onZoomReset:me,onZoomIn:()=>j(ie=>Math.min(5,ie+.25)),transportType:o,screenshotUsage:a,lastActionStatus:m}),s.jsx("style",{children:`
|
|
7
7
|
@keyframes slideUp {
|
|
8
8
|
from { opacity: 0; transform: translateY(6px); }
|
|
9
9
|
to { opacity: 1; transform: translateY(0); }
|
|
@@ -26,9 +26,9 @@ var om=Object.defineProperty;var im=(e,t,r)=>t in e?om(e,t,{enumerable:!0,config
|
|
|
26
26
|
50% { transform: translateY(-7px); }
|
|
27
27
|
100% { transform: translateY(0px); }
|
|
28
28
|
}
|
|
29
|
-
`})]})}function Un(e,t={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=t,o=Date.now()-e,l=Math.floor(o/1e3);if(l<a)return n;const c=Math.floor(l/60);if(c<60)return`${c}m${r}`;const d=Math.floor(c/60);if(d<24)return`${d}h${r}`;const m=Math.floor(d/24);return m<7?`${m}d${r}`:new Date(e).toLocaleDateString()}const _c=e=>Un(e);function Jp(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 Qs(e){const t=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating",a=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:r,isGenerating:n,isWaiting:a}}function Qp(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...Jp(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 Tn(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 zn(e,t,r){const n=Tn(e,t),a=Qs(e),o=a.isReconnecting,l=a.isConnecting,c=a.isGenerating,d=a.isWaiting,m=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||d,u=n.inboxBucket==="working"||c,x=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:x,requiresAction:m,isWorking:u,isReconnecting:o,isConnecting:l,isGenerating:c,isWaiting:d,inboxBucket:m?"needs_attention":u?"working":x?"task_complete":"idle"}}function Zp(e,t,r){return zn(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Lc({activeConv:e,onModalButton:t}){const[r,n]=i.useState(null);if(i.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Qs(e).isWaiting||!e.modalButtons)return null;const o=c=>{r||(n(c),t(c))},l=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(Ar,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((c,d)=>{const m=l(c).toLowerCase(),u=/^(run|approve|accept|yes|allow|always)/.test(m),h=/^(reject|deny|delete|remove|abort)/.test(m),x=r===c,S=r!==null;return s.jsx("button",{onClick:()=>o(c),disabled:S,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${u?"font-extrabold":h?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${S&&!x?"opacity-40":"opacity-100"} ${S?"cursor-not-allowed":"cursor-pointer"}`,style:u?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:h?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:x?"⏳ ...":l(c)},d)})})]})]})}const Bo="adhdev_controls_bar_visible",oo="adhdev:controlsbarvisibilitychange";function ca(e){if(!e)return!1;try{return e.getItem(Bo)==="1"}catch{return!1}}function eh(e,t){if(t)try{t.setItem(Bo,e?"1":"0")}catch{}}function th(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(oo,{detail:{visible:e}}))}function Oo(){const[e,t]=i.useState(()=>typeof window>"u"?!1:ca(window.localStorage)),r=i.useRef(e),n=i.useCallback((l,c=!0)=>{r.current=l,t(l),typeof window<"u"&&eh(l,window.localStorage),c&&th(l)},[]);i.useEffect(()=>{const l=d=>{const m=d.detail,u=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:ca(window.localStorage);r.current=u,t(u)},c=d=>{if(d.key!==Bo)return;const m=ca(window.localStorage);r.current=m,t(m)};return window.addEventListener(oo,l),window.addEventListener("storage",c),()=>{window.removeEventListener(oo,l),window.removeEventListener("storage",c)}},[]);const a=i.useCallback(l=>{n(l)},[n]),o=i.useCallback(()=>{n(!r.current)},[n]);return{isVisible:e,setVisibility:a,toggleVisibility:o}}var sh=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function rh(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function yt(e,t){if(rh(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":sh.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 Mn(e){return yt(e)==="generating"}function Fi(e,t){return yt(e,t)==="waiting_approval"}function ct(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function nh(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 da(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Vn(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 ah(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 oh(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function ih(e){return ah(e.trim().replace(/\.local$/i,""))}function lh(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function Rc(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(l=>typeof l=="string"&&l.trim().length>0&&!oh(l));if(r&&r!=="Unknown")return ih(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function At(e,t={}){return lh(e)||Rc(e,t)}function Pc(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 Dc(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 Cs(e,t){return Pc(e).join(" · ")}function _r(e){return e.transport==="pty"}function Fs(e){return e.transport==="acp"}function ch(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:ct(e)}function Wi(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),l=ct(r||"").trim().toLowerCase();return n===a||n===o||n===l}function dh(e,t=[],r=[]){var d,m,u,h;const n=yt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal});if(n==="waiting_approval")return"waiting_approval";if(n==="generating")return"generating";const a=t.find(x=>Fi(x.status,{activeModal:x.activeModal})||Mn(x.status));if(a)return yt(a.status,{activeModal:a.activeModal});const o=r.find(x=>Fi(x.status,{activeModal:x.activeModal})||Mn(x.status));if(o)return yt(o.status,{activeModal:o.activeModal});if(n&&n!=="idle")return n;const l=yt((d=t[0])==null?void 0:d.status,{activeModal:(m=t[0])==null?void 0:m.activeModal});if(l!=="idle")return l;const c=yt((u=r[0])==null?void 0:u.status,{activeModal:(h=r[0])==null?void 0:h.activeModal});return c!=="idle"?c:"idle"}function uh(e){return yt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function mh(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of e){const a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),o=t.get(a),l=yt(n.status);if(!o){t.set(a,{...n,status:l});continue}const c=r.indexOf(o.status||"idle"),d=r.indexOf(l||"idle");d>=0&&(c<0||d<c)&&t.set(a,{...n,status:l})}return Array.from(t.values())}function ph(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 hh(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&&ph(t.receivedAt)||0}function fh(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function io(e){return Math.max(fh(e),hh(e.activeChat))}function xh(e,t,r,n,a,o){const l=t-e;if(l!==0)return l;const c=r.localeCompare(n);return c!==0?c:a.localeCompare(o)}function Fo(e,t){return xh(io(e),io(t),At(e,{fallbackId:e.id}),At(t,{fallbackId:t.id}),e.id,t.id)}const Ec="adhdev_notification_prefs",Ki={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function bh(){try{const e=localStorage.getItem(Ec);if(e){const t=JSON.parse(e);return{...Ki,...t}}}catch{}return{...Ki}}function gh(e){try{localStorage.setItem(Ec,JSON.stringify(e))}catch{}}let Xt=bh(),hn=[];function yh(){hn.forEach(e=>e())}function vh(e){Xt={...Xt,...e},gh(Xt),yh()}function wh(){const[,e]=i.useState(0);i.useEffect(()=>{const r=()=>e(n=>n+1);return hn.push(r),()=>{hn=hn.filter(n=>n!==r)}},[]);const t=i.useCallback(r=>{vh(r)},[]);return[{...Xt},t]}function wr(e){if(!Xt.globalEnabled)return!1;switch(e){case"disconnect":return Xt.disconnectAlert;case"completion":return Xt.completionAlert;case"approval":return Xt.approvalAlert;case"browser":return Xt.browserNotifications;default:return!0}}const jh={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function $c(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Bc(){return"Notification"in window&&Notification.permission==="granted"}let ds=null;function kh(e){return e!==!1}async function Sh(){if(ds!==null)return ds;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return ds=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(ds=!!await e.pushManager.getSubscription(),ds):(ds=!1,!1)}catch{return ds=!1,!1}}function lo(e,t,r){if(Bc())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 Nh(e,t={}){const r={...jh,...t},n=i.useRef(new Map),a=i.useRef(0),[o,l]=i.useState(null);i.useEffect(()=>{let d=!1;return Sh().then(m=>{d||l(m)}),()=>{d=!0}},[]);const c=i.useCallback((d,m,u)=>{const h=Date.now();h-a.current<r.throttleMs||(a.current=h,lo(d,m,u))},[r.throttleMs]);i.useEffect(()=>{var d;if(!(!r.enabled||!Bc())&&wr("browser")&&!kh(o)){if(document.hasFocus()){for(const m of e)n.current.set(m.id,yt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const u=n.current.get(m.id),h=yt(m.status,{activeModal:m.activeModal}),x=m.name||m.id;if(r.onApproval&&wr("approval")&&h==="waiting_approval"&&u!=="waiting_approval"){const S=((d=m.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${x} — Approval needed`,S.slice(0,120),`approval-${m.id}`)}r.onComplete&&wr("completion")&&Mn(u)&&h==="idle"&&c(`✅ ${x} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&h==="error"&&u!=="error"&&c(`⚠️ ${x} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,h)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,c])}const Ch=/^(run|approve|accept|yes|allow|always)/,Ih=/^(run|approve|accept|yes|allow|always|proceed|save)/,Th=/^(reject|deny|delete|remove|abort|cancel|no)/;function Wo(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Mh(e){const t=Wo(e).toLowerCase();return Ch.test(t)?"primary":Th.test(t)?"danger":"default"}function Ah(e){return Ih.test(Wo(e).toLowerCase())?"approve":"reject"}function _h(e){return e.map((t,r)=>({label:Wo(t),variant:Mh(t),action:Ah(t),button:t,buttonIndex:r}))}function Lh(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Rh(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 Ph{constructor(){Ze(this,"dedupMap",new Map);Ze(this,"DEDUP_WINDOW_MS",5e3);Ze(this,"DEDUP_MAX_SIZE",50);Ze(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ze(this,"toastCallbacks",[]);Ze(this,"statusEventCallbacks",[]);Ze(this,"resolveActionFn",null);Ze(this,"viewRequestRespondFn",null);Ze(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(r=>r!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const r of this.toastCallbacks)r(t)}showToast(t,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:t,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(t){const r=Date.now(),n=this.dedupMap.get(t)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,o]of this.dedupMap)r-o>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(t){if(t.daemonId){const a=this.ides.find(o=>o.id===t.daemonId&&o.type==="adhdev-daemon");if(a)return a}const r=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const o=this.ides.find(l=>l.id===a&&l.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 b;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),o=n||t.daemonId||"",l=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),c=`${o}:${t.event}:${l}`;if(this.isDuplicate(c))return;for(const p of this.statusEventCallbacks)p(t);const d=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(d==null?void 0:d.type)||"";let u=ct(m);const h=this.resolveOwningDaemon(t);if(h){const p=At(h,{fallbackId:h.id});p&&(u=!m||m==="adhdev-daemon"?p:`${p}/${u}`)}let x="",S="info";if(t.event==="agent:generating_completed"){const p=t.duration?` (${t.duration}s)`:"";x=`✅ ${u} agent task completed${p}`,S="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(x=`⚡ ${u} approval needed`,S="warning",(b=t.modalButtons)!=null&&b.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(t);if(!p)return;const g=this.resolveActionFn,v=_h(t.modalButtons).map(I=>({label:I.label,variant:I.variant,onClick:()=>{g(p,"resolve_action",{action:I.action,button:I.button,buttonIndex:I.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),f=Lh(u,t.modalMessage,x),T=Date.now();this.emitToast({id:T,message:f,type:S,timestamp:T,targetKey:n||p,actions:v,duration:15e3}),x=""}}else if(t.event==="monitor:long_generating"){const p=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";x=`⚠️ ${u} agent is taking a long time${p}`,S="warning",wr("browser")&&!document.hasFocus()&&lo(`⚠️ ${u} — Long Running`,`Agent has been generating for over ${p.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const p=t.requesterName||"A team member",g=t.requestId,v=t.orgId;if(x=`👁️ ${p} wants to view your session`,S="warning",g&&v&&this.viewRequestRespondFn){const f=Date.now(),T=Rh(v,g,this.viewRequestRespondFn,(I,k)=>console.error(`[EventManager] ${I} view request failed:`,k));this.emitToast({id:f,message:x,type:S,timestamp:f,actions:T,duration:3e4}),x=""}wr("browser")&&!document.hasFocus()&&lo("👁️ View Request",`${p} wants to view your session`,`view-request-${g}`)}else t.event==="team:view_request_approved"?(x="✅ View request approved",S="success"):t.event==="team:view_request_rejected"&&(x=`❌ ${t.targetName||"Team member"} declined your view request`,S="warning");if(x){const p=Date.now();this.emitToast({id:p,message:x,type:S,timestamp:p,targetKey:n||t.daemonId,duration:5e3})}}}const it=new Ph,Hi=new Map;function An(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ws(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Gn(e){return An(e)?An(e.result)?e.result:e:null}function Dh(e){const t=Gn(e);return!t||!An(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function Xr(e){const t=Gn(e);return!t||!An(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function or(e){const t=Gn(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function Jr(e){const t=Gn(e);return!!t&&t.success===!1}function Eh(e){var t,r;for(const n of e||[]){if(n.type==="toast"&&((t=n.toast)!=null&&t.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";it.showToast(n.toast.message,a);continue}if(n.type==="notification"&&((r=n.notification)!=null&&r.body)){const a=n.notification.level==="warning"?"warning":n.notification.level==="success"?"success":"info";it.showToast(n.notification.body,a)}}}function $h(e,t){return e&&Ws(e.currentValue)?e.currentValue:t}function Bh(e,t){return Ws(t)?Ws(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Oh(e,t){var o,l;if((t.now??Date.now())<t.localOverrideUntil){const c=t.localValues[e];if(Ws(c))return c}const n=(o=t.controlValues)==null?void 0:o[e];if(Ws(n))return n;const a=(l=t.defaultValues)==null?void 0:l[e];return Ws(a)?a:void 0}function fn(e,t){return e.options||t[e.id]||[]}const Fh={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 Wh(e,t,r){var n;return((n=Fh[t])==null?void 0:n.has(r.id))===!0}function Ko(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Wh(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function ua(e,t){return{value:t}}function Kh(e,t,r){var a;return r?((a=fn(e,t).find(o=>o.value===r))==null?void 0:a.label)||r:""}const Hh={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Uh({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:l}){const{sendCommand:c}=jt(),d=`${e}:${t||n}`,m=Hh[n]||"#94a3b8",[u,h]=i.useState({}),x=i.useRef({}),S=i.useRef(l);x.current=u,S.current=l;const b=i.useRef(0),p={};for(const y of o||[])y.defaultValue!==void 0&&(p[y.id]=y.defaultValue);const g={...p,...l||{},...Date.now()<b.current?u:{}};i.useEffect(()=>{l&&Date.now()>b.current&&h({})},[l]);const[v,f]=i.useState(Hi.get(d)||{}),[T,I]=i.useState(null),[k,A]=i.useState(null),_=i.useCallback(async(y,F={})=>{const P={...F,...t&&{targetSessionId:t}};return await c(e,y,P)},[e,t,c]),N=i.useCallback(async(y,F={})=>{const P=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await _("invoke_provider_script",{...P,scriptName:y,...F})},[_,n,r,t]),w=i.useCallback((y,F,P)=>{const E=$h(P,F);h(G=>({...G,[y.id]:E})),Eh(P==null?void 0:P.effects)},[]),D=i.useCallback((y,F)=>{h(P=>{const E={...P};return F===void 0?delete E[y.id]:E[y.id]=F,E}),b.current=0},[]);if(!o||o.length===0)return null;const M=Ko(o,{hostIdeType:r,providerType:n});if(M.length===0)return null;const j=async y=>{if(T===y.id){I(null);return}if(fn(y,v).length>0){I(y.id);return}if(y.dynamic&&y.listScript){A(y.id);try{const P=await N(y.listScript,{}),E=Dh(P);if(!E){const ye=or(P);ye&&it.showToast(ye,"warning");return}const G=E.options;f(ye=>{const he={...ye,[y.id]:G};return Hi.set(d,he),he});const J=Oh(y.id,{localOverrideUntil:b.current,localValues:x.current,controlValues:S.current,defaultValues:p});if(Bh(J,E.currentValue)){const ye=E.currentValue;h(he=>({...he,[y.id]:ye}))}I(y.id)}catch(P){const E=P instanceof Error?P.message:`Could not load ${y.label}`;it.showToast(E,"warning")}finally{A(null)}}},W=async(y,F)=>{I(null);const P=(l==null?void 0:l[y.id])??p[y.id];h(E=>({...E,[y.id]:F})),b.current=Date.now()+5e3;try{if(!y.setScript)return;const E=await N(y.setScript,ua(y,F)),G=Xr(E);if(G&&!G.ok||Jr(E))throw new Error((G==null?void 0:G.error)||or(E)||`Could not update ${y.label}`);w(y,F,G)}catch(E){D(y,P);const G=E instanceof Error?E.message:`Could not update ${y.label}`;it.showToast(G,"warning")}},H=async y=>{const F=fn(y,v).map(he=>he.value);if(F.length===0)return;const P=String(g[y.id]||""),G=(F.indexOf(P)+1)%F.length,J=F[G];if(typeof J!="string")return;const ye=(l==null?void 0:l[y.id])??p[y.id];h(he=>({...he,[y.id]:J})),b.current=Date.now()+5e3;try{if(!y.setScript)return;const he=await N(y.setScript,ua(y,J)),ne=Xr(he);if(ne&&!ne.ok||Jr(he))throw new Error((ne==null?void 0:ne.error)||or(he)||`Could not update ${y.label}`);w(y,J,ne)}catch(he){D(y,ye);const ne=he instanceof Error?he.message:`Could not update ${y.label}`;it.showToast(ne,"warning")}},$=async y=>{const P=!g[y.id],E=(l==null?void 0:l[y.id])??p[y.id];h(G=>({...G,[y.id]:P})),b.current=Date.now()+5e3;try{if(!y.setScript)return;const G=await N(y.setScript,ua(y,P)),J=Xr(G);if(J&&!J.ok||Jr(G))throw new Error((J==null?void 0:J.error)||or(G)||`Could not update ${y.label}`);w(y,P,J)}catch(G){D(y,E);const J=G instanceof Error?G.message:`Could not update ${y.label}`;it.showToast(J,"warning")}},C=async y=>{if(!y.invokeScript)return;if(y.confirmMessage){const P=[y.confirmTitle,y.confirmMessage,y.confirmLabel].filter(G=>typeof G=="string"&&G.trim().length>0);if(!window.confirm(P.join(`
|
|
29
|
+
`})]})}function Un(e,t={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=t,o=Date.now()-e,l=Math.floor(o/1e3);if(l<a)return n;const c=Math.floor(l/60);if(c<60)return`${c}m${r}`;const d=Math.floor(c/60);if(d<24)return`${d}h${r}`;const m=Math.floor(d/24);return m<7?`${m}d${r}`:new Date(e).toLocaleDateString()}const Lc=e=>Un(e);function Qp(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 Qs(e){const t=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating",a=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:r,isGenerating:n,isWaiting:a}}function Zp(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...Qp(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 Tn(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 zn(e,t,r){const n=Tn(e,t),a=Qs(e),o=a.isReconnecting,l=a.isConnecting,c=a.isGenerating,d=a.isWaiting,m=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||d,u=n.inboxBucket==="working"||c,x=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:x,requiresAction:m,isWorking:u,isReconnecting:o,isConnecting:l,isGenerating:c,isWaiting:d,inboxBucket:m?"needs_attention":u?"working":x?"task_complete":"idle"}}function eh(e,t,r){return zn(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Rc({activeConv:e,onModalButton:t}){const[r,n]=i.useState(null);if(i.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Qs(e).isWaiting||!e.modalButtons)return null;const o=c=>{r||(n(c),t(c))},l=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(Ar,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((c,d)=>{const m=l(c).toLowerCase(),u=/^(run|approve|accept|yes|allow|always)/.test(m),h=/^(reject|deny|delete|remove|abort)/.test(m),x=r===c,S=r!==null;return s.jsx("button",{onClick:()=>o(c),disabled:S,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${u?"font-extrabold":h?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${S&&!x?"opacity-40":"opacity-100"} ${S?"cursor-not-allowed":"cursor-pointer"}`,style:u?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:h?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:x?"⏳ ...":l(c)},d)})})]})]})}const Bo="adhdev_controls_bar_visible",oo="adhdev:controlsbarvisibilitychange";function ca(e){if(!e)return!1;try{return e.getItem(Bo)==="1"}catch{return!1}}function th(e,t){if(t)try{t.setItem(Bo,e?"1":"0")}catch{}}function sh(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(oo,{detail:{visible:e}}))}function Oo(){const[e,t]=i.useState(()=>typeof window>"u"?!1:ca(window.localStorage)),r=i.useRef(e),n=i.useCallback((l,c=!0)=>{r.current=l,t(l),typeof window<"u"&&th(l,window.localStorage),c&&sh(l)},[]);i.useEffect(()=>{const l=d=>{const m=d.detail,u=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:ca(window.localStorage);r.current=u,t(u)},c=d=>{if(d.key!==Bo)return;const m=ca(window.localStorage);r.current=m,t(m)};return window.addEventListener(oo,l),window.addEventListener("storage",c),()=>{window.removeEventListener(oo,l),window.removeEventListener("storage",c)}},[]);const a=i.useCallback(l=>{n(l)},[n]),o=i.useCallback(()=>{n(!r.current)},[n]);return{isVisible:e,setVisibility:a,toggleVisibility:o}}var rh=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function nh(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function yt(e,t){if(nh(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":rh.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 Mn(e){return yt(e)==="generating"}function Fi(e,t){return yt(e,t)==="waiting_approval"}function ct(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function ah(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 da(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Vn(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 oh(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 ih(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function lh(e){return oh(e.trim().replace(/\.local$/i,""))}function ch(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function Pc(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(l=>typeof l=="string"&&l.trim().length>0&&!ih(l));if(r&&r!=="Unknown")return lh(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function At(e,t={}){return ch(e)||Pc(e,t)}function Dc(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 Ec(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 Cs(e,t){return Dc(e).join(" · ")}function _r(e){return e.transport==="pty"}function Fs(e){return e.transport==="acp"}function dh(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:ct(e)}function Wi(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),l=ct(r||"").trim().toLowerCase();return n===a||n===o||n===l}function uh(e,t=[],r=[]){var d,m,u,h;const n=yt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal});if(n==="waiting_approval")return"waiting_approval";if(n==="generating")return"generating";const a=t.find(x=>Fi(x.status,{activeModal:x.activeModal})||Mn(x.status));if(a)return yt(a.status,{activeModal:a.activeModal});const o=r.find(x=>Fi(x.status,{activeModal:x.activeModal})||Mn(x.status));if(o)return yt(o.status,{activeModal:o.activeModal});if(n&&n!=="idle")return n;const l=yt((d=t[0])==null?void 0:d.status,{activeModal:(m=t[0])==null?void 0:m.activeModal});if(l!=="idle")return l;const c=yt((u=r[0])==null?void 0:u.status,{activeModal:(h=r[0])==null?void 0:h.activeModal});return c!=="idle"?c:"idle"}function mh(e){return yt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function ph(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of e){const a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),o=t.get(a),l=yt(n.status);if(!o){t.set(a,{...n,status:l});continue}const c=r.indexOf(o.status||"idle"),d=r.indexOf(l||"idle");d>=0&&(c<0||d<c)&&t.set(a,{...n,status:l})}return Array.from(t.values())}function hh(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 fh(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&&hh(t.receivedAt)||0}function xh(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function io(e){return Math.max(xh(e),fh(e.activeChat))}function bh(e,t,r,n,a,o){const l=t-e;if(l!==0)return l;const c=r.localeCompare(n);return c!==0?c:a.localeCompare(o)}function Fo(e,t){return bh(io(e),io(t),At(e,{fallbackId:e.id}),At(t,{fallbackId:t.id}),e.id,t.id)}const $c="adhdev_notification_prefs",Ki={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function gh(){try{const e=localStorage.getItem($c);if(e){const t=JSON.parse(e);return{...Ki,...t}}}catch{}return{...Ki}}function yh(e){try{localStorage.setItem($c,JSON.stringify(e))}catch{}}let Xt=gh(),hn=[];function vh(){hn.forEach(e=>e())}function wh(e){Xt={...Xt,...e},yh(Xt),vh()}function jh(){const[,e]=i.useState(0);i.useEffect(()=>{const r=()=>e(n=>n+1);return hn.push(r),()=>{hn=hn.filter(n=>n!==r)}},[]);const t=i.useCallback(r=>{wh(r)},[]);return[{...Xt},t]}function wr(e){if(!Xt.globalEnabled)return!1;switch(e){case"disconnect":return Xt.disconnectAlert;case"completion":return Xt.completionAlert;case"approval":return Xt.approvalAlert;case"browser":return Xt.browserNotifications;default:return!0}}const kh={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Bc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Oc(){return"Notification"in window&&Notification.permission==="granted"}let ds=null;function Sh(e){return e!==!1}async function Nh(){if(ds!==null)return ds;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return ds=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(ds=!!await e.pushManager.getSubscription(),ds):(ds=!1,!1)}catch{return ds=!1,!1}}function lo(e,t,r){if(Oc())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 Ch(e,t={}){const r={...kh,...t},n=i.useRef(new Map),a=i.useRef(0),[o,l]=i.useState(null);i.useEffect(()=>{let d=!1;return Nh().then(m=>{d||l(m)}),()=>{d=!0}},[]);const c=i.useCallback((d,m,u)=>{const h=Date.now();h-a.current<r.throttleMs||(a.current=h,lo(d,m,u))},[r.throttleMs]);i.useEffect(()=>{var d;if(!(!r.enabled||!Oc())&&wr("browser")&&!Sh(o)){if(document.hasFocus()){for(const m of e)n.current.set(m.id,yt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const u=n.current.get(m.id),h=yt(m.status,{activeModal:m.activeModal}),x=m.name||m.id;if(r.onApproval&&wr("approval")&&h==="waiting_approval"&&u!=="waiting_approval"){const S=((d=m.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${x} — Approval needed`,S.slice(0,120),`approval-${m.id}`)}r.onComplete&&wr("completion")&&Mn(u)&&h==="idle"&&c(`✅ ${x} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&h==="error"&&u!=="error"&&c(`⚠️ ${x} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,h)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,c])}const Ih=/^(run|approve|accept|yes|allow|always)/,Th=/^(run|approve|accept|yes|allow|always|proceed|save)/,Mh=/^(reject|deny|delete|remove|abort|cancel|no)/;function Wo(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Ah(e){const t=Wo(e).toLowerCase();return Ih.test(t)?"primary":Mh.test(t)?"danger":"default"}function _h(e){return Th.test(Wo(e).toLowerCase())?"approve":"reject"}function Lh(e){return e.map((t,r)=>({label:Wo(t),variant:Ah(t),action:_h(t),button:t,buttonIndex:r}))}function Rh(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Ph(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 Dh{constructor(){Ze(this,"dedupMap",new Map);Ze(this,"DEDUP_WINDOW_MS",5e3);Ze(this,"DEDUP_MAX_SIZE",50);Ze(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ze(this,"toastCallbacks",[]);Ze(this,"statusEventCallbacks",[]);Ze(this,"resolveActionFn",null);Ze(this,"viewRequestRespondFn",null);Ze(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(r=>r!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const r of this.toastCallbacks)r(t)}showToast(t,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:t,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(t){const r=Date.now(),n=this.dedupMap.get(t)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,o]of this.dedupMap)r-o>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(t){if(t.daemonId){const a=this.ides.find(o=>o.id===t.daemonId&&o.type==="adhdev-daemon");if(a)return a}const r=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const o=this.ides.find(l=>l.id===a&&l.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 b;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),o=n||t.daemonId||"",l=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),c=`${o}:${t.event}:${l}`;if(this.isDuplicate(c))return;for(const p of this.statusEventCallbacks)p(t);const d=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(d==null?void 0:d.type)||"";let u=ct(m);const h=this.resolveOwningDaemon(t);if(h){const p=At(h,{fallbackId:h.id});p&&(u=!m||m==="adhdev-daemon"?p:`${p}/${u}`)}let x="",S="info";if(t.event==="agent:generating_completed"){const p=t.duration?` (${t.duration}s)`:"";x=`✅ ${u} agent task completed${p}`,S="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(x=`⚡ ${u} approval needed`,S="warning",(b=t.modalButtons)!=null&&b.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(t);if(!p)return;const g=this.resolveActionFn,v=Lh(t.modalButtons).map(T=>({label:T.label,variant:T.variant,onClick:()=>{g(p,"resolve_action",{action:T.action,button:T.button,buttonIndex:T.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),f=Rh(u,t.modalMessage,x),C=Date.now();this.emitToast({id:C,message:f,type:S,timestamp:C,targetKey:n||p,actions:v,duration:15e3}),x=""}}else if(t.event==="monitor:long_generating"){const p=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";x=`⚠️ ${u} agent is taking a long time${p}`,S="warning",wr("browser")&&!document.hasFocus()&&lo(`⚠️ ${u} — Long Running`,`Agent has been generating for over ${p.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const p=t.requesterName||"A team member",g=t.requestId,v=t.orgId;if(x=`👁️ ${p} wants to view your session`,S="warning",g&&v&&this.viewRequestRespondFn){const f=Date.now(),C=Ph(v,g,this.viewRequestRespondFn,(T,k)=>console.error(`[EventManager] ${T} view request failed:`,k));this.emitToast({id:f,message:x,type:S,timestamp:f,actions:C,duration:3e4}),x=""}wr("browser")&&!document.hasFocus()&&lo("👁️ View Request",`${p} wants to view your session`,`view-request-${g}`)}else t.event==="team:view_request_approved"?(x="✅ View request approved",S="success"):t.event==="team:view_request_rejected"&&(x=`❌ ${t.targetName||"Team member"} declined your view request`,S="warning");if(x){const p=Date.now();this.emitToast({id:p,message:x,type:S,timestamp:p,targetKey:n||t.daemonId,duration:5e3})}}}const it=new Dh,Hi=new Map;function An(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ws(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Gn(e){return An(e)?An(e.result)?e.result:e:null}function Eh(e){const t=Gn(e);return!t||!An(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function Xr(e){const t=Gn(e);return!t||!An(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function or(e){const t=Gn(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function Jr(e){const t=Gn(e);return!!t&&t.success===!1}function $h(e){var t,r;for(const n of e||[]){if(n.type==="toast"&&((t=n.toast)!=null&&t.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";it.showToast(n.toast.message,a);continue}if(n.type==="notification"&&((r=n.notification)!=null&&r.body)){const a=n.notification.level==="warning"?"warning":n.notification.level==="success"?"success":"info";it.showToast(n.notification.body,a)}}}function Bh(e,t){return e&&Ws(e.currentValue)?e.currentValue:t}function Oh(e,t){return Ws(t)?Ws(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Fh(e,t){var o,l;if((t.now??Date.now())<t.localOverrideUntil){const c=t.localValues[e];if(Ws(c))return c}const n=(o=t.controlValues)==null?void 0:o[e];if(Ws(n))return n;const a=(l=t.defaultValues)==null?void 0:l[e];return Ws(a)?a:void 0}function fn(e,t){return e.options||t[e.id]||[]}const Wh={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 Kh(e,t,r){var n;return((n=Wh[t])==null?void 0:n.has(r.id))===!0}function Ko(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Kh(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function ua(e,t){return{value:t}}function Hh(e,t,r){var a;return r?((a=fn(e,t).find(o=>o.value===r))==null?void 0:a.label)||r:""}const Uh={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function zh({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:l}){const{sendCommand:c}=jt(),d=`${e}:${t||n}`,m=Uh[n]||"#94a3b8",[u,h]=i.useState({}),x=i.useRef({}),S=i.useRef(l);x.current=u,S.current=l;const b=i.useRef(0),p={};for(const y of o||[])y.defaultValue!==void 0&&(p[y.id]=y.defaultValue);const g={...p,...l||{},...Date.now()<b.current?u:{}};i.useEffect(()=>{l&&Date.now()>b.current&&h({})},[l]);const[v,f]=i.useState(Hi.get(d)||{}),[C,T]=i.useState(null),[k,A]=i.useState(null),_=i.useCallback(async(y,F={})=>{const P={...F,...t&&{targetSessionId:t}};return await c(e,y,P)},[e,t,c]),N=i.useCallback(async(y,F={})=>{const P=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await _("invoke_provider_script",{...P,scriptName:y,...F})},[_,n,r,t]),w=i.useCallback((y,F,P)=>{const E=Bh(P,F);h(G=>({...G,[y.id]:E})),$h(P==null?void 0:P.effects)},[]),D=i.useCallback((y,F)=>{h(P=>{const E={...P};return F===void 0?delete E[y.id]:E[y.id]=F,E}),b.current=0},[]);if(!o||o.length===0)return null;const M=Ko(o,{hostIdeType:r,providerType:n});if(M.length===0)return null;const j=async y=>{if(C===y.id){T(null);return}if(fn(y,v).length>0){T(y.id);return}if(y.dynamic&&y.listScript){A(y.id);try{const P=await N(y.listScript,{}),E=Eh(P);if(!E){const ye=or(P);ye&&it.showToast(ye,"warning");return}const G=E.options;f(ye=>{const he={...ye,[y.id]:G};return Hi.set(d,he),he});const J=Fh(y.id,{localOverrideUntil:b.current,localValues:x.current,controlValues:S.current,defaultValues:p});if(Oh(J,E.currentValue)){const ye=E.currentValue;h(he=>({...he,[y.id]:ye}))}T(y.id)}catch(P){const E=P instanceof Error?P.message:`Could not load ${y.label}`;it.showToast(E,"warning")}finally{A(null)}}},W=async(y,F)=>{T(null);const P=(l==null?void 0:l[y.id])??p[y.id];h(E=>({...E,[y.id]:F})),b.current=Date.now()+5e3;try{if(!y.setScript)return;const E=await N(y.setScript,ua(y,F)),G=Xr(E);if(G&&!G.ok||Jr(E))throw new Error((G==null?void 0:G.error)||or(E)||`Could not update ${y.label}`);w(y,F,G)}catch(E){D(y,P);const G=E instanceof Error?E.message:`Could not update ${y.label}`;it.showToast(G,"warning")}},H=async y=>{const F=fn(y,v).map(he=>he.value);if(F.length===0)return;const P=String(g[y.id]||""),G=(F.indexOf(P)+1)%F.length,J=F[G];if(typeof J!="string")return;const ye=(l==null?void 0:l[y.id])??p[y.id];h(he=>({...he,[y.id]:J})),b.current=Date.now()+5e3;try{if(!y.setScript)return;const he=await N(y.setScript,ua(y,J)),ne=Xr(he);if(ne&&!ne.ok||Jr(he))throw new Error((ne==null?void 0:ne.error)||or(he)||`Could not update ${y.label}`);w(y,J,ne)}catch(he){D(y,ye);const ne=he instanceof Error?he.message:`Could not update ${y.label}`;it.showToast(ne,"warning")}},$=async y=>{const P=!g[y.id],E=(l==null?void 0:l[y.id])??p[y.id];h(G=>({...G,[y.id]:P})),b.current=Date.now()+5e3;try{if(!y.setScript)return;const G=await N(y.setScript,ua(y,P)),J=Xr(G);if(J&&!J.ok||Jr(G))throw new Error((J==null?void 0:J.error)||or(G)||`Could not update ${y.label}`);w(y,P,J)}catch(G){D(y,E);const J=G instanceof Error?G.message:`Could not update ${y.label}`;it.showToast(J,"warning")}},I=async y=>{if(!y.invokeScript)return;if(y.confirmMessage){const P=[y.confirmTitle,y.confirmMessage,y.confirmLabel].filter(G=>typeof G=="string"&&G.trim().length>0);if(!window.confirm(P.join(`
|
|
30
30
|
|
|
31
|
-
`)))return}const F=(l==null?void 0:l[y.id])??p[y.id];try{const P=await N(y.invokeScript),E=Xr(P);if(E&&!E.ok||Jr(P))throw new Error((E==null?void 0:E.error)||or(P)||`Could not run ${y.label}`);E&&w(y,F??!0,E)}catch(P){D(y,F);const E=P instanceof Error?P.message:`Could not run ${y.label}`;it.showToast(E,"warning")}};return s.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${m}33`,background:`${m}12`,color:m},children:a}),M.map(y=>{const F=String(g[y.id]||""),P=Kh(y,v,F),E=T===y.id,G=k===y.id,J=fn(y,v),ye="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(y.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${ye} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:E?`${m}55`:"var(--border-default)",background:E?`${m}10`:"var(--surface-tertiary)",color:F?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void j(y),title:y.label,children:[y.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:y.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:G?"Loading…":P||y.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),E&&J.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>I(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:y.label}),J.map(he=>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:he.value===F?`${m}14`:"transparent",color:he.value===F?"var(--text-primary)":"var(--text-secondary)",borderLeft:he.value===F?`2px solid ${m}`:"2px solid transparent"},title:he.description||he.label,onMouseEnter:ne=>{ne.currentTarget.style.background=`${m}10`},onMouseLeave:ne=>{ne.currentTarget.style.background=he.value===F?`${m}14`:"transparent"},onClick:()=>void W(y,he.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:he.label}),he.value===F&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},he.value))]})]})]},y.id);case"cycle":return s.jsxs("button",{type:"button",className:`${ye} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:F?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void H(y),title:`Click to cycle: ${J.map(he=>he.label).join(" → ")}`,children:[y.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:y.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:P||y.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},y.id);case"toggle":return s.jsxs("button",{type:"button",className:`${ye} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:F?`${m}44`:"var(--border-default)",background:F?`${m}14`:"var(--surface-tertiary)",color:F?m:"var(--text-muted)"},onClick:()=>void $(y),"aria-pressed":!!F,children:[y.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:y.icon}),y.label]},y.id);case"action":return s.jsxs("button",{type:"button",className:`${ye} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void C(y),children:[y.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:y.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:y.resultDisplay==="inline"&&F?`${y.label}: ${F}`:y.label})]},y.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:F?"var(--text-primary)":"var(--text-muted)"},children:[y.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:y.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:F?`${y.label}: ${F}`:y.label})]},y.id);default:return null}})]})})}function zh({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:l,controls:c,controlValues:d}){const{isVisible:m}=Oo(),u=Ko(c,{hostIdeType:a,providerType:o});return!e||t||u.length===0||!m?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(Uh,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:l,controls:u,controlValues:d})})}const ir=5,Oc=10*1024*1024;function Vh({hasDraft:e,isBusy:t=!1}){return!e||t}function Gh(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 qh(e){if(e.size>Oc)return null;const t=await Gh(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 Yh(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const Fc=i.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:o=null,onSend:l,isActive:c=!0,showControlsToggle:d=!1,animateVisibility:m=!0,onControlsToggle:u,messageInput:h}){const x=i.useRef(null),S=i.useRef(null),[b,p]=i.useState(""),[g,v]=i.useState([]),[f,T]=i.useState(null),[I,k]=i.useState(!1),A=i.useRef(!1),{isVisible:_,toggleVisibility:N}=Oo(),w=Yh(h),D=!!b.trim()||g.length>0;i.useEffect(()=>{p(""),v([]),T(null)},[t]),i.useEffect(()=>{var y;c&&((y=x.current)==null||y.focus({preventScroll:!0}))},[t,c]);const M=i.useCallback(async y=>{T(null);const F=Array.from(y).filter(he=>he.type.startsWith("image/"));if(F.length===0)return;const P=ir-g.length;if(P<=0){T(`Max ${ir} images`);return}const E=F.slice(0,P);if(E.filter(he=>he.size>Oc).length>0){T("Image too large (max 10 MB)");return}const ye=(await Promise.all(E.map(qh))).filter(he=>he!==null);v(he=>[...he,...ye])},[g.length]),j=i.useCallback(y=>{v(F=>F.filter((P,E)=>E!==y))},[]),W=i.useCallback(async()=>{const y=b.trim();if(!y&&g.length===0||a||A.current)return;A.current=!0;const F=g.length>0?[...g]:void 0;try{await l(y,F)!==!1&&(p(""),v([]),T(null))}finally{A.current=!1}},[b,g,a,l]),H=i.useCallback(y=>{w&&(y.preventDefault(),k(!0))},[w]),$=i.useCallback(()=>k(!1),[]),C=i.useCallback(y=>{w&&(y.preventDefault(),k(!1),y.dataTransfer.files.length>0&&M(y.dataTransfer.files))},[w,M]);return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",m?"transition-all duration-200 ease-out":"",I?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:c?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:c?200:0,opacity:c?1:0,transform:c?"translateY(0)":"translateY(10px)",padding:c?"10px 12px":"0 12px",pointerEvents:c?"auto":"none"},"aria-hidden":!c,onDragOver:H,onDragLeave:$,onDrop:C,children:[g.length>0&&s.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:g.map((y,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:y.previewUrl,alt:y.name,className:"w-full h-full object-cover"}),s.jsx("button",{type:"button",onClick:()=>j(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 ${y.name}`,children:"✕"})]},F))}),s.jsxs("div",{className:"flex gap-2 items-center",title:c?`Send message to ${r}`:void 0,children:[d&&s.jsx("button",{type:"button",onClick:()=>{N(),u==null||u()},"aria-label":_?"Hide controls":"Show controls","aria-pressed":_,title:_?"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"})]})}),w&&s.jsxs(s.Fragment,{children:[s.jsx("input",{ref:S,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:y=>{y.target.files&&M(y.target.files),y.target.value=""}}),s.jsx("button",{type:"button",onClick:()=>{var y;return(y=S.current)==null?void 0:y.click()},disabled:g.length>=ir,title:g.length>=ir?`Max ${ir} 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("input",{ref:x,type:"text",placeholder:o||(w&&g.length>0?"Add a message (optional)...":`Send message to ${r}...`),value:b,onChange:y=>p(y.target.value),onPaste:y=>{if(w&&y.clipboardData.files.length>0&&Array.from(y.clipboardData.files).some(E=>E.type.startsWith("image/"))){y.preventDefault(),M(y.clipboardData.files);return}const F=y.clipboardData.getData("text");F&&p(P=>P+F),y.preventDefault()},onKeyDown:y=>{if(y.key==="Enter"){if(y.nativeEvent.isComposing){y.preventDefault();return}y.preventDefault(),W()}},className:"w-full h-10 rounded-[20px] px-4 bg-bg-secondary text-sm text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),s.jsx("button",{onClick:()=>{W()},disabled:Vh({hasDraft:D,isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${D&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:D&&!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:D?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),(f||w&&I)&&s.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${f?"text-red-400":"text-[var(--accent-primary)]"}`,children:f||"Drop image here"}),o&&!f&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:o})]})}),at=e=>e.transport==="pty",Zs=(e,t)=>at(e)?e.mode||"terminal":"chat",Wc=(e,t)=>at(e)&&Zs(e)==="terminal",st=e=>e.transport==="acp",Xh=180;function ls(e){return e.streamSource!=="agent-stream"}function _s(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function Kc(e){return e.machineName||""}function Dr(e){return _s(e)}function Gt(e){return e.agentType||""}function _n(e){return e.hostIdeType||""}function Ho(e){return e.displayPrimary||e.agentName||"Agent"}function Hc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function Jh(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Uc(e){const t=Jh(e),r=Us(t==null?void 0:t.content),n=Us(e.lastMessagePreview);return r||n||""}function Qh(e,t=Xh){const r=Us(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 Zh(e){return Qh(Uc(e)||e.displaySecondary||"")}function zc(e){return[e.displaySecondary,Kc(e)].filter(Boolean)}function Vs(e){return e.agentName||ct(Gt(e))}function ef(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 ct(_n(e)||Gt(e))}function Vc(e){return ls(e)?e.sessionId:e.nativeSessionId}function Ui(e){return ls(e)?"native":e.tabKey}function tf(e){return e.sessionId}function sf(e,t){if(t)return ls(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function rf(e,t){const r=Gt(e),n=ls(e),a=at(e)||st(e),o=n?a?Vs(e)||(t==null?void 0:t.cliName)||ct(_n(e)||r):t!=null&&t.type?ct(t.type):ct(_n(e)||r):Vs(e);return{isNativeConversation:n,isCli:at(e),isAcp:st(e),isCliTerminal:Wc(e),providerType:r,displayLabel:o,targetEntry:sf(e,t)}}function xs(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:at(e)||st(e)?{agentType:Gt(e)}:e.streamSource==="agent-stream"?{agentType:Gt(e)}:t}function Gs(e){return e?Dr(e):""}function lr(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function Uo(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function nf(e){const t=e instanceof Error?e.message:String(e||""),r=t.toLowerCase();return r.includes("still processing the previous prompt")?"Wait for the current reply to finish before sending another message.":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 Gc(){return"select_session"}function af(){return"open_panel"}function of({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function lf(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function zi(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Ln(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function zo(e){return e instanceof Error?e.message:String(e||"")}function Vi(e){const t=zo(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Gi(e,t){const r=zo(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function cf(e,t,r){const n=xs(r);if(!t||t.length===0)return{message:e,...n};const a=t.map(o=>({type:"image",mimeType:o.mimeType,data:o.data,alt:o.name}));return e&&a.push({type:"text",text:e}),{message:e,input:{parts:a,textFallback:e},...n}}function qn({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,o]=i.useState(!1),[l,c]=i.useState(!1),[d,m]=i.useState(null),u=i.useRef(!1),h=i.useRef(null);i.useEffect(()=>{m(null)},[t==null?void 0:t.tabKey]);const x=i.useCallback(async(g,v)=>{if(!t||u.current)return!1;const f=g.trim(),T=Uo(t);if(of({hasMessage:!!f,blockedMessage:T,sendInFlight:u.current}))return T&&m(T),!1;const I=Date.now(),k={tabKey:t.tabKey,message:f,timestamp:I};if(lf(h.current,k))return m(null),!0;u.current=!0,c(!0),m(null),h.current=k;try{const A=Gs(t);if(!A)return h.current=zi(h.current,k),m("Unable to send message right now."),!1;const _=await e(A,"send_chat",cf(f,v,t)),N=Ln(_);if(N!=null&&N.deduplicated)return m(null),!0;if((N==null?void 0:N.sent)===!1)throw new Error((N==null?void 0:N.error)||"Send failed");if((N==null?void 0:N.success)===!1)throw new Error((N==null?void 0:N.error)||"Send failed");return m(null),!0}catch(A){const _=zo(A);return _.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",_):console.warn("Send blocked/failed",A),h.current=zi(h.current,k),m(nf(A)),!1}finally{u.current=!1,c(!1)}},[t,e]),S=i.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(g){console.error("Relaunch failed",g)}},[t,e]),b=i.useCallback(async g=>{if(t)try{const f=(t.modalButtons||[]).indexOf(g),T=g.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),I=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(T),k=Gs(t);if(!k)return;const A=await e(k,"resolve_action",{button:g,action:I?"approve":"reject",...f>=0&&{buttonIndex:f},...xs(t)}),_=Ln(A);_.success||r(N=>[...N,{routeId:t.tabKey,text:Gi(g,_==null?void 0:_.error),timestamp:Date.now()}])}catch(v){Vi(v)||console.error("[ModalButton] Error:",v),r(f=>[...f,{routeId:t.tabKey,text:Vi(v)?Gi(g,v):`❌ **${g}** error`,timestamp:Date.now()}])}},[t,e,r]),p=i.useCallback(async()=>{if(!(!t||a)){o(!0);try{await e(t.routeId,af(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(g){console.error("Focus agent failed",g)}finally{o(!1)}}},[t,a,e]);return{isSendingChat:l,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:x,handleRelaunch:S,handleModalButton:b,handleFocusAgent:p}}const df=10,uf=8e3,mf=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function pf(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 co(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(mf.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=pf(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=>co(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,co(a,n,r+1)]))}function cr(e,t){return Array.isArray(e)?e.slice(-t):[]}function hf(e,t=Date.now()){const r=e&&t-e.firstAt<=uf,n=r?e.count+1:1;return n>=df?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function qc(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:cr(e.chatTailState.liveMessages??t.messages,10),activeConversationMessagesTail:cr(t.messages,10),visibleMessagesTail:cr(e.visibleMessages,5),historyMessagesTail:cr(e.chatTailState.historyMessages,5),actionLogsTail:cr(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 co(r)}function Yc(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 Xc(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 Jc(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(`
|
|
31
|
+
`)))return}const F=(l==null?void 0:l[y.id])??p[y.id];try{const P=await N(y.invokeScript),E=Xr(P);if(E&&!E.ok||Jr(P))throw new Error((E==null?void 0:E.error)||or(P)||`Could not run ${y.label}`);E&&w(y,F??!0,E)}catch(P){D(y,F);const E=P instanceof Error?P.message:`Could not run ${y.label}`;it.showToast(E,"warning")}};return s.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${m}33`,background:`${m}12`,color:m},children:a}),M.map(y=>{const F=String(g[y.id]||""),P=Hh(y,v,F),E=C===y.id,G=k===y.id,J=fn(y,v),ye="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(y.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${ye} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:E?`${m}55`:"var(--border-default)",background:E?`${m}10`:"var(--surface-tertiary)",color:F?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void j(y),title:y.label,children:[y.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:y.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:G?"Loading…":P||y.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),E&&J.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>T(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:y.label}),J.map(he=>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:he.value===F?`${m}14`:"transparent",color:he.value===F?"var(--text-primary)":"var(--text-secondary)",borderLeft:he.value===F?`2px solid ${m}`:"2px solid transparent"},title:he.description||he.label,onMouseEnter:ne=>{ne.currentTarget.style.background=`${m}10`},onMouseLeave:ne=>{ne.currentTarget.style.background=he.value===F?`${m}14`:"transparent"},onClick:()=>void W(y,he.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:he.label}),he.value===F&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},he.value))]})]})]},y.id);case"cycle":return s.jsxs("button",{type:"button",className:`${ye} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:F?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void H(y),title:`Click to cycle: ${J.map(he=>he.label).join(" → ")}`,children:[y.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:y.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:P||y.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},y.id);case"toggle":return s.jsxs("button",{type:"button",className:`${ye} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:F?`${m}44`:"var(--border-default)",background:F?`${m}14`:"var(--surface-tertiary)",color:F?m:"var(--text-muted)"},onClick:()=>void $(y),"aria-pressed":!!F,children:[y.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:y.icon}),y.label]},y.id);case"action":return s.jsxs("button",{type:"button",className:`${ye} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void I(y),children:[y.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:y.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:y.resultDisplay==="inline"&&F?`${y.label}: ${F}`:y.label})]},y.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:F?"var(--text-primary)":"var(--text-muted)"},children:[y.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:y.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:F?`${y.label}: ${F}`:y.label})]},y.id);default:return null}})]})})}function Vh({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:l,controls:c,controlValues:d}){const{isVisible:m}=Oo(),u=Ko(c,{hostIdeType:a,providerType:o});return!e||t||u.length===0||!m?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(zh,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:l,controls:u,controlValues:d})})}const ir=5,Fc=10*1024*1024;function Gh({hasDraft:e,isBusy:t=!1}){return!e||t}function qh(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 Yh(e){if(e.size>Fc)return null;const t=await qh(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 Xh(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const Wc=i.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:o=null,onSend:l,isActive:c=!0,showControlsToggle:d=!1,animateVisibility:m=!0,onControlsToggle:u,messageInput:h}){const x=i.useRef(null),S=i.useRef(null),[b,p]=i.useState(""),[g,v]=i.useState([]),[f,C]=i.useState(null),[T,k]=i.useState(!1),A=i.useRef(!1),{isVisible:_,toggleVisibility:N}=Oo(),w=Xh(h),D=!!b.trim()||g.length>0;i.useEffect(()=>{p(""),v([]),C(null)},[t]),i.useEffect(()=>{var y;c&&((y=x.current)==null||y.focus({preventScroll:!0}))},[t,c]);const M=i.useCallback(async y=>{C(null);const F=Array.from(y).filter(he=>he.type.startsWith("image/"));if(F.length===0)return;const P=ir-g.length;if(P<=0){C(`Max ${ir} images`);return}const E=F.slice(0,P);if(E.filter(he=>he.size>Fc).length>0){C("Image too large (max 10 MB)");return}const ye=(await Promise.all(E.map(Yh))).filter(he=>he!==null);v(he=>[...he,...ye])},[g.length]),j=i.useCallback(y=>{v(F=>F.filter((P,E)=>E!==y))},[]),W=i.useCallback(async()=>{const y=b.trim();if(!y&&g.length===0||a||A.current)return;A.current=!0;const F=g.length>0?[...g]:void 0;try{await l(y,F)!==!1&&(p(""),v([]),C(null))}finally{A.current=!1}},[b,g,a,l]),H=i.useCallback(y=>{w&&(y.preventDefault(),k(!0))},[w]),$=i.useCallback(()=>k(!1),[]),I=i.useCallback(y=>{w&&(y.preventDefault(),k(!1),y.dataTransfer.files.length>0&&M(y.dataTransfer.files))},[w,M]);return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",m?"transition-all duration-200 ease-out":"",T?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:c?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:c?200:0,opacity:c?1:0,transform:c?"translateY(0)":"translateY(10px)",padding:c?"10px 12px":"0 12px",pointerEvents:c?"auto":"none"},"aria-hidden":!c,onDragOver:H,onDragLeave:$,onDrop:I,children:[g.length>0&&s.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:g.map((y,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:y.previewUrl,alt:y.name,className:"w-full h-full object-cover"}),s.jsx("button",{type:"button",onClick:()=>j(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 ${y.name}`,children:"✕"})]},F))}),s.jsxs("div",{className:"flex gap-2 items-center",title:c?`Send message to ${r}`:void 0,children:[d&&s.jsx("button",{type:"button",onClick:()=>{N(),u==null||u()},"aria-label":_?"Hide controls":"Show controls","aria-pressed":_,title:_?"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"})]})}),w&&s.jsxs(s.Fragment,{children:[s.jsx("input",{ref:S,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:y=>{y.target.files&&M(y.target.files),y.target.value=""}}),s.jsx("button",{type:"button",onClick:()=>{var y;return(y=S.current)==null?void 0:y.click()},disabled:g.length>=ir,title:g.length>=ir?`Max ${ir} 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("input",{ref:x,type:"text",placeholder:o||(w&&g.length>0?"Add a message (optional)...":`Send message to ${r}...`),value:b,onChange:y=>p(y.target.value),onPaste:y=>{if(w&&y.clipboardData.files.length>0&&Array.from(y.clipboardData.files).some(E=>E.type.startsWith("image/"))){y.preventDefault(),M(y.clipboardData.files);return}const F=y.clipboardData.getData("text");F&&p(P=>P+F),y.preventDefault()},onKeyDown:y=>{if(y.key==="Enter"){if(y.nativeEvent.isComposing){y.preventDefault();return}y.preventDefault(),W()}},className:"w-full h-10 rounded-[20px] px-4 bg-bg-secondary text-sm text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),s.jsx("button",{onClick:()=>{W()},disabled:Gh({hasDraft:D,isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${D&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:D&&!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:D?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),(f||w&&T)&&s.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${f?"text-red-400":"text-[var(--accent-primary)]"}`,children:f||"Drop image here"}),o&&!f&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:o})]})}),at=e=>e.transport==="pty",Zs=(e,t)=>at(e)?e.mode||"terminal":"chat",Kc=(e,t)=>at(e)&&Zs(e)==="terminal",st=e=>e.transport==="acp",Jh=180;function ls(e){return e.streamSource!=="agent-stream"}function _s(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function Hc(e){return e.machineName||""}function Dr(e){return _s(e)}function Gt(e){return e.agentType||""}function _n(e){return e.hostIdeType||""}function Ho(e){return e.displayPrimary||e.agentName||"Agent"}function Uc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function Qh(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function zc(e){const t=Qh(e),r=Us(t==null?void 0:t.content),n=Us(e.lastMessagePreview);return r||n||""}function Zh(e,t=Jh){const r=Us(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 ef(e){return Zh(zc(e)||e.displaySecondary||"")}function Vc(e){return[e.displaySecondary,Hc(e)].filter(Boolean)}function Vs(e){return e.agentName||ct(Gt(e))}function tf(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 ct(_n(e)||Gt(e))}function Gc(e){return ls(e)?e.sessionId:e.nativeSessionId}function Ui(e){return ls(e)?"native":e.tabKey}function sf(e){return e.sessionId}function rf(e,t){if(t)return ls(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function nf(e,t){const r=Gt(e),n=ls(e),a=at(e)||st(e),o=n?a?Vs(e)||(t==null?void 0:t.cliName)||ct(_n(e)||r):t!=null&&t.type?ct(t.type):ct(_n(e)||r):Vs(e);return{isNativeConversation:n,isCli:at(e),isAcp:st(e),isCliTerminal:Kc(e),providerType:r,displayLabel:o,targetEntry:rf(e,t)}}function xs(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:at(e)||st(e)?{agentType:Gt(e)}:e.streamSource==="agent-stream"?{agentType:Gt(e)}:t}function Gs(e){return e?Dr(e):""}function lr(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function Uo(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function af(e){const t=e instanceof Error?e.message:String(e||""),r=t.toLowerCase();return r.includes("still processing the previous prompt")?"Wait for the current reply to finish before sending another message.":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 qc(){return"select_session"}function of(){return"open_panel"}function lf({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function cf(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function zi(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Ln(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function zo(e){return e instanceof Error?e.message:String(e||"")}function Vi(e){const t=zo(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Gi(e,t){const r=zo(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function df(e,t,r){const n=xs(r);if(!t||t.length===0)return{message:e,...n};const a=t.map(o=>({type:"image",mimeType:o.mimeType,data:o.data,alt:o.name}));return e&&a.push({type:"text",text:e}),{message:e,input:{parts:a,textFallback:e},...n}}function qn({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,o]=i.useState(!1),[l,c]=i.useState(!1),[d,m]=i.useState(null),u=i.useRef(!1),h=i.useRef(null);i.useEffect(()=>{m(null)},[t==null?void 0:t.tabKey]);const x=i.useCallback(async(g,v)=>{if(!t||u.current)return!1;const f=g.trim(),C=Uo(t);if(lf({hasMessage:!!f,blockedMessage:C,sendInFlight:u.current}))return C&&m(C),!1;const T=Date.now(),k={tabKey:t.tabKey,message:f,timestamp:T};if(cf(h.current,k))return m(null),!0;u.current=!0,c(!0),m(null),h.current=k;try{const A=Gs(t);if(!A)return h.current=zi(h.current,k),m("Unable to send message right now."),!1;const _=await e(A,"send_chat",df(f,v,t)),N=Ln(_);if(N!=null&&N.deduplicated)return m(null),!0;if((N==null?void 0:N.sent)===!1)throw new Error((N==null?void 0:N.error)||"Send failed");if((N==null?void 0:N.success)===!1)throw new Error((N==null?void 0:N.error)||"Send failed");return m(null),!0}catch(A){const _=zo(A);return _.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",_):console.warn("Send blocked/failed",A),h.current=zi(h.current,k),m(af(A)),!1}finally{u.current=!1,c(!1)}},[t,e]),S=i.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(g){console.error("Relaunch failed",g)}},[t,e]),b=i.useCallback(async g=>{if(t)try{const f=(t.modalButtons||[]).indexOf(g),C=g.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),T=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(C),k=Gs(t);if(!k)return;const A=await e(k,"resolve_action",{button:g,action:T?"approve":"reject",...f>=0&&{buttonIndex:f},...xs(t)}),_=Ln(A);_.success||r(N=>[...N,{routeId:t.tabKey,text:Gi(g,_==null?void 0:_.error),timestamp:Date.now()}])}catch(v){Vi(v)||console.error("[ModalButton] Error:",v),r(f=>[...f,{routeId:t.tabKey,text:Vi(v)?Gi(g,v):`❌ **${g}** error`,timestamp:Date.now()}])}},[t,e,r]),p=i.useCallback(async()=>{if(!(!t||a)){o(!0);try{await e(t.routeId,of(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(g){console.error("Focus agent failed",g)}finally{o(!1)}}},[t,a,e]);return{isSendingChat:l,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:x,handleRelaunch:S,handleModalButton:b,handleFocusAgent:p}}const uf=10,mf=8e3,pf=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function hf(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 co(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(pf.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=hf(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=>co(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,co(a,n,r+1)]))}function cr(e,t){return Array.isArray(e)?e.slice(-t):[]}function ff(e,t=Date.now()){const r=e&&t-e.firstAt<=mf,n=r?e.count+1:1;return n>=uf?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function Yc(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:cr(e.chatTailState.liveMessages??t.messages,10),activeConversationMessagesTail:cr(t.messages,10),visibleMessagesTail:cr(e.visibleMessages,5),historyMessagesTail:cr(e.chatTailState.historyMessages,5),actionLogsTail:cr(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 co(r)}function Xc(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 Jc(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 Qc(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
32
|
`)}return typeof t.text=="string"?t.text:t.bundle&&typeof t.bundle=="object"?`# ADHDev Chat Debug Bundle
|
|
33
33
|
|
|
34
34
|
\`\`\`json
|
|
@@ -37,9 +37,9 @@ ${JSON.stringify(t.bundle,null,2)}
|
|
|
37
37
|
|
|
38
38
|
\`\`\`json
|
|
39
39
|
${JSON.stringify(t,null,2)}
|
|
40
|
-
\`\`\``}function ma(e,t){return`${e}:${t}`}function ff(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function dr(e,t){ff()&&console.debug(`[subscription-manager] ${e}`,t)}class xf{constructor(){Ze(this,"active",new Map);Ze(this,"retryTimers",new Map)}subscribe(t,r,n,a,o){var u;const l=ma(n.topic,n.key),c=this.active.get(l);let d=!0;if(c)c.handlers.add(a),c.lastUpdate&&a(c.lastUpdate);else{const h={daemonId:r,request:n,handlers:new Set([a])};this.active.set(l,h),dr("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((u=t.sendData)==null?void 0:u.call(t,r,n))??!1,!d&&(o!=null&&o.retryIntervalMs)&&this.scheduleRetry(l,t,o.retryIntervalMs)}const m=()=>{var S;this.clearRetry(l);const h=this.active.get(l);if(!h||(h.handlers.delete(a),h.handlers.size>0))return;this.active.delete(l);const x={type:"unsubscribe",topic:n.topic,key:n.key};dr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(S=t.sendData)==null||S.call(t,r,x)};return m.initialSendAccepted=d,m}publish(t){const r=ma(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,Hs.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),Hs.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=ma(t,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(t){var r;dr("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);dr("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 l=((c=r.sendData)==null?void 0:c.call(r,o.daemonId,o.request))??!1;dr("subscribe_retry",{id:t,accepted:l,topic:o.request.topic,key:o.request.key}),l||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 xf;function bf(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});for(const o of n.childSessions||[]){if(!(o!=null&&o.id))continue;const l=r.get(o.id)||{};r.set(o.id,{...l,...o})}}return r}function gf(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 pa(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function yf(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function vf(e){yf()&&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 Rn(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:o,timestamp:l}=t,c=l||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:m,childrenByParent:u}=gf(d),h=bf(o,n),x=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,S=m.filter(g=>g.kind==="workspace"&&g.transport==="cdp-page"),b=m.filter(g=>g.kind==="agent"&&g.transport==="pty"),p=m.filter(g=>g.kind==="agent"&&g.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:c,...e.version&&{version:e.version},...x&&{machine:x,platform:x.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:S.some(g=>!!g.cdpConnected)});for(const g of S){const v=h.get(g.id),f=br(g,v),T=(u.get(g.id)||[]).map(I=>br(I,h.get(I.id)));r.push({id:`${n}:ide:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:f.parentId,sessionKind:f.kind,transport:f.transport,sessionCapabilities:f.capabilities,type:f.providerType,status:f.cdpConnected?"online":"detected",daemonId:n,instanceId:pa(n,g.id),workspace:f.workspace,terminals:0,childSessions:T,agents:T.map(I=>({id:I.id,name:I.providerName||I.providerType,type:I.providerType,status:I.status})),activeChat:f.activeChat,chats:[],cdpConnected:f.cdpConnected,...f.lastMessagePreview!==void 0&&{lastMessagePreview:f.lastMessagePreview},...f.lastMessageRole!==void 0&&{lastMessageRole:f.lastMessageRole},...f.lastMessageAt!==void 0&&{lastMessageAt:f.lastMessageAt},...f.lastMessageHash!==void 0&&{lastMessageHash:f.lastMessageHash},lastUpdated:f.lastUpdated,unread:f.unread,lastSeenAt:f.lastSeenAt,inboxBucket:f.inboxBucket,completionMarker:f.completionMarker,seenCompletionMarker:f.seenCompletionMarker,surfaceHidden:f.surfaceHidden,...f.controlValues!==void 0&&{controlValues:f.controlValues},...f.providerControls!==void 0&&{providerControls:f.providerControls},...f.summaryMetadata!==void 0&&{summaryMetadata:f.summaryMetadata},...f.settings!==void 0&&{settings:f.settings},...f.messageInput!==void 0&&{messageInput:f.messageInput},timestamp:c})}for(const g of b){const v=h.get(g.id),f=br(g,v);r.push({id:`${n}:cli:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:f.parentId,sessionKind:f.kind,transport:f.transport,sessionCapabilities:f.capabilities,type:f.providerType,agentType:f.providerType,status:f.status||"running",daemonId:n,instanceId:pa(n,g.id),cliName:f.providerName||f.providerType,mode:f.mode||(v==null?void 0:v.mode)||"terminal",workspace:f.workspace||"",activeChat:f.activeChat,...f.resume!==void 0&&{resume:f.resume},...f.runtimeKey!==void 0&&{runtimeKey:f.runtimeKey},...f.runtimeDisplayName!==void 0&&{runtimeDisplayName:f.runtimeDisplayName},...f.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:f.runtimeWorkspaceLabel},...f.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:f.runtimeWriteOwner},...f.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:f.runtimeAttachedClients},...f.lastMessagePreview!==void 0&&{lastMessagePreview:f.lastMessagePreview},...f.lastMessageRole!==void 0&&{lastMessageRole:f.lastMessageRole},...f.lastMessageAt!==void 0&&{lastMessageAt:f.lastMessageAt},...f.lastMessageHash!==void 0&&{lastMessageHash:f.lastMessageHash},lastUpdated:f.lastUpdated,unread:f.unread,lastSeenAt:f.lastSeenAt,inboxBucket:f.inboxBucket,completionMarker:f.completionMarker,seenCompletionMarker:f.seenCompletionMarker,surfaceHidden:f.surfaceHidden,...f.controlValues!==void 0&&{controlValues:f.controlValues},...f.providerControls!==void 0&&{providerControls:f.providerControls},...f.summaryMetadata!==void 0&&{summaryMetadata:f.summaryMetadata},...f.settings!==void 0&&{settings:f.settings},...f.messageInput!==void 0&&{messageInput:f.messageInput},timestamp:c,_isCli:!0})}for(const g of p){const v=h.get(g.id),f=br(g,v);r.push({id:`${n}:acp:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:f.parentId,sessionKind:f.kind,transport:f.transport,sessionCapabilities:f.capabilities,type:f.providerType,agentType:f.providerType,status:f.status||"running",daemonId:n,instanceId:pa(n,g.id),cliName:f.providerName||f.providerType,mode:"chat",workspace:f.workspace||"",activeChat:f.activeChat,...f.runtimeKey!==void 0&&{runtimeKey:f.runtimeKey},...f.runtimeDisplayName!==void 0&&{runtimeDisplayName:f.runtimeDisplayName},...f.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:f.runtimeWorkspaceLabel},...f.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:f.runtimeWriteOwner},...f.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:f.runtimeAttachedClients},...f.lastMessagePreview!==void 0&&{lastMessagePreview:f.lastMessagePreview},...f.lastMessageRole!==void 0&&{lastMessageRole:f.lastMessageRole},...f.lastMessageAt!==void 0&&{lastMessageAt:f.lastMessageAt},...f.lastMessageHash!==void 0&&{lastMessageHash:f.lastMessageHash},lastUpdated:f.lastUpdated,unread:f.unread,lastSeenAt:f.lastSeenAt,inboxBucket:f.inboxBucket,completionMarker:f.completionMarker,seenCompletionMarker:f.seenCompletionMarker,surfaceHidden:f.surfaceHidden,...f.controlValues!==void 0&&{controlValues:f.controlValues},...f.providerControls!==void 0&&{providerControls:f.providerControls},...f.summaryMetadata!==void 0&&{summaryMetadata:f.summaryMetadata},...f.settings!==void 0&&{settings:f.settings},...f.messageInput!==void 0&&{messageInput:f.messageInput},timestamp:c,_isAcp:!0})}return vf(r),r}const wf=15e3,jf=15e3,kf=6e4,Sf=1200,qi=12,Nf=8e3,Cf=4e3,ha=new Map,fa=new Map,Qr=new Set,jr=new Map;function If(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 Yi(e,t){const r=jr.get(e);!r||r.size===0||(jr.delete(e),r.forEach(n=>n(t)))}function Tf(e,t){return new Promise(r=>{const n=jr.get(e)||new Set;jr.set(e,n);const a=l=>{clearTimeout(o),n.delete(a),n.size===0&&jr.delete(e),r(l)},o=setTimeout(()=>a(!1),t);n.add(a)})}function Er(){const{sendCommand:e,sendData:t}=jt(),{injectEntries:r,getIdes:n}=Mr();return i.useCallback(async(a,o)=>{if(!a)return;const l=(o==null?void 0:o.minFreshMs)??kf,c=fa.get(a)||0;if(!(o!=null&&o.force)&&Qr.has(a)&&c>0||!(o!=null&&o.force)&&c>0&&Date.now()-c<l)return;const d=ha.get(a);if(d)return d;const m=(async()=>{if(t&&!Qr.has(a)){const p=Qt.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},g=>{const v=n(),f=v.find(I=>I.id===a),T=Rn(g.status,{daemonId:a,existingDaemon:f,existingEntries:v,timestamp:g.timestamp});T.length>0&&r(T),fa.set(a,Date.now()),Yi(a,!0)});if(p.initialSendAccepted?Qr.add(a):Qr.delete(a),!(o!=null&&o.force)&&p.initialSendAccepted&&await Tf(a,Sf))return}const u=await e(a,"get_status_metadata"),h=If(u);if(!h)return;const x=n(),S=x.find(p=>p.id===a),b=Rn(h,{daemonId:a,existingDaemon:S,existingEntries:x,timestamp:h.timestamp||Date.now()});b.length>0&&r(b,{authoritativeDaemonIds:[a]}),fa.set(a,Date.now()),Yi(a,!0)})().finally(()=>{ha.delete(a)});return ha.set(a,m),m},[n,r,e,t])}function Mf(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const Af=60,_f=50;function Qc(e={}){return e.isCliLike?_f:Af}function Lf(e={}){return Qc(e)}function Tt(e){return(typeof e=="string"?e.trim():"")||void 0}function Jt(e,t){const r=Tt(t);return r?`${e}:${r}`:void 0}function os(e,t,r){const n=Jt(t,r),a=Tt(r);n&&e.push(n),a&&e.push(a)}function Bs(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function Zc(e){return Tt(e.providerSessionId)||Tt(e.sessionId)||Tt(e.tabKey)||Tt(e.routeId)}function Vo(e){return Bs([Tt(e.providerSessionId),Tt(e.sessionId)])}function Ks(e){const t=[];return os(t,"provider",e.providerSessionId),os(t,"session",e.sessionId),os(t,"tab",e.tabKey),os(t,"route",e.routeId),Bs(t)}function Rf(e){const t=[];return Tt(e.providerSessionId)?(os(t,"provider",e.providerSessionId),Bs(t)):Tt(e.sessionId)?(os(t,"session",e.sessionId),Bs(t)):Tt(e.tabKey)?(os(t,"tab",e.tabKey),Bs(t)):Tt(e.routeId)?(os(t,"route",e.routeId),Bs(t)):[]}function Go(e){return Jt("provider",e.providerSessionId)||Jt("session",e.sessionId)||Jt("tab",e.tabKey)||Jt("route",e.routeId)||"unknown:"}function $r(e){return Vo(e)[0]}function Pf(e){const t=Tt(e.providerSessionId),r=Tt(e.sessionId),n=Tt(e.tabKey),a=Tt(e.routeId),o=[Jt("provider",t),Jt("session",r),Jt("tab",n),Jt("route",a)].filter(d=>typeof d=="string"),l=Ks({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),c=Go({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:c,targetKey:c,targetValue:Zc({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:$r({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:l}}function uo(e,t){const r=Pf(e);return Rf(t).some(n=>r.lookupKeys.includes(n))}const Br=60,Df=1e3,qo=12e4,Ef=new Set(["generating","waiting_approval","starting","streaming","working"]),Xi=new Map;function ed(e,t){return`${e}::${t}`}function mo(e=Br){return{liveMessages:[],hasLiveSnapshot:!1,cursor:$f([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function $f(e,t=Br){return{tailLimit:t}}function Ji(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("|")}class Bf{constructor(t){Ze(this,"manager");Ze(this,"sendData");Ze(this,"daemonId");Ze(this,"sessionId");Ze(this,"historySessionId");Ze(this,"subscriptionKey");Ze(this,"fallbackRecentCount");Ze(this,"snapshot");Ze(this,"transportSubscription",null);Ze(this,"listeners",new Set);Ze(this,"retainCount",0);Ze(this,"loadHistoryPromise",null);Ze(this,"pendingDisconnectTimer",null);this.manager=t.manager||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=mo(Math.max(0,t.tailLimit??Br))}updateOptions(t){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 r=Math.max(0,t.tailLimit);r!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect()))}}getSnapshot(){return this.snapshot}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}),l=Array.isArray(o.messages)?o.messages:[],c=!n&&l.length===0&&o.hasMore!==!0&&this.fallbackRecentCount>0;this.snapshot={...this.snapshot,historyMessages:[...l,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+l.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:Df}))}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=Array.isArray(t.messages)?t.messages:[],n={tailLimit:this.snapshot.cursor.tailLimit};Ji(this.snapshot.liveMessages)===Ji(r)&&this.snapshot.cursor.tailLimit===n.tailLimit||(this.snapshot={...this.snapshot,liveMessages:r,hasLiveSnapshot:!0,cursor:n},this.emit())}}function td(e){const t=ed(e.daemonId,e.sessionId),r=Xi.get(t);if(r)return r.updateOptions(e),r;const n=new Bf(e);return Xi.set(t,n),n}function Of(e,t){return{...e,loadHistoryPage:t}}function Ff(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function Wf(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Ef.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??qo)),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 Kf(e=qo){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Hf(e,t={}){const r=new Set,n=[];for(const a of e){if(!Wf(a,t))continue;const o=Dr(a),l=a.sessionId||"";if(!o||!l)continue;const c=ed(o,l);if(r.has(c))continue;r.add(c);const d=$r(a);n.push({daemonId:o,sessionId:l,historySessionId:d||l,subscriptionKey:`daemon:${o}:session:${l}`})}return n.sort(Ff),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Uf(e,t){const{sendData:r,sendCommand:n}=jt(),a=(t==null?void 0:t.enabled)!==!1,o=Dr(e),l=e.sessionId||"",c=$r(e)||l,d=`daemon:${o}:session:${l}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??Br),u=i.useMemo(()=>!a||!o||!l?null:td({daemonId:o,sessionId:l,historySessionId:c,subscriptionKey:d,sendData:r,tailLimit:m,fallbackRecentCount:e.messages.length}),[e.messages.length,o,a,c,r,l,d,m]),[h,x]=i.useState(()=>(u==null?void 0:u.getSnapshot())||mo(m));i.useEffect(()=>{if(!u){x(mo(m));return}u.retain(),x(u.getSnapshot());const b=u.subscribe(p=>{x(p)});return()=>{b(),u.release()}},[u,m]);const S=i.useCallback(async()=>{!u||!o||!l||await u.loadHistoryPage(async({offset:b,excludeRecentCount:p})=>{const g=e.agentType,v=await n(o,"chat_history",{agentType:g,offset:b,limit:30,targetSessionId:l,historySessionId:c,excludeRecentCount:p}),f=v&&typeof v=="object"&&"result"in v?v.result||{}:v||{};return{messages:Array.isArray(f.messages)?f.messages:[],hasMore:f.hasMore===!0}})},[e.agentType,u,o,c,n,l]);return i.useMemo(()=>Of(h,S),[S,h])}function zf(e,t){const{sendData:r}=jt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??Br),o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??qo)),l=Kf(o),[c,d]=i.useState(0);i.useEffect(()=>{if(!n||e.length===0)return;const u=setInterval(()=>{d(h=>h+1)},l);return()=>{clearInterval(u)}},[e.length,n,l]);const m=i.useMemo(()=>Hf(e,{recentActivityMs:o}),[e,o,c]);i.useEffect(()=>{if(!n||!r||m.descriptors.length===0)return;const u=m.descriptors.map(h=>td({...h,sendData:r,tailLimit:a}));return u.forEach(h=>{h.retain()}),()=>{u.forEach(h=>h.release())}},[m.signature,n,r,a])}function Vf(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function Qi(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 Gf(e,t){if(e.length===0)return[];if(t.some(Qi))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||!Qi(o))continue;const l=String(o.role||"").toLowerCase();n.has(l)||(n.add(l),r.unshift(o))}return r}function qf(e){const{historyMessages:t,liveMessages:r,visibleLiveCount:n}=e,a=Math.max(0,r.length-n),o=a>0?r.slice(0,a):[],l=a>0?r.slice(-n):r,c=Gf(o,l),d=c.length>0?[...c,...l]:l;return t.length===0?d:[...t,...d]}function Yf(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Xf(e){return Yf(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}function Jf(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function Qf(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function Zf(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function sd(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function rd(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 ex(e){return sd(e)?!1:e.inboxBucket==="task_complete"&&rd(e).length>0}function Zi(e){return e.branch||"detached HEAD"}function tx(e){if(e.error)return`${Zi(e)} · Git error: ${e.error}`;const t=[Zi(e)];return e.changedFiles>0?t.push(Jf(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 sx(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${tx(t)}`}function rx(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function nx(e,t={}){if(t.enabled===!1)return[];if(!Zf(e))return[];const r=sd(e)?"working":ex(e)?"complete":null;if(!r)return[];const n=r==="complete"?rd(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${Qf(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:sx(r,e.git),timestamp:rx(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 ax=60;function po({activeConv:e,ideEntry:t,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:o,isFocusingAgent:l,actionLogs:c,userName:d,scrollToBottomRequestNonce:m,isInputActive:u=!0,isVisible:h=!0}){var Ce,ee,me,ie,pe,le,B;const x=i.useRef(new Map),S=i.useRef(void 0),b=Er(),{sendCommand:p}=jt(),{isVisible:g}=Oo();Pr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:c.length,isSendingChat:n});const v=Nt.useMemo(()=>Qs(e),[e.status,e.connectionState]),f=i.useMemo(()=>rf(e,t),[e,t]),T=i.useMemo(()=>{var z;return Ko((z=f.targetEntry)==null?void 0:z.providerControls,{hostIdeType:e.hostIdeType,providerType:f.providerType})},[e.hostIdeType,f.providerType,(Ce=f.targetEntry)==null?void 0:Ce.providerControls]),I=Qc({isCliLike:f.isCli||f.isAcp}),k=Lf({isCliLike:f.isCli||f.isAcp}),A=Uf(e,{enabled:h&&!!e.sessionId,tailLimit:k}),[_,N]=i.useState(I),[w,D]=i.useState(()=>Ri()),M=e.tabKey,j=A.historyMessages,W=A.hasMoreHistory,H=A.historyError,$=Vf(e,A),C=Sc($).length;i.useEffect(()=>{N(I)},[I,M]);const y=Math.max(0,$.length-_),F=Ho(e),P=Dr(e),E=Xf(e),G=Uo(e),J=a||G,ye=!!G,[he,ne]=i.useState(!1);i.useEffect(()=>{const z=f.targetEntry;P&&(!z||z.providerControls===void 0||z.controlValues===void 0)&&b(P,{minFreshMs:3e4}).catch(()=>{})},[P,f.isAcp,(ee=f.targetEntry)==null?void 0:ee.providerControls,(me=f.targetEntry)==null?void 0:me.controlValues,b]);const ue=i.useCallback(async()=>{if(!he){if($.length>_){N(z=>Math.min($.length,z+ax));return}ne(!0);try{await A.loadHistoryPage()}finally{ne(!1)}}},[A,he,$.length,_]),{allMessages:Se,receivedAtMap:ve}=i.useMemo(()=>{const z=qf({historyMessages:j,liveMessages:$,visibleLiveCount:_}),de=nx(e),re=de.length>0?[...z,...de]:z,R={};return re.forEach((q,ce)=>{const Ne=`${e.tabKey}:${In(q,ce)}`;let je=Mf(q)||x.current.get(Ne)||0;je||(je=Date.now(),x.current.set(Ne,je)),R[In(q,ce)]=je}),{allMessages:re,receivedAtMap:R}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,y,j,$,_]),X=i.useMemo(()=>c.filter(z=>z.routeId===e.tabKey).sort((z,de)=>z.timestamp-de.timestamp),[c,e.tabKey]),xe=i.useCallback(async()=>{var ce,Ne;if(!P)return;const z=qc({activeConv:e,visibleMessages:Se,actionLogs:c,controls:(ce=f.targetEntry)==null?void 0:ce.providerControls,controlValues:(Ne=f.targetEntry)==null?void 0:Ne.controlValues,visibleBarControlCount:T.length,chatTailState:{liveMessages:A.liveMessages,hasLiveSnapshot:A.hasLiveSnapshot,hasMoreHistory:W,historyError:H,historyMessages:j},ui:{controlsVisible:g,visibleLiveCount:_,activityVisible:w,activityCount:C,hiddenLiveCount:y,isInputActive:u,isVisible:h}}),de=await p(P,"get_chat_debug_bundle",{agentType:f.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:z}),re=Ln(de),R=Jc(re),q=await Xc(R);q==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),it.showToast(Yc(re,{locatorCopyStatus:q}),q==="failed"?"warning":"success")},[e,c,C,Se,g,A.hasLiveSnapshot,A.liveMessages,f.providerType,(ie=f.targetEntry)==null?void 0:ie.controlValues,(pe=f.targetEntry)==null?void 0:pe.providerControls,P,W,y,j,u,h,H,p,w,T.length,_]),fe=i.useCallback(()=>{D(z=>{const de=!z;return Ip(de),de})},[]);i.useEffect(()=>{const z=de=>{de.key===Do&&D(Ri())};return window.addEventListener("storage",z),()=>window.removeEventListener("storage",z)},[]);const we=i.useCallback(()=>{const z=hf(S.current);S.current=z.state,z.shouldCollect&&xe().catch(de=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",de),it.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[xe]),be=i.useMemo(()=>{if($.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((v.isGenerating||e.status==="streaming")&&ne(!1),e.status==="not_monitored"&&E)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(zs,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),s.jsx("button",{onClick:o,disabled:l,className:"btn btn-primary",children:l?"⌛ Switching...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ns,{size:14})," Open ",F," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&E)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(vc,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),s.jsx("button",{onClick:o,disabled:l,className:"btn btn-primary",children:l?"⌛ Opening...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ns,{size:14})," Open ",F," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!he)return!W&&j.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,E,o,W,j.length,l,he,$.length,F,v.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[s.jsx("div",{className:"chat-activity-toggle-bar",children:s.jsxs("button",{type:"button",className:`chat-activity-toggle ${w?"chat-activity-toggle-active":""}`,onClick:fe,"aria-pressed":w,title:"Show tool, terminal, and runtime activity rows",children:[s.jsx("span",{className:"chat-activity-toggle-dot"}),"Activity",C>0&&s.jsx("span",{className:"chat-activity-toggle-count",children:C})]})}),s.jsx(Kp,{messages:Se,actionLogs:X,agentName:Vs(e)||F||"Agent",userName:d,isCliMode:f.isCli||f.isAcp,isWorking:v.isGenerating,contextKey:e.tabKey,receivedAtMap:ve,lastMessageHash:e.lastMessageHash,showActivityMessages:w,onLoadMore:ue,isLoadingMore:he,hasMoreHistory:W,hiddenLiveCount:y,loadError:H??void 0,emptyState:be,scrollToBottomRequestNonce:m,isVisible:h}),s.jsx(zh,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:f.providerType,displayLabel:f.displayLabel,controls:(le=f.targetEntry)==null?void 0:le.providerControls,controlValues:(B=f.targetEntry)==null?void 0:B.controlValues,isActive:u,isCliTerminal:f.isCliTerminal}),!f.isCliTerminal&&s.jsx(Fc,{contextKey:e.tabKey,panelLabel:F,isSending:n,isBusy:ye,statusMessage:J,onSend:r,isActive:u,showControlsToggle:T.length>0,onControlsToggle:we,messageInput:e.messageInput})]})}let nd=cs;function ad(){return nd()}class ox{constructor(){Ze(this,"listeners",new Map)}send(t){}isConnected(){return!1}on(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{var n;(n=this.listeners.get(t))==null||n.delete(r)}}emit(t,...r){var n;(n=this.listeners.get(t))==null||n.forEach(a=>a(...r))}}let od=new ox;class ix{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 mt=new ix;function lx(e){e.dashboardWS&&(od=e.dashboardWS),e.connectionManager&&(mt=e.connectionManager),e.useDaemonsHook&&(nd=e.useDaemonsHook)}const cx=.5,dx=1.25;function ut(e){return Ho(e)}function Is(e){return zc(e).join(" · ")}function id(e){const t=Uc(e);return t||(e.title?e.title:Is(e)||"No messages yet")}function ld(e,t){const{isReconnecting:r,isConnecting:n}=Qs(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function ux(e,t){const r=["Chat",...zc(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function bs(e){return ld(e)||Is(e)}function mx(e){return`${ut(e)} · ${id(e)}`}function px(e){const t=_n(e),r=t?ct(t):Vs(e);return`${ut(e)} — ${r||"Agent"}`}function hx(e){return Vs(e)||"CLI"}function cd(e){return Hc(e)}function dd(e){return e?`Remote · ${ut(e)||e.workspaceName||"Session"}`:"Remote"}function fx({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:l=!0,isInputActive:c=!0}){var ae;cs();const{sendPtyInput:d}=jt(),[m,u]=i.useState(!1),h=i.useRef(!1);h.current=m;const[x,S]=i.useState("Runtime terminal unavailable"),[b,p]=i.useState(!1),[g,v]=i.useState(null),[f,T]=i.useState(!1),[I,k]=i.useState(!1),[A,_]=i.useState(1),[N,w]=i.useState(!1),[D,M]=i.useState({width:0,height:0}),[j,W]=i.useState({width:0,height:0}),[H,$]=i.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[C,y]=i.useState(null),F=i.useRef(null),P=i.useRef(null),E=i.useRef(!1),G=i.useRef(!1),J=i.useRef(l),ye=i.useRef(0),he=i.useRef(!1),ne=i.useRef(""),ue=i.useRef(null),Se=i.useRef(!1),ve=i.useRef(!1),X=i.useRef(null),xe=i.useRef(null),fe=i.useRef(null),we=32*1024,be=()=>{var K,Y,se,oe;return((Y=(K=F.current)==null?void 0:K.ownerDocument)==null?void 0:Y.defaultView)||((oe=(se=P.current)==null?void 0:se.ownerDocument)==null?void 0:oe.defaultView)||window},Ce=K=>{const Y=be();return{ownerWindow:Y,frameId:Y.requestAnimationFrame(K)}},ee=()=>{const K=X.current;if(K){try{K.ownerWindow.cancelAnimationFrame(K.frameId)}catch{}X.current=null}},me=()=>{const K=xe.current;if(K){try{K.ownerWindow.clearTimeout(K.timeoutId)}catch{}xe.current=null}},ie=()=>{const K=fe.current;if(K){try{K.ownerWindow.clearTimeout(K.timeoutId)}catch{}fe.current=null}},pe=()=>{l&&X.current===null&&(X.current=Ce(()=>{rt()}))},le=e.tabKey,B=e.sessionId||"",z=e.daemonId||((ae=e.routeId)==null?void 0:ae.split(":")[0])||e.routeId||"",de=Uo(e),re=m?o||de:x,R=cx,q=dx,ce=.05,Ne=()=>{const K=j.width,Y=j.height;if(!Number.isFinite(D.width)||D.width<=0||!Number.isFinite(D.height)||D.height<=0||!Number.isFinite(K)||K<=0||!Number.isFinite(Y)||Y<=0)return 1;const se=D.width/K,oe=D.height/Y;return Number(Math.min(q,Math.max(R,Math.min(se,oe))).toFixed(2))},je=Ne(),O=E.current&&A>je,Ie=Number.isFinite(j.width)&&j.width>0?Math.max(D.width,Math.round(j.width*A)):D.width,Le=Number.isFinite(j.height)&&j.height>0?Math.max(D.height,Math.round(j.height*A)):D.height,He=()=>{Ce(()=>{const K=P.current;K&&(K.scrollLeft=0,K.scrollTop=K.scrollHeight-K.clientHeight)})},ze=()=>{var K,Y;ye.current=0,he.current=!1,ne.current="",ue.current=null,Se.current=!1,ve.current=!1,E.current||(G.current=!1,_(1)),X.current!==null&&ee(),u(!1),S("Runtime terminal unavailable"),ie(),me(),v(null),y(null),w(!1),p(!1),T(!1),k(!1),(Y=(K=r.current)==null?void 0:K.reset)==null||Y.call(K)},Xe=()=>{var K,Y;ye.current=0,he.current=!1,ne.current="",ue.current=null,Se.current=!1,ve.current=!1,X.current!==null&&ee(),u(!0),S(""),ie(),me(),v(null),y(null),w(!1),p(!1),T(!1),k(!1),(Y=(K=r.current)==null?void 0:K.reset)==null||Y.call(K)},Je=()=>{ve.current&&(ve.current=!1,Ce(()=>{var K,Y;(Y=(K=r.current)==null?void 0:K.scrollToTop)==null||Y.call(K)}))},rt=()=>{if(X.current=null,!l)return;const K=ne.current;if(!K)return;const Y=K.slice(0,we);ne.current=K.slice(Y.length);const se=r.current;if(!se){ne.current=Y+ne.current,pe();return}se.write(Y,()=>{if(ne.current.length>0){pe();return}Je()})},pt=K=>{K&&(ne.current+=K,pe())},xt=(K,Y=0,se,oe,ke={})=>{var Ee,Ae,$e,Fe;const Pe=!!ke.force;!Pe&&Y>0&&ye.current>=Y||!Pe&&Y===0&&he.current||(ye.current=Y,Y>0&&T(!0),u(!0),S(""),typeof se=="number"&&typeof oe=="number"&&se>0&&oe>0&&((Ae=(Ee=r.current)==null?void 0:Ee.resize)==null||Ae.call(Ee,se,oe)),ne.current="",(Fe=($e=r.current)==null?void 0:$e.reset)==null||Fe.call($e),K?pt(K):Je())};i.useEffect(()=>{ze()},[B]),i.useEffect(()=>{var Y;if(!B)return;const K=((Y=mt.onRuntimeEvent)==null?void 0:Y.call(mt,B,se=>{if(!(!se||se.sessionId!==B)){if(se.type==="runtime_snapshot"){if(!l){ue.current={text:se.text||"",seq:se.seq||0,cols:se.cols,rows:se.rows,force:!!se.force};return}xt(se.text||"",se.seq||0,se.cols,se.rows,{force:!!se.force});return}if(se.type==="session_output"){he.current=!0,typeof se.seq=="number"&&(ye.current=Math.max(ye.current,se.seq),se.seq>0&&T(!0)),h.current||u(!0),h.current||S(""),typeof se.data=="string"&&pt(se.data);return}if(se.type==="session_cleared"){if(!l){Se.current=!0,ne.current="",ue.current=null;return}Xe();return}if(se.type==="session_io_error"){const oe=typeof se.error=="string"&&se.error?se.error:typeof se.reason=="string"&&se.reason?se.reason:"unknown error";u(!1),S(`Runtime input failed: ${oe}`);return}}},z))||(()=>{});return()=>{K()}},[z,B,r,l]);const vt=async(K={})=>{var Y;if(!z||!B)return{success:!1,error:"daemonId and sessionId are required"};K.preserveStatus||S(K.loadingMessage||"Loading runtime terminal...");try{const se=await((Y=mt.requestRuntimeSnapshot)==null?void 0:Y.call(mt,z,B,{sinceSeq:K.sinceSeq,force:K.force}));return se&&se.success===!1?(K.preserveStatus||(u(!1),S(`Runtime terminal unavailable: ${se.error}`)),se):se||{success:!0}}catch(se){const oe=(se==null?void 0:se.message)||String(se);return K.preserveStatus||(u(!1),S(`Runtime terminal unavailable: ${oe}`)),{success:!1,error:oe}}},Te=async K=>{var Pe,Ee;const Y=((Pe=F.current)==null?void 0:Pe.ownerDocument)||document,se=Y.defaultView||window,oe=(Ee=se.navigator)==null?void 0:Ee.clipboard;if(oe!=null&&oe.writeText&&se.isSecureContext)try{return await oe.writeText(K),!0}catch{}let ke=null;try{return ke=Y.createElement("textarea"),ke.value=K,ke.setAttribute("readonly","true"),ke.style.position="fixed",ke.style.left="-9999px",ke.style.top="0",Y.body.appendChild(ke),ke.focus(),ke.select(),Y.execCommand("copy")}catch{return!1}finally{ke==null||ke.remove()}},Ve=K=>{me(),y(K);const Y=be();xe.current={ownerWindow:Y,timeoutId:Y.setTimeout(()=>{xe.current=null,y(se=>se===K?null:se)},2200)}},tt=K=>{ie(),v(K);const Y=be();fe.current={ownerWindow:Y,timeoutId:Y.setTimeout(()=>{fe.current=null,v(se=>se===K?null:se)},2200)}},Ge=async()=>{var ke,Pe,Ee,Ae;const K=((Pe=(ke=r.current)==null?void 0:ke.getSelection)==null?void 0:Pe.call(ke))||"",Y=((Ae=(Ee=r.current)==null?void 0:Ee.getVisibleText)==null?void 0:Ae.call(Ee))||"",se=K.trimEnd()||Y.trimEnd();if(!se){Ve("Nothing to copy");return}if(!await Te(se)){Ve("Copy failed");return}Ve(K.trimEnd()?"Copied selection":"Copied visible terminal")},ot=K=>{if(!m||!l)return;((d==null?void 0:d(z,B,K))??!1)||Ve("Terminal input failed")},U=async()=>{if(b)return;p(!0),v("Loading older terminal output..."),ve.current=!0;const K=await vt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(p(!1),(K==null?void 0:K.success)===!1){ve.current=!1,v(`Older terminal output unavailable: ${K.error}`);return}k(!0),tt("Older terminal output loaded"),Ce(()=>{var Y;(Y=r.current)==null||Y.bumpResize()})};i.useEffect(()=>{var Y,se;if(!B)return;z&&((Y=mt.getState)==null?void 0:Y.call(mt,z))==="connected"&&vt();const K=(se=mt.onStateChange)==null?void 0:se.call(mt,(oe,ke)=>{oe!==z||ke!=="connected"||vt()});return()=>{K==null||K()}},[z,B,r]),i.useEffect(()=>{t&&ze()},[t,le,r]),i.useEffect(()=>{var oe,ke;const K=F.current,Y=(ke=(oe=K==null?void 0:K.ownerDocument)==null?void 0:oe.defaultView)==null?void 0:ke.ResizeObserver;if(!K||!Y)return;const se=new Y(Pe=>{const Ee=Pe[0];if(!Ee)return;const{width:Ae,height:$e}=Ee.contentRect;M(Fe=>{const Me=Math.round(Ae),Qe=Math.round($e);return Fe.width===Me&&Fe.height===Qe?Fe:{width:Me,height:Qe}})});return se.observe(K),()=>se.disconnect()},[]),i.useEffect(()=>{if(E.current)return;const K=Ne();!Number.isFinite(K)||K<=0||_(Y=>G.current?K<Y-ce?K:Y:(G.current=!0,K))},[j.height,j.width,D.height,D.width]),i.useEffect(()=>{O&&He()},[O,Le,Ie]),i.useEffect(()=>{var se;const K=J.current;if(J.current=l,!l)return;K||k(!1),Se.current&&(Se.current=!1,Xe());const Y=ue.current;Y&&(ue.current=null,xt(Y.text,Y.seq,Y.cols,Y.rows,{force:!!Y.force})),z&&B&&((se=mt.getState)==null?void 0:se.call(mt,z))==="connected"&&vt(),ne.current&&X.current===null&&pe(),Ce(()=>{var oe;(oe=r.current)==null||oe.bumpResize()})},[z,l,B]),i.useEffect(()=>()=>{X.current!==null&&ee(),me(),ie()},[]),i.useEffect(()=>{const K=oe=>{var Pe;const ke=oe.detail;ke!=null&&ke.sessionId&&ke.sessionId!==B||m&&((Pe=r.current)==null||Pe.bumpResize())},Y=be(),se=Y===window?[window]:[window,Y];for(const oe of se)oe.addEventListener("adhdev:fit-cli-terminal",K);return()=>{for(const oe of se)oe.removeEventListener("adhdev:fit-cli-terminal",K)}},[m,B,r]);const Z=m&&f&&!I&&(H.atTop||!H.canScroll)||b||!!g;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:F,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[Z&&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:()=>{U()},disabled:!B||b,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:b?"Loading older...":"Load older terminal output"}),g&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:g})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[C&&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:C}),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:()=>{Ge()},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:()=>w(K=>!K),disabled:!m,"aria-label":"Open terminal control keys","aria-expanded":N,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),N&&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:()=>w(!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:()=>ot("\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:()=>ot(" "),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:()=>ot("\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:()=>ot("\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:()=>ot("\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:()=>ot("\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:()=>ot("\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:()=>ot(""),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:()=>ot(""),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:()=>ot(""),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:()=>{E.current=!0,_(K=>{const Y=Math.max(je,Number((K-.1).toFixed(2)));return Y>je&&He(),Y})},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:()=>{E.current=!0,_(K=>{const Y=Math.min(q,Number((K+.1).toFixed(2)));return Y>je&&He(),Y})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:P,className:O?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:s.jsx("div",{style:{width:Ie>0?`${Ie}px`:"100%",height:Le>0?`${Le}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:j.width>0?`${j.width}px`:"100%",height:j.height>0?`${j.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:A},children:s.jsx(Mc,{ref:r,readOnly:!m||!l,sizingMode:"measured",onViewportMetrics:W,onScrollMetrics:$,onInput:K=>{!m||(d==null||d(z,B,K))}})})})}),!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:x})]}),s.jsx(Fc,{contextKey:e.tabKey,panelLabel:ut(e),isSending:a,isBusy:!!de,statusMessage:re,onSend:async K=>de?!1:n(K),isActive:c&&l,showControlsToggle:!1,animateVisibility:!1})]})}const xx=5e3,bx=12e3;function gx(e){return e==="disconnected"||e==="reconnecting"}function yx({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=xx,reconnectActionDelayMs:o=bx}){const l=gx(e),[c,d]=i.useState(()=>!l||a<=0),[m,u]=i.useState(()=>!l||o<=0),h=i.useRef(!1);i.useEffect(()=>{if(!l){d(!1);return}if(h.current=!1,a<=0){h.current=!0,d(!0);return}d(!1);const k=setTimeout(()=>{h.current=!0,d(!0)},a);return()=>clearTimeout(k)},[a,l]),i.useEffect(()=>{if(!l){u(!1);return}if(o<=0){u(!0);return}u(!1);const k=setTimeout(()=>{u(!0)},o);return()=>clearTimeout(k)},[o,l]);const x=l?c:e==="offline"||e==="auth_failed",S=!!(n&&e!=="auth_failed"&&(!l||m)),b=i.useMemo(()=>!t||e!=="connected"?!1:a<=0||h.current,[a,t,e]),p=e==="auth_failed"?"red":e==="offline"?"orange":"accent",g={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))"},v={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)"},f={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},T="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",I={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[x&&s.jsx("div",{className:T,style:I,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:g[p],border:v[p],color:f[p]},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.")]}),S&&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"})]})}),b&&s.jsx("div",{className:T,style:I,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 vx({terminalBackend:e,isStandalone:t=!1,machineLabel:r,machineKey:n}){const a=i.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[o,l]=i.useState(!1);if(i.useEffect(()=>{if(!a){l(!1);return}try{l(localStorage.getItem(a)==="1")}catch{l(!1)}},[a]),!t||!e||e.backend!=="xterm"||o)return null;const c=(r==null?void 0:r.trim())||"This machine",d=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}l(!0)};return s.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5",style:{background:"linear-gradient(90deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04))",borderBottom:"1px solid rgba(245,158,11,0.2)",color:"#d97706"},children:[s.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[s.jsxs("span",{children:[c," is using `xterm` fallback."]}),s.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),s.jsx("button",{type:"button",onClick:d,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function Yo({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(Ro,{size:n}):s.jsx(es,{size:n})})}const zt="New session",ud="A connected machine is ready. Start a new session to begin chatting, or open a workspace to launch an IDE, CLI, or ACP session.";function wx(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 jx(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 kx(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 qs({git:e,className:t="",compact:r=!1}){const n=wx(e),a=jx(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 ${kx(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 Sx({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,l=a.filter(c=>c==="connecting"||c==="new"||c==="checking").length;return r>0&&l>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 el({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function tl({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const l=Un(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",l].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[c?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),n()},children:"Mark read"}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),a()},children:"Mark unread"}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),o()},children:"Delete"})]})]})}function Nx({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:l,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:m,hiddenConversations:u=[],onShowConversation:h,onShowAllHidden:x,onResetPanelsToMain:S,inboxOpen:b,onInboxOpenChange:p,hiddenOpen:g,onHiddenOpenChange:v,onOpenNewSession:f,onOpenDashboardGuide:T,guideNudgeVisible:I=!1,actionShortcuts:k,notifications:A,notificationUnreadCount:_,onOpenNotification:N,onMarkNotificationRead:w,onMarkNotificationUnread:D,onDeleteNotification:M,onOpenGitDialog:j,onOpenMeshGraph:W}){var Ce;const{ides:H,p2pStates:$={}}=cs(),C=!!e&&at(e)&&!st(e),y=!!e&&st(e),F=!!(e!=null&&e.daemonId)&&typeof((Ce=e==null?void 0:e.settings)==null?void 0:Ce.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.length>0,P=c||(e?Wc(e)?"terminal":"chat":null),[E,G]=i.useState(!1),J=i.useRef(null),ye=i.useRef(null),he=H.filter(ee=>ee.type==="adhdev-daemon"),ne=Sx({wsStatus:t,isConnected:r,daemonCount:he.length,p2pStates:$}),ue=ne.subtitle,Se=ne.tone==="connected"?"#22c55e":ne.tone==="limited"?"#eab308":"#ef4444",ve=ne.tone==="connected"?"0 0 4px #22c55e80":ne.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",X=i.useMemo(()=>A.filter(ee=>!ee.readAt),[A]),xe=i.useMemo(()=>A.filter(ee=>!!ee.readAt),[A]),fe=i.useMemo(()=>X.slice(0,9),[X]),we=_;i.useEffect(()=>{if(!b)return;const ee=me=>{var ie;(ie=J.current)!=null&&ie.contains(me.target)||p(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[b,p]),i.useEffect(()=>{if(!g)return;const ee=me=>{var ie;(ie=ye.current)!=null&&ie.contains(me.target)||v(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[g,v]),i.useEffect(()=>{if(!g&&!b)return;const ee=me=>{if(!me.altKey)return;const ie=me.code.match(/^Digit([1-9])$/);if(!ie)return;const pe=Number(ie[1])-1,le=g?u[pe]:void 0,B=b?fe[pe]:void 0;if(!(!le&&!B)){if(me.preventDefault(),me.stopPropagation(),le){h==null||h(le),v(!1);return}B&&(N(B),p(!1))}};return window.addEventListener("keydown",ee,!0),()=>window.removeEventListener("keydown",ee,!0)},[u,g,b,fe,v,p,N,h]);const be=ee=>{if(!ee)return;const me=n.find(ie=>ie.tabKey===ee);me&&(m==null||m(me))};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(es,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?ut(e):"Dashboard"}),s.jsx("span",{title:ne.title,"aria-label":ne.title,className:"header-title-status-dot",style:{background:Se,boxShadow:ve}}),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:Se,boxShadow:ve}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[ue&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",ue]}),f&&s.jsx("button",{type:"button",onClick:f,className:"btn btn-secondary btn-sm ml-2",title:`${zt}${k!=null&&k.openNewSession?` (${k.openNewSession})`:""}`,"aria-label":zt,children:s.jsx(jc,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[T&&s.jsxs("button",{type:"button",onClick:T,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:"?"}),I&&s.jsx("span",{children:"Guide"})]}),e&&(C||y||!st(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:Is(e)||ut(e),children:ut(e)}),j&&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:()=>j(e.daemonId,e.workspacePath),children:s.jsx(qs,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(qs,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),F&&W&&s.jsxs("button",{type:"button",onClick:()=>W(e),className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",title:"Open live repo mesh graph",children:[s.jsx(as,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:"Mesh graph"})]}),(C||y)&&l&&s.jsxs(s.Fragment,{children:[C&&d&&P&&s.jsx(Yo,{mode:P,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>l(e),className:"btn btn-secondary btn-sm",title:y?"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(wt,{size:14})})]}),!st(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(_o,{size:14})}),!C&&!st(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(_t,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:J,children:[s.jsxs("div",{className:`dashboard-header-hidden${E?" is-drop-target":""}`,ref:ye,onDragEnter:ee=>{ee.dataTransfer.types.includes("text/tab-key")&&(ee.preventDefault(),G(!0))},onDragOver:ee=>{ee.dataTransfer.types.includes("text/tab-key")&&(ee.preventDefault(),ee.dataTransfer.dropEffect="move",G(!0))},onDragLeave:ee=>{ee.currentTarget.contains(ee.relatedTarget)||G(!1)},onDrop:ee=>{const me=ee.dataTransfer.getData("text/tab-key");ee.preventDefault(),G(!1),be(me)},children:[s.jsxs("button",{type:"button",onClick:()=>v(!g),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(Lo,{size:16}),u.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:u.length})]}),g&&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(el,{value:k==null?void 0:k.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[S&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:S,children:"Reset panels"}),u.length>0&&x&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{x(),v(!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(el,{value:k==null?void 0:k.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:ut(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(ee=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(ee),v(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:ut(ee)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(ee)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(ee)+1]}):null,Is(ee)]})]},ee.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!b),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(Hn,{size:16}),we>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:we})]}),b&&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(ee=>s.jsx(tl,{notification:ee,shortcutIndex:fe.indexOf(ee)>=0?fe.indexOf(ee)+1:void 0,onOpen:()=>N(ee),onMarkRead:()=>w(ee.id),onMarkUnread:()=>D(ee.id),onDelete:()=>M(ee.id)},ee.id))]}),xe.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),xe.map(ee=>s.jsx(tl,{notification:ee,onOpen:()=>N(ee),onMarkRead:()=>w(ee.id),onMarkUnread:()=>D(ee.id),onDelete:()=>M(ee.id)},ee.id))]}),A.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 Cx(e,t){return String(e||"")!==String(t||"")}function Ix(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(l=>!(o&&!l.canResume||r&&![l.title,l.preview].map(d=>String(d||"").toLowerCase()).join(`
|
|
41
|
-
`).includes(r)||n&&!String(l.workspace||"").toLowerCase().includes(n)||a&&!
|
|
42
|
-
`).includes(a)))}function Tx(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 md(e,t={}){return Tx(Ix(e,t),t.sortMode||"recent")}function Pn(e){return e?"Resume saved history":"Start fresh"}function Xo(e){return e?"Resuming saved history…":"Starting fresh…"}function Mx(){return"Start fresh"}function pd(e,t=!1){return e==="cli"?Pn(t):e==="ide"?"Start IDE":"Start ACP session"}function hd(e,t=!1){return e==="cli"?Xo(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Ax(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function _x(){return"Open saved history"}function Lx(){return"Saved History"}function Jo(){return"Use saved history when you want continuity in the same provider conversation."}function Rx(){return"No saved history found yet."}function Px(){return"Refresh saved history"}function Dx(){return"Refreshing saved history…"}function gs(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function ys(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 Ys(e){return e==="start-fresh"?"Start fresh":"Restart"}function Xs(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Qo(e){return`Resume saved history with ${e}?`}function Zo(){return"Review or change the target workspace before resuming saved history."}function Ex(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 ei({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:l=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:m,onClose:u,onNewChat:h,onSwitchSession:x,onRefreshHistory:S,onResumeSavedSession:b}){var M;const p=t.find(j=>j.id===e.routeId),g=(p==null?void 0:p.chats)||[],v=(M=p==null?void 0:p.activeChat)==null?void 0:M.id,f=at(e)&&!st(e),[T,I]=i.useState(()=>Ct()),k=c||T,A=String(d||"").trim(),_=j=>{if(m){m(j);return}I(j)},N=i.useMemo(()=>a.map(j=>{const W=String(j.workspace||"").trim();return j.canResume||W||!A?j:{...j,workspace:A,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[A,a]),w=i.useMemo(()=>md(N,{textQuery:k.textQuery,workspaceQuery:k.workspaceQuery,modelQuery:k.modelQuery,resumableOnly:k.resumableOnly,sortMode:k.sortMode}),[N,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:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:f?Lx():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:px(e)}),f&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Jo()})]}),s.jsx("button",{onClick:u,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(wt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!f&&s.jsx("button",{onClick:h,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"}),f?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:j=>_({...k,textQuery:j.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:j=>_({...k,workspaceQuery:j.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:j=>_({...k,modelQuery:j.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:j=>_({...k,sortMode:j.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:j=>_({...k,resumableOnly:j.target.checked})}),"Resume-ready only"]})]}),w.map(j=>{const W=e.providerSessionId===j.providerSessionId,H=W||!j.canResume||!!l,$=j.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{H||!b||b(j)},disabled:H,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${W?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${H?"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 ${W?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:j.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:j.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Ex(j.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:j.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:[j.workspace||"Workspace unknown",$?" · selected workspace":"",Cs(j.summaryMetadata)?` · ${Cs(j.summaryMetadata)}`:"",j.messageCount>0?` · ${j.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:W?"ACTIVE":j.canResume?$?"RESUME IN SELECTED WORKSPACE":l===j.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},j.id)})]}):g.map(j=>s.jsxs("div",{onClick:()=>{x(e.routeId,j.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${v===j.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 ${v===j.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:j.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:[j.id.substring(0,12),"..."]}),v===j.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},j.id)),(f&&!o&&w.length===0||!f&&g.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(op,{size:32})}),s.jsx("div",{className:"text-[13px]",children:f?a.length>0?"No saved history matches these filters.":Rx():"No recent chat sessions found."})]}),f&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Dx()})})]}),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:S,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(Rr,{size:13})," ",f?Px():"Refresh History"]})})})]})]});return typeof document>"u"?D:Tr.createPortal(D,document.body)}const sl={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 fd({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=sl[n.type]||sl.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(wt,{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,l)=>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},l))})]})]},n.id)})})}const $x=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Bx(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function Ox(e){return e.sessionId||e.instanceId||e.agentType}function xa(e,t){return t||e||"unknown"}function xd(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=At(r,{fallbackId:r.id}));return t}function bd(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 ti(e,t={}){return Fx(e,bd(e,t))}function Fx(e,t={}){var h,x,S,b,p;const r=[],n=t.machineName,a=t.connectionState,o=Bx(e),l=e.workspace||"",c=ch(e.type,{agentName:e.cliName}),d=at(e)||st(e)?c:ct(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(g=>{var v,f;return{sessionId:g.id,instanceId:g.id,providerSessionId:g.providerSessionId,transport:g.transport,sessionCapabilities:g.capabilities,agentType:g.providerType,agentName:g.providerName||ct(g.providerType),status:g.status,title:g.title,lastMessagePreview:g.lastMessagePreview,lastMessageRole:g.lastMessageRole,lastMessageAt:g.lastMessageAt,lastMessageHash:g.lastMessageHash,messages:((v=g.activeChat)==null?void 0:v.messages)||[],activeModal:((f=g.activeChat)==null?void 0:f.activeModal)||void 0,unread:g.unread,lastSeenAt:g.lastSeenAt,lastUpdated:g.lastUpdated,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,surfaceHidden:g.surfaceHidden,git:g.git,settings:g.settings,messageInput:g.messageInput}}):[],u=$x(e);if(u){const g=e.sessionId||e.instanceId,v=(h=e.settings)==null?void 0:h.meshCoordinatorFor,f=(x=e.settings)==null?void 0:x.meshNodeFor,T=v?" (Coordinator)":f?" (Mesh Node)":"",I=c+T,k=(S=e.activeChat)==null?void 0:S.activeModal,A=k&&Array.isArray(k.buttons)&&k.buttons.length>0,_=dh(e.activeChat,[{status:e.status,activeModal:(b=e.activeChat)==null?void 0:b.activeModal}],e.agents||[]),N=e.activeChat||{title:"",messages:[]};let w=N.title&&String(N.title).trim()?String(N.title).trim():"";const D=(p=e.activeChat)==null?void 0:p.id,M=e.chats;if(D&&Array.isArray(M)&&M.length>0){const $=M.find(C=>C.id===D||C.id&&String(C.id)===String(D));$!=null&&$.title&&String($.title).trim()&&(w=String($.title).trim())}const j=(at(e)||st(e),e.type),W=(at(e)||st(e))&&Wi(w,I,j)?"":w,H=N.messages||[];r.push({routeId:e.id,sessionId:g,providerSessionId:e.providerSessionId,nativeSessionId:g,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:at(e)?e.mode||"terminal":"chat",agentName:I,agentType:j,status:_,title:W,messages:H,resume:e.resume,hostIdeType:!at(e)&&!st(e)?e.type:void 0,workspaceName:o,workspacePath:l,git:e.git,displayPrimary:W||o||(at(e)?e.mode==="chat"?I:`Terminal${T}`:I),displaySecondary:at(e)&&o?I:d,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:A?k.buttons:void 0,modalMessage:A?k.message:void 0,streamSource:"native",tabKey:xa(g,e.id),machineName:n,connectionState:a,settings:e.settings,messageInput:e.messageInput})}if(u&&(at(e)||st(e)))return r;for(const g of m){const v=g.activeModal&&Array.isArray(g.activeModal.buttons)&&g.activeModal.buttons.length>0,f=uh(g),T=Ox(g),I=`${e.id}:${T}`,k=g.title&&String(g.title).trim()||"",A=Wi(k,g.agentName,g.agentType)?"":k,_=g.messages||[];(g.transport==="cdp-webview"||g.sessionId||g.providerSessionId||_.length>0||v||A||!["idle","panel_hidden","disconnected","not_monitored"].includes(f))&&r.push({routeId:e.id,sessionId:g.sessionId||g.instanceId,providerSessionId:g.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:g.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:g.sessionCapabilities,mode:"chat",agentName:g.agentName,agentType:g.agentType,status:f,title:A,messages:_,hostIdeType:e.type,workspaceName:o,workspacePath:l,git:g.git||e.git,displayPrimary:A||o||g.agentName||d,displaySecondary:`${d} · ${g.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:g.lastMessagePreview,lastMessageRole:g.lastMessageRole,lastMessageAt:g.lastMessageAt,lastMessageHash:g.lastMessageHash,lastUpdated:g.lastUpdated||e.lastUpdated,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,modalButtons:v?g.activeModal.buttons:void 0,modalMessage:v?g.activeModal.message:void 0,streamSource:"agent-stream",tabKey:xa(g.sessionId||g.instanceId,I),machineName:n,connectionState:a,settings:g.settings,messageInput:g.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:l,git:e.git,displayPrimary:o||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:xa(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),r}function gd(e){return String(e.type||e.id||"").trim()}function Wx(e){var t;return e.category!=="cli"||!gd(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 Kx(e){var n;const t=new Set,r=[];for(const a of e||[]){if(!Wx(a))continue;const o=gd(a);if(!o||t.has(o))continue;t.add(o);const l=String(a.displayName||a.name||o),c=a.detectedPath||((n=a.lastDetection)==null?void 0:n.path)||null;r.push({type:o,label:l,icon:a.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c})}return r}function Yn(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 ho(e,t){const r=new Set(t.map(n=>n.type));return Yn(e).filter(n=>r.has(n))}function Hx(e){return e.map(t=>t.type)}function Ux(e,t){const r=Yn(e),n=t.trim();return!n||r.includes(n)?r:[...r,n]}function zx(e,t){return Yn(e).filter(r=>r!==t)}function rl(e,t,r){const n=Yn(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 l=r==="up"?Math.max(0,a-1):Math.min(o.length,a+1);return o.splice(l,0,t),o}function nl({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 al({value:e,availableProviders:t,onChange:r,disabled:n=!1,saveButton:a}){const[o,l]=i.useState(""),c=i.useMemo(()=>new Map(t.map(x=>[x.type,x])),[t]),d=i.useMemo(()=>ho(e,t),[e,t]),m=e.length-d.length,u=t.filter(x=>!d.includes(x.type)),h=()=>{o&&(r(Ux(d,o)),l(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:d.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):d.map((x,S)=>{const b=c.get(x);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:["#",S+1]}),(b==null?void 0:b.icon)&&s.jsx("span",{"aria-hidden":"true",children:b.icon}),s.jsx("span",{className:"font-mono text-[12px] text-text-primary",children:x}),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:b?`${b.label} · ${b.statusLabel}`:x})]}),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||S===0,title:"Move up",onClick:()=>r(rl(d,x,"up")),children:s.jsx(nl,{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||S===d.length-1,title:"Move down",onClick:()=>r(rl(d,x,"down")),children:s.jsx(nl,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>r(zx(d,x)),children:"Remove"})]})]},x)})}),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:x=>l(x.target.value),disabled:n||u.length===0,children:[s.jsx("option",{value:"",children:u.length?"Select provider…":"No additional detected CLI providers"}),u.map(x=>s.jsxs("option",{value:x.type,children:[x.label," (",x.type,")"]},x.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:n||!o,onClick:h,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 Vx(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 yd(e,t){const r=Vx(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const vd=[{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:"🏄"}],wd=[{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:"🧩"}],jd=[{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:"🟠"}],Gx=vd,qx=wd,Yx=jd;function ts(...e){return um(mm(e))}function Xx({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:ts("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:l,children:c}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(Xx,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:ts("mx-auto flex w-full flex-col gap-4",o,l),children:c})})]})}const fo="adhdev:themechange";function Jx(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Ds(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Es(e){return e==="system"?Jx():e}function kd(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function xn(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(fo,{detail:{preference:e,theme:t}}))}function Qx(){const e=Ds(),t=Es(e);kd(t),xn(e,t)}function er(){const[e,t]=i.useState(Ds),[r,n]=i.useState(()=>Es(Ds()));i.useEffect(()=>{kd(r)},[r]),i.useEffect(()=>{const l=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const m=d.matches?"light":"dark";n(m),xn("system",m)}};return l.addEventListener("change",c),()=>l.removeEventListener("change",c)},[e]),i.useEffect(()=>{const l=d=>{const m=d.detail||{},u=m.preference,h=m.theme;t(u==="dark"||u==="light"||u==="system"?u:Ds()),n(h==="dark"||h==="light"?h:Es(Ds()))},c=d=>{if(d.key!=="theme")return;const m=Ds(),u=Es(m);t(m),n(u)};return window.addEventListener(fo,l),window.addEventListener("storage",c),()=>{window.removeEventListener(fo,l),window.removeEventListener("storage",c)}},[]);const a=i.useCallback(l=>{const c=Es(l);t(l),n(c);try{localStorage.setItem("theme",l)}catch{}xn(l,c)},[]),o=i.useCallback(()=>{t(l=>{const c=l==="dark"?"light":l==="light"?"system":"dark",d=Es(c);n(d);try{localStorage.setItem("theme",c)}catch{}return xn(c,d),c})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const ol={dark:"Dark",light:"Light",system:"System"};function Zx({collapsed:e}){const{preference:t,cycleTheme:r}=er(),n=t==="dark"?s.jsx(lp,{size:16}):t==="light"?s.jsx(ip,{size:16}):s.jsx(cp,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${ol[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:ol[t]})]})}function ba(e,t){return e?typeof e=="function"?e(t):e:null}function eb({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:l,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const[m,u]=i.useState(!1),[h,x]=i.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),S=()=>u(!0),b=()=>u(!1),p=()=>{x(T=>{const I=!T;try{localStorage.setItem(d,I?"1":"0")}catch{}return I})},g=i.useMemo(()=>({collapsed:h,mobileMenuOpen:m,openMobileMenu:S,closeMobileMenu:b,toggleCollapsed:p}),[h,m]),v=T=>`nav-item${T.active?" active":""} cursor-pointer ${h?"justify-center py-2.5 px-0":""}${T.className?` ${T.className}`:""}`,f=T=>s.jsxs("div",{className:v(T),id:`nav-${T.id}`,onClick:()=>{T.onSelect(),b()},title:h?T.title??(typeof T.label=="string"?T.label:void 0):T.title,children:[s.jsx("span",{className:"nav-icon",children:T.icon}),!h&&T.label]},T.id);return s.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${h?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:S,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:b,onKeyDown:T=>T.key==="Escape"&&b()}),s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${h?"justify-center gap-0":""}`,children:ba(t,g)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:b,children:s.jsx(wt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(f)}),n.map(T=>s.jsxs("div",{className:T.className??"border-t border-border-subtle pt-2 mt-2",children:[!h&&T.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:T.title}):null,T.items.map(f)]},T.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(f),ba(o,g),s.jsx(Zx,{collapsed:h}),ba(l,g)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function St({title:e,icon:t,description:r,accentColor:n,className:a,children:o}){return s.jsxs("div",{className:ts("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 Dn({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:ts("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 tb={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"},sb={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Os({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:ts("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",tb[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:sb[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 Lt({label:e,hint:t,children:r,className:n}){return s.jsxs("div",{className:ts("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 ga(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:ts("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 rb={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"},nb={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function ab({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:ts("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",rb[e],r),children:[s.jsx("span",{className:ts("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",nb[e])}),n]})}function hs({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 ob({onPrefChange:e}){const[t,r]=wh(),[n,a]=i.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);i.useEffect(()=>{const l=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return l(),window.addEventListener("focus",l),document.addEventListener("visibilitychange",l),()=>{window.removeEventListener("focus",l),document.removeEventListener("visibilitychange",l)}},[]);const o=(l,c)=>{r({[l]:c}),e==null||e(l,c)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(hs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Hn,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:l=>o("globalEnabled",l)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(hs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_t,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:l=>o("browserNotifications",l)}),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:()=>{$c().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(hs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(dp,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:l=>o("completionAlert",l)}),s.jsx(hs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(up,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:l=>o("approvalAlert",l)}),s.jsx(hs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(zs,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:l=>o("disconnectAlert",l)})]}),!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 En(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function ib(e,t){const r=En(e),n=En(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 Sd(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function Sr(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||ib(r,t)>=0)return!1;const n=En(r),a=En(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function lb(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function ya(e,t){return e instanceof Error?e.message:t}function cb({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const o=e.filter(l=>l.type==="adhdev-daemon");return o.length===0?s.jsx(Dn,{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(l=>s.jsx(ub,{ide:l,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},l.id))})}function il({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:o}){const l=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return Tr.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 ${l}`,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 db(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Gx,...qx,...Yx].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 ub({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var H,$;const[o,l]=i.useState("idle"),[c,d]=i.useState(""),[m,u]=i.useState(null),[h,x]=i.useState("idle"),[S,b]=i.useState(""),p=e.version||null,g=((H=e.machine)==null?void 0:H.platform)||(($=e.system)==null?void 0:$.platform)||"",v=At(e,{fallbackId:e.id}),f=g==="win32"?"🪟":g==="darwin"?"🍎":"🐧",T=t.filter(C=>C.daemonId===e.id&&C.transport==="cdp-page"),I=t.filter(C=>C.daemonId===e.id&&C.transport==="pty"),k=t.filter(C=>C.daemonId===e.id&&C.transport==="acp"),A=e.p2p,_=async()=>{if(r){l("upgrading"),d("Starting upgrade...");try{const C=lb(await r(e.id,"daemon_upgrade",{}));C.alreadyLatest?(l("done"),d(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(l("done"),d(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(l("error"),d(C.error||"Upgrade failed"))}catch(C){l("error"),d(ya(C,"Connection lost during upgrade"))}}},N=async()=>{if(u(null),!!n){x("loading");try{await n(e.id),x("done"),b("Machine disconnected.")}catch(C){x("error"),b(ya(C,"Failed to disconnect"))}}},w=async()=>{if(u(null),!!a){x("loading");try{await a(e.id),x("done"),b("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(C){x("error"),b(ya(C,"Failed to revoke token"))}}},D="0.9.81",M=Sd(e,D),j=Sr(e,D),W=T.length+I.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:f}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:v}),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),"…"]}),p&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${M?"":"bg-bg-secondary"}`,style:M?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",p,!M&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&M&&s.jsx("button",{onClick:_,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":`${j?"↑ Update now":`↑ Update${` to v${D}`}`}`}),n&&s.jsx("button",{onClick:()=>u("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>u("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(ab,{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:[A&&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 ${A.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${A.state==="connecting"||A.state==="new"?"animate-pulse":""}`,style:A.state==="connecting"||A.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",A.state==="connected"?"connected":A.state==="connecting"||A.state==="new"?"connecting...":A.state||"off"]}),A.peers!==void 0&&A.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",A.peers," peer",A.peers!==1?"s":"",")"]})]}),A&&W>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),W>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[T.map(C=>{const y=db(C.type),F=C.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:y.icon}),s.jsx("span",{children:y.name}),F!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${F?"bg-green-400":"animate-pulse"}`,style:F?void 0:{background:"var(--status-warning)"},title:F?"CDP connected":"CDP connecting..."})]},C.id)}),I.map(C=>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:C.cliName||"CLI"})]},C.id)),k.map(C=>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:C.cliName||"ACP"})]},C.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(c||S)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||h==="error"?"text-red-400":o==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:S||c})]}),m==="disconnect"&&s.jsx(il,{title:"🔌 Disconnect Machine",message:`Disconnect "${v}" from ADHDev?
|
|
40
|
+
\`\`\``}function ma(e,t){return`${e}:${t}`}function xf(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function dr(e,t){xf()&&console.debug(`[subscription-manager] ${e}`,t)}class bf{constructor(){Ze(this,"active",new Map);Ze(this,"retryTimers",new Map)}subscribe(t,r,n,a,o){var u;const l=ma(n.topic,n.key),c=this.active.get(l);let d=!0;if(c)c.handlers.add(a),c.lastUpdate&&a(c.lastUpdate);else{const h={daemonId:r,request:n,handlers:new Set([a])};this.active.set(l,h),dr("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((u=t.sendData)==null?void 0:u.call(t,r,n))??!1,!d&&(o!=null&&o.retryIntervalMs)&&this.scheduleRetry(l,t,o.retryIntervalMs)}const m=()=>{var S;this.clearRetry(l);const h=this.active.get(l);if(!h||(h.handlers.delete(a),h.handlers.size>0))return;this.active.delete(l);const x={type:"unsubscribe",topic:n.topic,key:n.key};dr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(S=t.sendData)==null||S.call(t,r,x)};return m.initialSendAccepted=d,m}publish(t){const r=ma(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,Hs.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),Hs.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=ma(t,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(t){var r;dr("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);dr("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 l=((c=r.sendData)==null?void 0:c.call(r,o.daemonId,o.request))??!1;dr("subscribe_retry",{id:t,accepted:l,topic:o.request.topic,key:o.request.key}),l||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 bf;function gf(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});for(const o of n.childSessions||[]){if(!(o!=null&&o.id))continue;const l=r.get(o.id)||{};r.set(o.id,{...l,...o})}}return r}function yf(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 pa(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function vf(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function wf(e){vf()&&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 Rn(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:o,timestamp:l}=t,c=l||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:m,childrenByParent:u}=yf(d),h=gf(o,n),x=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,S=m.filter(g=>g.kind==="workspace"&&g.transport==="cdp-page"),b=m.filter(g=>g.kind==="agent"&&g.transport==="pty"),p=m.filter(g=>g.kind==="agent"&&g.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:c,...e.version&&{version:e.version},...x&&{machine:x,platform:x.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:S.some(g=>!!g.cdpConnected)});for(const g of S){const v=h.get(g.id),f=br(g,v),C=(u.get(g.id)||[]).map(T=>br(T,h.get(T.id)));r.push({id:`${n}:ide:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:f.parentId,sessionKind:f.kind,transport:f.transport,sessionCapabilities:f.capabilities,type:f.providerType,status:f.cdpConnected?"online":"detected",daemonId:n,instanceId:pa(n,g.id),workspace:f.workspace,terminals:0,childSessions:C,agents:C.map(T=>({id:T.id,name:T.providerName||T.providerType,type:T.providerType,status:T.status})),activeChat:f.activeChat,chats:[],cdpConnected:f.cdpConnected,...f.lastMessagePreview!==void 0&&{lastMessagePreview:f.lastMessagePreview},...f.lastMessageRole!==void 0&&{lastMessageRole:f.lastMessageRole},...f.lastMessageAt!==void 0&&{lastMessageAt:f.lastMessageAt},...f.lastMessageHash!==void 0&&{lastMessageHash:f.lastMessageHash},lastUpdated:f.lastUpdated,unread:f.unread,lastSeenAt:f.lastSeenAt,inboxBucket:f.inboxBucket,completionMarker:f.completionMarker,seenCompletionMarker:f.seenCompletionMarker,surfaceHidden:f.surfaceHidden,...f.controlValues!==void 0&&{controlValues:f.controlValues},...f.providerControls!==void 0&&{providerControls:f.providerControls},...f.summaryMetadata!==void 0&&{summaryMetadata:f.summaryMetadata},...f.settings!==void 0&&{settings:f.settings},...f.messageInput!==void 0&&{messageInput:f.messageInput},timestamp:c})}for(const g of b){const v=h.get(g.id),f=br(g,v);r.push({id:`${n}:cli:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:f.parentId,sessionKind:f.kind,transport:f.transport,sessionCapabilities:f.capabilities,type:f.providerType,agentType:f.providerType,status:f.status||"running",daemonId:n,instanceId:pa(n,g.id),cliName:f.providerName||f.providerType,mode:f.mode||(v==null?void 0:v.mode)||"terminal",workspace:f.workspace||"",activeChat:f.activeChat,...f.resume!==void 0&&{resume:f.resume},...f.runtimeKey!==void 0&&{runtimeKey:f.runtimeKey},...f.runtimeDisplayName!==void 0&&{runtimeDisplayName:f.runtimeDisplayName},...f.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:f.runtimeWorkspaceLabel},...f.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:f.runtimeWriteOwner},...f.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:f.runtimeAttachedClients},...f.lastMessagePreview!==void 0&&{lastMessagePreview:f.lastMessagePreview},...f.lastMessageRole!==void 0&&{lastMessageRole:f.lastMessageRole},...f.lastMessageAt!==void 0&&{lastMessageAt:f.lastMessageAt},...f.lastMessageHash!==void 0&&{lastMessageHash:f.lastMessageHash},lastUpdated:f.lastUpdated,unread:f.unread,lastSeenAt:f.lastSeenAt,inboxBucket:f.inboxBucket,completionMarker:f.completionMarker,seenCompletionMarker:f.seenCompletionMarker,surfaceHidden:f.surfaceHidden,...f.controlValues!==void 0&&{controlValues:f.controlValues},...f.providerControls!==void 0&&{providerControls:f.providerControls},...f.summaryMetadata!==void 0&&{summaryMetadata:f.summaryMetadata},...f.settings!==void 0&&{settings:f.settings},...f.messageInput!==void 0&&{messageInput:f.messageInput},timestamp:c,_isCli:!0})}for(const g of p){const v=h.get(g.id),f=br(g,v);r.push({id:`${n}:acp:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:f.parentId,sessionKind:f.kind,transport:f.transport,sessionCapabilities:f.capabilities,type:f.providerType,agentType:f.providerType,status:f.status||"running",daemonId:n,instanceId:pa(n,g.id),cliName:f.providerName||f.providerType,mode:"chat",workspace:f.workspace||"",activeChat:f.activeChat,...f.runtimeKey!==void 0&&{runtimeKey:f.runtimeKey},...f.runtimeDisplayName!==void 0&&{runtimeDisplayName:f.runtimeDisplayName},...f.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:f.runtimeWorkspaceLabel},...f.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:f.runtimeWriteOwner},...f.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:f.runtimeAttachedClients},...f.lastMessagePreview!==void 0&&{lastMessagePreview:f.lastMessagePreview},...f.lastMessageRole!==void 0&&{lastMessageRole:f.lastMessageRole},...f.lastMessageAt!==void 0&&{lastMessageAt:f.lastMessageAt},...f.lastMessageHash!==void 0&&{lastMessageHash:f.lastMessageHash},lastUpdated:f.lastUpdated,unread:f.unread,lastSeenAt:f.lastSeenAt,inboxBucket:f.inboxBucket,completionMarker:f.completionMarker,seenCompletionMarker:f.seenCompletionMarker,surfaceHidden:f.surfaceHidden,...f.controlValues!==void 0&&{controlValues:f.controlValues},...f.providerControls!==void 0&&{providerControls:f.providerControls},...f.summaryMetadata!==void 0&&{summaryMetadata:f.summaryMetadata},...f.settings!==void 0&&{settings:f.settings},...f.messageInput!==void 0&&{messageInput:f.messageInput},timestamp:c,_isAcp:!0})}return wf(r),r}const jf=15e3,kf=15e3,Sf=6e4,Nf=1200,qi=12,Cf=8e3,If=4e3,ha=new Map,fa=new Map,Qr=new Set,jr=new Map;function Tf(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 Yi(e,t){const r=jr.get(e);!r||r.size===0||(jr.delete(e),r.forEach(n=>n(t)))}function Mf(e,t){return new Promise(r=>{const n=jr.get(e)||new Set;jr.set(e,n);const a=l=>{clearTimeout(o),n.delete(a),n.size===0&&jr.delete(e),r(l)},o=setTimeout(()=>a(!1),t);n.add(a)})}function Er(){const{sendCommand:e,sendData:t}=jt(),{injectEntries:r,getIdes:n}=Mr();return i.useCallback(async(a,o)=>{if(!a)return;const l=(o==null?void 0:o.minFreshMs)??Sf,c=fa.get(a)||0;if(!(o!=null&&o.force)&&Qr.has(a)&&c>0||!(o!=null&&o.force)&&c>0&&Date.now()-c<l)return;const d=ha.get(a);if(d)return d;const m=(async()=>{if(t&&!Qr.has(a)){const p=Qt.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},g=>{const v=n(),f=v.find(T=>T.id===a),C=Rn(g.status,{daemonId:a,existingDaemon:f,existingEntries:v,timestamp:g.timestamp});C.length>0&&r(C),fa.set(a,Date.now()),Yi(a,!0)});if(p.initialSendAccepted?Qr.add(a):Qr.delete(a),!(o!=null&&o.force)&&p.initialSendAccepted&&await Mf(a,Nf))return}const u=await e(a,"get_status_metadata"),h=Tf(u);if(!h)return;const x=n(),S=x.find(p=>p.id===a),b=Rn(h,{daemonId:a,existingDaemon:S,existingEntries:x,timestamp:h.timestamp||Date.now()});b.length>0&&r(b,{authoritativeDaemonIds:[a]}),fa.set(a,Date.now()),Yi(a,!0)})().finally(()=>{ha.delete(a)});return ha.set(a,m),m},[n,r,e,t])}function Af(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const _f=60,Lf=50;function Zc(e={}){return e.isCliLike?Lf:_f}function Rf(e={}){return Zc(e)}function Tt(e){return(typeof e=="string"?e.trim():"")||void 0}function Jt(e,t){const r=Tt(t);return r?`${e}:${r}`:void 0}function os(e,t,r){const n=Jt(t,r),a=Tt(r);n&&e.push(n),a&&e.push(a)}function Bs(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function ed(e){return Tt(e.providerSessionId)||Tt(e.sessionId)||Tt(e.tabKey)||Tt(e.routeId)}function Vo(e){return Bs([Tt(e.providerSessionId),Tt(e.sessionId)])}function Ks(e){const t=[];return os(t,"provider",e.providerSessionId),os(t,"session",e.sessionId),os(t,"tab",e.tabKey),os(t,"route",e.routeId),Bs(t)}function Pf(e){const t=[];return Tt(e.providerSessionId)?(os(t,"provider",e.providerSessionId),Bs(t)):Tt(e.sessionId)?(os(t,"session",e.sessionId),Bs(t)):Tt(e.tabKey)?(os(t,"tab",e.tabKey),Bs(t)):Tt(e.routeId)?(os(t,"route",e.routeId),Bs(t)):[]}function Go(e){return Jt("provider",e.providerSessionId)||Jt("session",e.sessionId)||Jt("tab",e.tabKey)||Jt("route",e.routeId)||"unknown:"}function $r(e){return Vo(e)[0]}function Df(e){const t=Tt(e.providerSessionId),r=Tt(e.sessionId),n=Tt(e.tabKey),a=Tt(e.routeId),o=[Jt("provider",t),Jt("session",r),Jt("tab",n),Jt("route",a)].filter(d=>typeof d=="string"),l=Ks({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),c=Go({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:c,targetKey:c,targetValue:ed({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:$r({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:l}}function uo(e,t){const r=Df(e);return Pf(t).some(n=>r.lookupKeys.includes(n))}const Br=60,Ef=1e3,qo=12e4,$f=new Set(["generating","waiting_approval","starting","streaming","working"]),Xi=new Map;function td(e,t){return`${e}::${t}`}function mo(e=Br){return{liveMessages:[],hasLiveSnapshot:!1,cursor:Bf([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Bf(e,t=Br){return{tailLimit:t}}function Ji(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("|")}class Of{constructor(t){Ze(this,"manager");Ze(this,"sendData");Ze(this,"daemonId");Ze(this,"sessionId");Ze(this,"historySessionId");Ze(this,"subscriptionKey");Ze(this,"fallbackRecentCount");Ze(this,"snapshot");Ze(this,"transportSubscription",null);Ze(this,"listeners",new Set);Ze(this,"retainCount",0);Ze(this,"loadHistoryPromise",null);Ze(this,"pendingDisconnectTimer",null);this.manager=t.manager||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=mo(Math.max(0,t.tailLimit??Br))}updateOptions(t){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 r=Math.max(0,t.tailLimit);r!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect()))}}getSnapshot(){return this.snapshot}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}),l=Array.isArray(o.messages)?o.messages:[],c=!n&&l.length===0&&o.hasMore!==!0&&this.fallbackRecentCount>0;this.snapshot={...this.snapshot,historyMessages:[...l,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+l.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:Ef}))}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=Array.isArray(t.messages)?t.messages:[],n={tailLimit:this.snapshot.cursor.tailLimit};Ji(this.snapshot.liveMessages)===Ji(r)&&this.snapshot.cursor.tailLimit===n.tailLimit||(this.snapshot={...this.snapshot,liveMessages:r,hasLiveSnapshot:!0,cursor:n},this.emit())}}function sd(e){const t=td(e.daemonId,e.sessionId),r=Xi.get(t);if(r)return r.updateOptions(e),r;const n=new Of(e);return Xi.set(t,n),n}function Ff(e,t){return{...e,loadHistoryPage:t}}function Wf(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function Kf(e,t={}){const r=String(e.status||"").trim().toLowerCase();if($f.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??qo)),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 Hf(e=qo){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Uf(e,t={}){const r=new Set,n=[];for(const a of e){if(!Kf(a,t))continue;const o=Dr(a),l=a.sessionId||"";if(!o||!l)continue;const c=td(o,l);if(r.has(c))continue;r.add(c);const d=$r(a);n.push({daemonId:o,sessionId:l,historySessionId:d||l,subscriptionKey:`daemon:${o}:session:${l}`})}return n.sort(Wf),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function zf(e,t){const{sendData:r,sendCommand:n}=jt(),a=(t==null?void 0:t.enabled)!==!1,o=Dr(e),l=e.sessionId||"",c=$r(e)||l,d=`daemon:${o}:session:${l}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??Br),u=i.useMemo(()=>!a||!o||!l?null:sd({daemonId:o,sessionId:l,historySessionId:c,subscriptionKey:d,sendData:r,tailLimit:m,fallbackRecentCount:e.messages.length}),[e.messages.length,o,a,c,r,l,d,m]),[h,x]=i.useState(()=>(u==null?void 0:u.getSnapshot())||mo(m));i.useEffect(()=>{if(!u){x(mo(m));return}u.retain(),x(u.getSnapshot());const b=u.subscribe(p=>{x(p)});return()=>{b(),u.release()}},[u,m]);const S=i.useCallback(async()=>{!u||!o||!l||await u.loadHistoryPage(async({offset:b,excludeRecentCount:p})=>{const g=e.agentType,v=await n(o,"chat_history",{agentType:g,offset:b,limit:30,targetSessionId:l,historySessionId:c,excludeRecentCount:p}),f=v&&typeof v=="object"&&"result"in v?v.result||{}:v||{};return{messages:Array.isArray(f.messages)?f.messages:[],hasMore:f.hasMore===!0}})},[e.agentType,u,o,c,n,l]);return i.useMemo(()=>Ff(h,S),[S,h])}function Vf(e,t){const{sendData:r}=jt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??Br),o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??qo)),l=Hf(o),[c,d]=i.useState(0);i.useEffect(()=>{if(!n||e.length===0)return;const u=setInterval(()=>{d(h=>h+1)},l);return()=>{clearInterval(u)}},[e.length,n,l]);const m=i.useMemo(()=>Uf(e,{recentActivityMs:o}),[e,o,c]);i.useEffect(()=>{if(!n||!r||m.descriptors.length===0)return;const u=m.descriptors.map(h=>sd({...h,sendData:r,tailLimit:a}));return u.forEach(h=>{h.retain()}),()=>{u.forEach(h=>h.release())}},[m.signature,n,r,a])}function Gf(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function Qi(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 qf(e,t){if(e.length===0)return[];if(t.some(Qi))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||!Qi(o))continue;const l=String(o.role||"").toLowerCase();n.has(l)||(n.add(l),r.unshift(o))}return r}function Yf(e){const{historyMessages:t,liveMessages:r,visibleLiveCount:n}=e,a=Math.max(0,r.length-n),o=a>0?r.slice(0,a):[],l=a>0?r.slice(-n):r,c=qf(o,l),d=c.length>0?[...c,...l]:l;return t.length===0?d:[...t,...d]}function Xf(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Jf(e){return Xf(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}function Qf(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function Zf(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function ex(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function rd(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function nd(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 tx(e){return rd(e)?!1:e.inboxBucket==="task_complete"&&nd(e).length>0}function Zi(e){return e.branch||"detached HEAD"}function sx(e){if(e.error)return`${Zi(e)} · Git error: ${e.error}`;const t=[Zi(e)];return e.changedFiles>0?t.push(Qf(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 rx(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${sx(t)}`}function nx(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function ax(e,t={}){if(t.enabled===!1)return[];if(!ex(e))return[];const r=rd(e)?"working":tx(e)?"complete":null;if(!r)return[];const n=r==="complete"?nd(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${Zf(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:rx(r,e.git),timestamp:nx(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 ox=60;function po({activeConv:e,ideEntry:t,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:o,isFocusingAgent:l,actionLogs:c,userName:d,scrollToBottomRequestNonce:m,isInputActive:u=!0,isVisible:h=!0}){var Ce,ee,me,ie,pe,le,B;const x=i.useRef(new Map),S=i.useRef(void 0),b=Er(),{sendCommand:p}=jt(),{isVisible:g}=Oo();Pr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:c.length,isSendingChat:n});const v=Nt.useMemo(()=>Qs(e),[e.status,e.connectionState]),f=i.useMemo(()=>nf(e,t),[e,t]),C=i.useMemo(()=>{var z;return Ko((z=f.targetEntry)==null?void 0:z.providerControls,{hostIdeType:e.hostIdeType,providerType:f.providerType})},[e.hostIdeType,f.providerType,(Ce=f.targetEntry)==null?void 0:Ce.providerControls]),T=Zc({isCliLike:f.isCli||f.isAcp}),k=Rf({isCliLike:f.isCli||f.isAcp}),A=zf(e,{enabled:h&&!!e.sessionId,tailLimit:k}),[_,N]=i.useState(T),[w,D]=i.useState(()=>Ri()),M=e.tabKey,j=A.historyMessages,W=A.hasMoreHistory,H=A.historyError,$=Gf(e,A),I=Nc($).length;i.useEffect(()=>{N(T)},[T,M]);const y=Math.max(0,$.length-_),F=Ho(e),P=Dr(e),E=Jf(e),G=Uo(e),J=a||G,ye=!!G,[he,ne]=i.useState(!1);i.useEffect(()=>{const z=f.targetEntry;P&&(!z||z.providerControls===void 0||z.controlValues===void 0)&&b(P,{minFreshMs:3e4}).catch(()=>{})},[P,f.isAcp,(ee=f.targetEntry)==null?void 0:ee.providerControls,(me=f.targetEntry)==null?void 0:me.controlValues,b]);const ue=i.useCallback(async()=>{if(!he){if($.length>_){N(z=>Math.min($.length,z+ox));return}ne(!0);try{await A.loadHistoryPage()}finally{ne(!1)}}},[A,he,$.length,_]),{allMessages:Se,receivedAtMap:ve}=i.useMemo(()=>{const z=Yf({historyMessages:j,liveMessages:$,visibleLiveCount:_}),de=ax(e),re=de.length>0?[...z,...de]:z,R={};return re.forEach((q,ce)=>{const Ne=`${e.tabKey}:${In(q,ce)}`;let je=Af(q)||x.current.get(Ne)||0;je||(je=Date.now(),x.current.set(Ne,je)),R[In(q,ce)]=je}),{allMessages:re,receivedAtMap:R}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,y,j,$,_]),X=i.useMemo(()=>c.filter(z=>z.routeId===e.tabKey).sort((z,de)=>z.timestamp-de.timestamp),[c,e.tabKey]),xe=i.useCallback(async()=>{var ce,Ne;if(!P)return;const z=Yc({activeConv:e,visibleMessages:Se,actionLogs:c,controls:(ce=f.targetEntry)==null?void 0:ce.providerControls,controlValues:(Ne=f.targetEntry)==null?void 0:Ne.controlValues,visibleBarControlCount:C.length,chatTailState:{liveMessages:A.liveMessages,hasLiveSnapshot:A.hasLiveSnapshot,hasMoreHistory:W,historyError:H,historyMessages:j},ui:{controlsVisible:g,visibleLiveCount:_,activityVisible:w,activityCount:I,hiddenLiveCount:y,isInputActive:u,isVisible:h}}),de=await p(P,"get_chat_debug_bundle",{agentType:f.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:z}),re=Ln(de),R=Qc(re),q=await Jc(R);q==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),it.showToast(Xc(re,{locatorCopyStatus:q}),q==="failed"?"warning":"success")},[e,c,I,Se,g,A.hasLiveSnapshot,A.liveMessages,f.providerType,(ie=f.targetEntry)==null?void 0:ie.controlValues,(pe=f.targetEntry)==null?void 0:pe.providerControls,P,W,y,j,u,h,H,p,w,C.length,_]),fe=i.useCallback(()=>{D(z=>{const de=!z;return Tp(de),de})},[]);i.useEffect(()=>{const z=de=>{de.key===Do&&D(Ri())};return window.addEventListener("storage",z),()=>window.removeEventListener("storage",z)},[]);const we=i.useCallback(()=>{const z=ff(S.current);S.current=z.state,z.shouldCollect&&xe().catch(de=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",de),it.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[xe]),be=i.useMemo(()=>{if($.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((v.isGenerating||e.status==="streaming")&&ne(!1),e.status==="not_monitored"&&E)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(zs,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),s.jsx("button",{onClick:o,disabled:l,className:"btn btn-primary",children:l?"⌛ Switching...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ns,{size:14})," Open ",F," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&E)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(wc,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),s.jsx("button",{onClick:o,disabled:l,className:"btn btn-primary",children:l?"⌛ Opening...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ns,{size:14})," Open ",F," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!he)return!W&&j.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,E,o,W,j.length,l,he,$.length,F,v.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[s.jsx("div",{className:"chat-activity-toggle-bar",children:s.jsxs("button",{type:"button",className:`chat-activity-toggle ${w?"chat-activity-toggle-active":""}`,onClick:fe,"aria-pressed":w,title:"Show tool, terminal, and runtime activity rows",children:[s.jsx("span",{className:"chat-activity-toggle-dot"}),"Activity",I>0&&s.jsx("span",{className:"chat-activity-toggle-count",children:I})]})}),s.jsx(Hp,{messages:Se,actionLogs:X,agentName:Vs(e)||F||"Agent",userName:d,isCliMode:f.isCli||f.isAcp,isWorking:v.isGenerating,contextKey:e.tabKey,receivedAtMap:ve,lastMessageHash:e.lastMessageHash,showActivityMessages:w,onLoadMore:ue,isLoadingMore:he,hasMoreHistory:W,hiddenLiveCount:y,loadError:H??void 0,emptyState:be,scrollToBottomRequestNonce:m,isVisible:h}),s.jsx(Vh,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:f.providerType,displayLabel:f.displayLabel,controls:(le=f.targetEntry)==null?void 0:le.providerControls,controlValues:(B=f.targetEntry)==null?void 0:B.controlValues,isActive:u,isCliTerminal:f.isCliTerminal}),!f.isCliTerminal&&s.jsx(Wc,{contextKey:e.tabKey,panelLabel:F,isSending:n,isBusy:ye,statusMessage:J,onSend:r,isActive:u,showControlsToggle:C.length>0,onControlsToggle:we,messageInput:e.messageInput})]})}let ad=cs;function od(){return ad()}class ix{constructor(){Ze(this,"listeners",new Map)}send(t){}isConnected(){return!1}on(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{var n;(n=this.listeners.get(t))==null||n.delete(r)}}emit(t,...r){var n;(n=this.listeners.get(t))==null||n.forEach(a=>a(...r))}}let id=new ix;class lx{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 mt=new lx;function cx(e){e.dashboardWS&&(id=e.dashboardWS),e.connectionManager&&(mt=e.connectionManager),e.useDaemonsHook&&(ad=e.useDaemonsHook)}const dx=.5,ux=1.25;function ut(e){return Ho(e)}function Is(e){return Vc(e).join(" · ")}function ld(e){const t=zc(e);return t||(e.title?e.title:Is(e)||"No messages yet")}function cd(e,t){const{isReconnecting:r,isConnecting:n}=Qs(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function mx(e,t){const r=["Chat",...Vc(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function bs(e){return cd(e)||Is(e)}function px(e){return`${ut(e)} · ${ld(e)}`}function hx(e){const t=_n(e),r=t?ct(t):Vs(e);return`${ut(e)} — ${r||"Agent"}`}function fx(e){return Vs(e)||"CLI"}function dd(e){return Uc(e)}function ud(e){return e?`Remote · ${ut(e)||e.workspaceName||"Session"}`:"Remote"}function xx({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:l=!0,isInputActive:c=!0}){var ae;cs();const{sendPtyInput:d}=jt(),[m,u]=i.useState(!1),h=i.useRef(!1);h.current=m;const[x,S]=i.useState("Runtime terminal unavailable"),[b,p]=i.useState(!1),[g,v]=i.useState(null),[f,C]=i.useState(!1),[T,k]=i.useState(!1),[A,_]=i.useState(1),[N,w]=i.useState(!1),[D,M]=i.useState({width:0,height:0}),[j,W]=i.useState({width:0,height:0}),[H,$]=i.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[I,y]=i.useState(null),F=i.useRef(null),P=i.useRef(null),E=i.useRef(!1),G=i.useRef(!1),J=i.useRef(l),ye=i.useRef(0),he=i.useRef(!1),ne=i.useRef(""),ue=i.useRef(null),Se=i.useRef(!1),ve=i.useRef(!1),X=i.useRef(null),xe=i.useRef(null),fe=i.useRef(null),we=32*1024,be=()=>{var K,Y,se,oe;return((Y=(K=F.current)==null?void 0:K.ownerDocument)==null?void 0:Y.defaultView)||((oe=(se=P.current)==null?void 0:se.ownerDocument)==null?void 0:oe.defaultView)||window},Ce=K=>{const Y=be();return{ownerWindow:Y,frameId:Y.requestAnimationFrame(K)}},ee=()=>{const K=X.current;if(K){try{K.ownerWindow.cancelAnimationFrame(K.frameId)}catch{}X.current=null}},me=()=>{const K=xe.current;if(K){try{K.ownerWindow.clearTimeout(K.timeoutId)}catch{}xe.current=null}},ie=()=>{const K=fe.current;if(K){try{K.ownerWindow.clearTimeout(K.timeoutId)}catch{}fe.current=null}},pe=()=>{l&&X.current===null&&(X.current=Ce(()=>{rt()}))},le=e.tabKey,B=e.sessionId||"",z=e.daemonId||((ae=e.routeId)==null?void 0:ae.split(":")[0])||e.routeId||"",de=Uo(e),re=m?o||de:x,R=dx,q=ux,ce=.05,Ne=()=>{const K=j.width,Y=j.height;if(!Number.isFinite(D.width)||D.width<=0||!Number.isFinite(D.height)||D.height<=0||!Number.isFinite(K)||K<=0||!Number.isFinite(Y)||Y<=0)return 1;const se=D.width/K,oe=D.height/Y;return Number(Math.min(q,Math.max(R,Math.min(se,oe))).toFixed(2))},je=Ne(),O=E.current&&A>je,Ie=Number.isFinite(j.width)&&j.width>0?Math.max(D.width,Math.round(j.width*A)):D.width,Le=Number.isFinite(j.height)&&j.height>0?Math.max(D.height,Math.round(j.height*A)):D.height,He=()=>{Ce(()=>{const K=P.current;K&&(K.scrollLeft=0,K.scrollTop=K.scrollHeight-K.clientHeight)})},ze=()=>{var K,Y;ye.current=0,he.current=!1,ne.current="",ue.current=null,Se.current=!1,ve.current=!1,E.current||(G.current=!1,_(1)),X.current!==null&&ee(),u(!1),S("Runtime terminal unavailable"),ie(),me(),v(null),y(null),w(!1),p(!1),C(!1),k(!1),(Y=(K=r.current)==null?void 0:K.reset)==null||Y.call(K)},Xe=()=>{var K,Y;ye.current=0,he.current=!1,ne.current="",ue.current=null,Se.current=!1,ve.current=!1,X.current!==null&&ee(),u(!0),S(""),ie(),me(),v(null),y(null),w(!1),p(!1),C(!1),k(!1),(Y=(K=r.current)==null?void 0:K.reset)==null||Y.call(K)},Je=()=>{ve.current&&(ve.current=!1,Ce(()=>{var K,Y;(Y=(K=r.current)==null?void 0:K.scrollToTop)==null||Y.call(K)}))},rt=()=>{if(X.current=null,!l)return;const K=ne.current;if(!K)return;const Y=K.slice(0,we);ne.current=K.slice(Y.length);const se=r.current;if(!se){ne.current=Y+ne.current,pe();return}se.write(Y,()=>{if(ne.current.length>0){pe();return}Je()})},pt=K=>{K&&(ne.current+=K,pe())},xt=(K,Y=0,se,oe,ke={})=>{var Ee,Ae,$e,Fe;const Pe=!!ke.force;!Pe&&Y>0&&ye.current>=Y||!Pe&&Y===0&&he.current||(ye.current=Y,Y>0&&C(!0),u(!0),S(""),typeof se=="number"&&typeof oe=="number"&&se>0&&oe>0&&((Ae=(Ee=r.current)==null?void 0:Ee.resize)==null||Ae.call(Ee,se,oe)),ne.current="",(Fe=($e=r.current)==null?void 0:$e.reset)==null||Fe.call($e),K?pt(K):Je())};i.useEffect(()=>{ze()},[B]),i.useEffect(()=>{var Y;if(!B)return;const K=((Y=mt.onRuntimeEvent)==null?void 0:Y.call(mt,B,se=>{if(!(!se||se.sessionId!==B)){if(se.type==="runtime_snapshot"){if(!l){ue.current={text:se.text||"",seq:se.seq||0,cols:se.cols,rows:se.rows,force:!!se.force};return}xt(se.text||"",se.seq||0,se.cols,se.rows,{force:!!se.force});return}if(se.type==="session_output"){he.current=!0,typeof se.seq=="number"&&(ye.current=Math.max(ye.current,se.seq),se.seq>0&&C(!0)),h.current||u(!0),h.current||S(""),typeof se.data=="string"&&pt(se.data);return}if(se.type==="session_cleared"){if(!l){Se.current=!0,ne.current="",ue.current=null;return}Xe();return}if(se.type==="session_io_error"){const oe=typeof se.error=="string"&&se.error?se.error:typeof se.reason=="string"&&se.reason?se.reason:"unknown error";u(!1),S(`Runtime input failed: ${oe}`);return}}},z))||(()=>{});return()=>{K()}},[z,B,r,l]);const vt=async(K={})=>{var Y;if(!z||!B)return{success:!1,error:"daemonId and sessionId are required"};K.preserveStatus||S(K.loadingMessage||"Loading runtime terminal...");try{const se=await((Y=mt.requestRuntimeSnapshot)==null?void 0:Y.call(mt,z,B,{sinceSeq:K.sinceSeq,force:K.force}));return se&&se.success===!1?(K.preserveStatus||(u(!1),S(`Runtime terminal unavailable: ${se.error}`)),se):se||{success:!0}}catch(se){const oe=(se==null?void 0:se.message)||String(se);return K.preserveStatus||(u(!1),S(`Runtime terminal unavailable: ${oe}`)),{success:!1,error:oe}}},Te=async K=>{var Pe,Ee;const Y=((Pe=F.current)==null?void 0:Pe.ownerDocument)||document,se=Y.defaultView||window,oe=(Ee=se.navigator)==null?void 0:Ee.clipboard;if(oe!=null&&oe.writeText&&se.isSecureContext)try{return await oe.writeText(K),!0}catch{}let ke=null;try{return ke=Y.createElement("textarea"),ke.value=K,ke.setAttribute("readonly","true"),ke.style.position="fixed",ke.style.left="-9999px",ke.style.top="0",Y.body.appendChild(ke),ke.focus(),ke.select(),Y.execCommand("copy")}catch{return!1}finally{ke==null||ke.remove()}},Ve=K=>{me(),y(K);const Y=be();xe.current={ownerWindow:Y,timeoutId:Y.setTimeout(()=>{xe.current=null,y(se=>se===K?null:se)},2200)}},tt=K=>{ie(),v(K);const Y=be();fe.current={ownerWindow:Y,timeoutId:Y.setTimeout(()=>{fe.current=null,v(se=>se===K?null:se)},2200)}},Ge=async()=>{var ke,Pe,Ee,Ae;const K=((Pe=(ke=r.current)==null?void 0:ke.getSelection)==null?void 0:Pe.call(ke))||"",Y=((Ae=(Ee=r.current)==null?void 0:Ee.getVisibleText)==null?void 0:Ae.call(Ee))||"",se=K.trimEnd()||Y.trimEnd();if(!se){Ve("Nothing to copy");return}if(!await Te(se)){Ve("Copy failed");return}Ve(K.trimEnd()?"Copied selection":"Copied visible terminal")},ot=K=>{if(!m||!l)return;((d==null?void 0:d(z,B,K))??!1)||Ve("Terminal input failed")},U=async()=>{if(b)return;p(!0),v("Loading older terminal output..."),ve.current=!0;const K=await vt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(p(!1),(K==null?void 0:K.success)===!1){ve.current=!1,v(`Older terminal output unavailable: ${K.error}`);return}k(!0),tt("Older terminal output loaded"),Ce(()=>{var Y;(Y=r.current)==null||Y.bumpResize()})};i.useEffect(()=>{var Y,se;if(!B)return;z&&((Y=mt.getState)==null?void 0:Y.call(mt,z))==="connected"&&vt();const K=(se=mt.onStateChange)==null?void 0:se.call(mt,(oe,ke)=>{oe!==z||ke!=="connected"||vt()});return()=>{K==null||K()}},[z,B,r]),i.useEffect(()=>{t&&ze()},[t,le,r]),i.useEffect(()=>{var oe,ke;const K=F.current,Y=(ke=(oe=K==null?void 0:K.ownerDocument)==null?void 0:oe.defaultView)==null?void 0:ke.ResizeObserver;if(!K||!Y)return;const se=new Y(Pe=>{const Ee=Pe[0];if(!Ee)return;const{width:Ae,height:$e}=Ee.contentRect;M(Fe=>{const Me=Math.round(Ae),Qe=Math.round($e);return Fe.width===Me&&Fe.height===Qe?Fe:{width:Me,height:Qe}})});return se.observe(K),()=>se.disconnect()},[]),i.useEffect(()=>{if(E.current)return;const K=Ne();!Number.isFinite(K)||K<=0||_(Y=>G.current?K<Y-ce?K:Y:(G.current=!0,K))},[j.height,j.width,D.height,D.width]),i.useEffect(()=>{O&&He()},[O,Le,Ie]),i.useEffect(()=>{var se;const K=J.current;if(J.current=l,!l)return;K||k(!1),Se.current&&(Se.current=!1,Xe());const Y=ue.current;Y&&(ue.current=null,xt(Y.text,Y.seq,Y.cols,Y.rows,{force:!!Y.force})),z&&B&&((se=mt.getState)==null?void 0:se.call(mt,z))==="connected"&&vt(),ne.current&&X.current===null&&pe(),Ce(()=>{var oe;(oe=r.current)==null||oe.bumpResize()})},[z,l,B]),i.useEffect(()=>()=>{X.current!==null&&ee(),me(),ie()},[]),i.useEffect(()=>{const K=oe=>{var Pe;const ke=oe.detail;ke!=null&&ke.sessionId&&ke.sessionId!==B||m&&((Pe=r.current)==null||Pe.bumpResize())},Y=be(),se=Y===window?[window]:[window,Y];for(const oe of se)oe.addEventListener("adhdev:fit-cli-terminal",K);return()=>{for(const oe of se)oe.removeEventListener("adhdev:fit-cli-terminal",K)}},[m,B,r]);const Z=m&&f&&!T&&(H.atTop||!H.canScroll)||b||!!g;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:F,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[Z&&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:()=>{U()},disabled:!B||b,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:b?"Loading older...":"Load older terminal output"}),g&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:g})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[I&&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:I}),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:()=>{Ge()},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:()=>w(K=>!K),disabled:!m,"aria-label":"Open terminal control keys","aria-expanded":N,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),N&&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:()=>w(!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:()=>ot("\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:()=>ot(" "),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:()=>ot("\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:()=>ot("\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:()=>ot("\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:()=>ot("\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:()=>ot("\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:()=>ot(""),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:()=>ot(""),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:()=>ot(""),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:()=>{E.current=!0,_(K=>{const Y=Math.max(je,Number((K-.1).toFixed(2)));return Y>je&&He(),Y})},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:()=>{E.current=!0,_(K=>{const Y=Math.min(q,Number((K+.1).toFixed(2)));return Y>je&&He(),Y})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:P,className:O?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:s.jsx("div",{style:{width:Ie>0?`${Ie}px`:"100%",height:Le>0?`${Le}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:j.width>0?`${j.width}px`:"100%",height:j.height>0?`${j.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:A},children:s.jsx(Ac,{ref:r,readOnly:!m||!l,sizingMode:"measured",onViewportMetrics:W,onScrollMetrics:$,onInput:K=>{!m||(d==null||d(z,B,K))}})})})}),!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:x})]}),s.jsx(Wc,{contextKey:e.tabKey,panelLabel:ut(e),isSending:a,isBusy:!!de,statusMessage:re,onSend:async K=>de?!1:n(K),isActive:c&&l,showControlsToggle:!1,animateVisibility:!1})]})}const bx=5e3,gx=12e3;function yx(e){return e==="disconnected"||e==="reconnecting"}function vx({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=bx,reconnectActionDelayMs:o=gx}){const l=yx(e),[c,d]=i.useState(()=>!l||a<=0),[m,u]=i.useState(()=>!l||o<=0),h=i.useRef(!1);i.useEffect(()=>{if(!l){d(!1);return}if(h.current=!1,a<=0){h.current=!0,d(!0);return}d(!1);const k=setTimeout(()=>{h.current=!0,d(!0)},a);return()=>clearTimeout(k)},[a,l]),i.useEffect(()=>{if(!l){u(!1);return}if(o<=0){u(!0);return}u(!1);const k=setTimeout(()=>{u(!0)},o);return()=>clearTimeout(k)},[o,l]);const x=l?c:e==="offline"||e==="auth_failed",S=!!(n&&e!=="auth_failed"&&(!l||m)),b=i.useMemo(()=>!t||e!=="connected"?!1:a<=0||h.current,[a,t,e]),p=e==="auth_failed"?"red":e==="offline"?"orange":"accent",g={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))"},v={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)"},f={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},C="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",T={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[x&&s.jsx("div",{className:C,style:T,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:g[p],border:v[p],color:f[p]},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.")]}),S&&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"})]})}),b&&s.jsx("div",{className:C,style:T,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 wx({terminalBackend:e,isStandalone:t=!1,machineLabel:r,machineKey:n}){const a=i.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[o,l]=i.useState(!1);if(i.useEffect(()=>{if(!a){l(!1);return}try{l(localStorage.getItem(a)==="1")}catch{l(!1)}},[a]),!t||!e||e.backend!=="xterm"||o)return null;const c=(r==null?void 0:r.trim())||"This machine",d=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}l(!0)};return s.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5",style:{background:"linear-gradient(90deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04))",borderBottom:"1px solid rgba(245,158,11,0.2)",color:"#d97706"},children:[s.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[s.jsxs("span",{children:[c," is using `xterm` fallback."]}),s.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),s.jsx("button",{type:"button",onClick:d,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function Yo({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(Ro,{size:n}):s.jsx(es,{size:n})})}const zt="New session",md="A connected machine is ready. Start a new session to begin chatting, or open a workspace to launch an IDE, CLI, or ACP session.";function jx(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 kx(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 Sx(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 qs({git:e,className:t="",compact:r=!1}){const n=jx(e),a=kx(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 ${Sx(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 Nx({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,l=a.filter(c=>c==="connecting"||c==="new"||c==="checking").length;return r>0&&l>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 el({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function tl({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const l=Un(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",l].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[c?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),n()},children:"Mark read"}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),a()},children:"Mark unread"}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),o()},children:"Delete"})]})]})}function Cx({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:l,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:m,hiddenConversations:u=[],onShowConversation:h,onShowAllHidden:x,onResetPanelsToMain:S,inboxOpen:b,onInboxOpenChange:p,hiddenOpen:g,onHiddenOpenChange:v,onOpenNewSession:f,onOpenDashboardGuide:C,guideNudgeVisible:T=!1,actionShortcuts:k,notifications:A,notificationUnreadCount:_,onOpenNotification:N,onMarkNotificationRead:w,onMarkNotificationUnread:D,onDeleteNotification:M,onOpenGitDialog:j,onOpenMeshGraph:W}){var Ce;const{ides:H,p2pStates:$={}}=cs(),I=!!e&&at(e)&&!st(e),y=!!e&&st(e),F=!!(e!=null&&e.daemonId)&&typeof((Ce=e==null?void 0:e.settings)==null?void 0:Ce.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.length>0,P=c||(e?Kc(e)?"terminal":"chat":null),[E,G]=i.useState(!1),J=i.useRef(null),ye=i.useRef(null),he=H.filter(ee=>ee.type==="adhdev-daemon"),ne=Nx({wsStatus:t,isConnected:r,daemonCount:he.length,p2pStates:$}),ue=ne.subtitle,Se=ne.tone==="connected"?"#22c55e":ne.tone==="limited"?"#eab308":"#ef4444",ve=ne.tone==="connected"?"0 0 4px #22c55e80":ne.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",X=i.useMemo(()=>A.filter(ee=>!ee.readAt),[A]),xe=i.useMemo(()=>A.filter(ee=>!!ee.readAt),[A]),fe=i.useMemo(()=>X.slice(0,9),[X]),we=_;i.useEffect(()=>{if(!b)return;const ee=me=>{var ie;(ie=J.current)!=null&&ie.contains(me.target)||p(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[b,p]),i.useEffect(()=>{if(!g)return;const ee=me=>{var ie;(ie=ye.current)!=null&&ie.contains(me.target)||v(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[g,v]),i.useEffect(()=>{if(!g&&!b)return;const ee=me=>{if(!me.altKey)return;const ie=me.code.match(/^Digit([1-9])$/);if(!ie)return;const pe=Number(ie[1])-1,le=g?u[pe]:void 0,B=b?fe[pe]:void 0;if(!(!le&&!B)){if(me.preventDefault(),me.stopPropagation(),le){h==null||h(le),v(!1);return}B&&(N(B),p(!1))}};return window.addEventListener("keydown",ee,!0),()=>window.removeEventListener("keydown",ee,!0)},[u,g,b,fe,v,p,N,h]);const be=ee=>{if(!ee)return;const me=n.find(ie=>ie.tabKey===ee);me&&(m==null||m(me))};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(es,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?ut(e):"Dashboard"}),s.jsx("span",{title:ne.title,"aria-label":ne.title,className:"header-title-status-dot",style:{background:Se,boxShadow:ve}}),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:Se,boxShadow:ve}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[ue&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",ue]}),f&&s.jsx("button",{type:"button",onClick:f,className:"btn btn-secondary btn-sm ml-2",title:`${zt}${k!=null&&k.openNewSession?` (${k.openNewSession})`:""}`,"aria-label":zt,children:s.jsx(kc,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[C&&s.jsxs("button",{type:"button",onClick:C,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:"?"}),T&&s.jsx("span",{children:"Guide"})]}),e&&(I||y||!st(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:Is(e)||ut(e),children:ut(e)}),j&&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:()=>j(e.daemonId,e.workspacePath),children:s.jsx(qs,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(qs,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),F&&W&&s.jsxs("button",{type:"button",onClick:()=>W(e),className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",title:"Open live repo mesh graph",children:[s.jsx(as,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:"Mesh graph"})]}),(I||y)&&l&&s.jsxs(s.Fragment,{children:[I&&d&&P&&s.jsx(Yo,{mode:P,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>l(e),className:"btn btn-secondary btn-sm",title:y?"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(wt,{size:14})})]}),!st(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(_o,{size:14})}),!I&&!st(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(_t,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:J,children:[s.jsxs("div",{className:`dashboard-header-hidden${E?" is-drop-target":""}`,ref:ye,onDragEnter:ee=>{ee.dataTransfer.types.includes("text/tab-key")&&(ee.preventDefault(),G(!0))},onDragOver:ee=>{ee.dataTransfer.types.includes("text/tab-key")&&(ee.preventDefault(),ee.dataTransfer.dropEffect="move",G(!0))},onDragLeave:ee=>{ee.currentTarget.contains(ee.relatedTarget)||G(!1)},onDrop:ee=>{const me=ee.dataTransfer.getData("text/tab-key");ee.preventDefault(),G(!1),be(me)},children:[s.jsxs("button",{type:"button",onClick:()=>v(!g),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(Lo,{size:16}),u.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:u.length})]}),g&&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(el,{value:k==null?void 0:k.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[S&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:S,children:"Reset panels"}),u.length>0&&x&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{x(),v(!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(el,{value:k==null?void 0:k.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:ut(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(ee=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(ee),v(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:ut(ee)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(ee)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(ee)+1]}):null,Is(ee)]})]},ee.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!b),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(Hn,{size:16}),we>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:we})]}),b&&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(ee=>s.jsx(tl,{notification:ee,shortcutIndex:fe.indexOf(ee)>=0?fe.indexOf(ee)+1:void 0,onOpen:()=>N(ee),onMarkRead:()=>w(ee.id),onMarkUnread:()=>D(ee.id),onDelete:()=>M(ee.id)},ee.id))]}),xe.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),xe.map(ee=>s.jsx(tl,{notification:ee,onOpen:()=>N(ee),onMarkRead:()=>w(ee.id),onMarkUnread:()=>D(ee.id),onDelete:()=>M(ee.id)},ee.id))]}),A.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 Ix(e,t){return String(e||"")!==String(t||"")}function Tx(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(l=>!(o&&!l.canResume||r&&![l.title,l.preview].map(d=>String(d||"").toLowerCase()).join(`
|
|
41
|
+
`).includes(r)||n&&!String(l.workspace||"").toLowerCase().includes(n)||a&&!Dc(l.summaryMetadata).map(d=>d.toLowerCase()).join(`
|
|
42
|
+
`).includes(a)))}function Mx(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 pd(e,t={}){return Mx(Tx(e,t),t.sortMode||"recent")}function Pn(e){return e?"Resume saved history":"Start fresh"}function Xo(e){return e?"Resuming saved history…":"Starting fresh…"}function Ax(){return"Start fresh"}function hd(e,t=!1){return e==="cli"?Pn(t):e==="ide"?"Start IDE":"Start ACP session"}function fd(e,t=!1){return e==="cli"?Xo(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function _x(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Lx(){return"Open saved history"}function Rx(){return"Saved History"}function Jo(){return"Use saved history when you want continuity in the same provider conversation."}function Px(){return"No saved history found yet."}function Dx(){return"Refresh saved history"}function Ex(){return"Refreshing saved history…"}function gs(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function ys(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 Ys(e){return e==="start-fresh"?"Start fresh":"Restart"}function Xs(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Qo(e){return`Resume saved history with ${e}?`}function Zo(){return"Review or change the target workspace before resuming saved history."}function $x(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 ei({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:l=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:m,onClose:u,onNewChat:h,onSwitchSession:x,onRefreshHistory:S,onResumeSavedSession:b}){var M;const p=t.find(j=>j.id===e.routeId),g=(p==null?void 0:p.chats)||[],v=(M=p==null?void 0:p.activeChat)==null?void 0:M.id,f=at(e)&&!st(e),[C,T]=i.useState(()=>Ct()),k=c||C,A=String(d||"").trim(),_=j=>{if(m){m(j);return}T(j)},N=i.useMemo(()=>a.map(j=>{const W=String(j.workspace||"").trim();return j.canResume||W||!A?j:{...j,workspace:A,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[A,a]),w=i.useMemo(()=>pd(N,{textQuery:k.textQuery,workspaceQuery:k.workspaceQuery,modelQuery:k.modelQuery,resumableOnly:k.resumableOnly,sortMode:k.sortMode}),[N,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:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:f?Rx():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:hx(e)}),f&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Jo()})]}),s.jsx("button",{onClick:u,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(wt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!f&&s.jsx("button",{onClick:h,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"}),f?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:j=>_({...k,textQuery:j.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:j=>_({...k,workspaceQuery:j.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:j=>_({...k,modelQuery:j.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:j=>_({...k,sortMode:j.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:j=>_({...k,resumableOnly:j.target.checked})}),"Resume-ready only"]})]}),w.map(j=>{const W=e.providerSessionId===j.providerSessionId,H=W||!j.canResume||!!l,$=j.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{H||!b||b(j)},disabled:H,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${W?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${H?"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 ${W?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:j.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:j.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:$x(j.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:j.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:[j.workspace||"Workspace unknown",$?" · selected workspace":"",Cs(j.summaryMetadata)?` · ${Cs(j.summaryMetadata)}`:"",j.messageCount>0?` · ${j.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:W?"ACTIVE":j.canResume?$?"RESUME IN SELECTED WORKSPACE":l===j.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},j.id)})]}):g.map(j=>s.jsxs("div",{onClick:()=>{x(e.routeId,j.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${v===j.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 ${v===j.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:j.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:[j.id.substring(0,12),"..."]}),v===j.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},j.id)),(f&&!o&&w.length===0||!f&&g.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(ip,{size:32})}),s.jsx("div",{className:"text-[13px]",children:f?a.length>0?"No saved history matches these filters.":Px():"No recent chat sessions found."})]}),f&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Ex()})})]}),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:S,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(Rr,{size:13})," ",f?Dx():"Refresh History"]})})})]})]});return typeof document>"u"?D:Tr.createPortal(D,document.body)}const sl={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 xd({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=sl[n.type]||sl.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(wt,{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,l)=>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},l))})]})]},n.id)})})}const Bx=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Ox(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function Fx(e){return e.sessionId||e.instanceId||e.agentType}function xa(e,t){return t||e||"unknown"}function bd(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=At(r,{fallbackId:r.id}));return t}function gd(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 ti(e,t={}){return Wx(e,gd(e,t))}function Wx(e,t={}){var h,x,S,b,p;const r=[],n=t.machineName,a=t.connectionState,o=Ox(e),l=e.workspace||"",c=dh(e.type,{agentName:e.cliName}),d=at(e)||st(e)?c:ct(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(g=>{var v,f;return{sessionId:g.id,instanceId:g.id,providerSessionId:g.providerSessionId,transport:g.transport,sessionCapabilities:g.capabilities,agentType:g.providerType,agentName:g.providerName||ct(g.providerType),status:g.status,title:g.title,lastMessagePreview:g.lastMessagePreview,lastMessageRole:g.lastMessageRole,lastMessageAt:g.lastMessageAt,lastMessageHash:g.lastMessageHash,messages:((v=g.activeChat)==null?void 0:v.messages)||[],activeModal:((f=g.activeChat)==null?void 0:f.activeModal)||void 0,unread:g.unread,lastSeenAt:g.lastSeenAt,lastUpdated:g.lastUpdated,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,surfaceHidden:g.surfaceHidden,git:g.git,settings:g.settings,messageInput:g.messageInput}}):[],u=Bx(e);if(u){const g=e.sessionId||e.instanceId,v=(h=e.settings)==null?void 0:h.meshCoordinatorFor,f=(x=e.settings)==null?void 0:x.meshNodeFor,C=v?" (Coordinator)":f?" (Mesh Node)":"",T=c+C,k=(S=e.activeChat)==null?void 0:S.activeModal,A=k&&Array.isArray(k.buttons)&&k.buttons.length>0,_=uh(e.activeChat,[{status:e.status,activeModal:(b=e.activeChat)==null?void 0:b.activeModal}],e.agents||[]),N=e.activeChat||{title:"",messages:[]};let w=N.title&&String(N.title).trim()?String(N.title).trim():"";const D=(p=e.activeChat)==null?void 0:p.id,M=e.chats;if(D&&Array.isArray(M)&&M.length>0){const $=M.find(I=>I.id===D||I.id&&String(I.id)===String(D));$!=null&&$.title&&String($.title).trim()&&(w=String($.title).trim())}const j=(at(e)||st(e),e.type),W=(at(e)||st(e))&&Wi(w,T,j)?"":w,H=N.messages||[];r.push({routeId:e.id,sessionId:g,providerSessionId:e.providerSessionId,nativeSessionId:g,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:at(e)?e.mode||"terminal":"chat",agentName:T,agentType:j,status:_,title:W,messages:H,resume:e.resume,hostIdeType:!at(e)&&!st(e)?e.type:void 0,workspaceName:o,workspacePath:l,git:e.git,displayPrimary:W||o||(at(e)?e.mode==="chat"?T:`Terminal${C}`:T),displaySecondary:at(e)&&o?T:d,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:A?k.buttons:void 0,modalMessage:A?k.message:void 0,streamSource:"native",tabKey:xa(g,e.id),machineName:n,connectionState:a,settings:e.settings,messageInput:e.messageInput})}if(u&&(at(e)||st(e)))return r;for(const g of m){const v=g.activeModal&&Array.isArray(g.activeModal.buttons)&&g.activeModal.buttons.length>0,f=mh(g),C=Fx(g),T=`${e.id}:${C}`,k=g.title&&String(g.title).trim()||"",A=Wi(k,g.agentName,g.agentType)?"":k,_=g.messages||[];(g.transport==="cdp-webview"||g.sessionId||g.providerSessionId||_.length>0||v||A||!["idle","panel_hidden","disconnected","not_monitored"].includes(f))&&r.push({routeId:e.id,sessionId:g.sessionId||g.instanceId,providerSessionId:g.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:g.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:g.sessionCapabilities,mode:"chat",agentName:g.agentName,agentType:g.agentType,status:f,title:A,messages:_,hostIdeType:e.type,workspaceName:o,workspacePath:l,git:g.git||e.git,displayPrimary:A||o||g.agentName||d,displaySecondary:`${d} · ${g.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:g.lastMessagePreview,lastMessageRole:g.lastMessageRole,lastMessageAt:g.lastMessageAt,lastMessageHash:g.lastMessageHash,lastUpdated:g.lastUpdated||e.lastUpdated,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,modalButtons:v?g.activeModal.buttons:void 0,modalMessage:v?g.activeModal.message:void 0,streamSource:"agent-stream",tabKey:xa(g.sessionId||g.instanceId,T),machineName:n,connectionState:a,settings:g.settings,messageInput:g.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:l,git:e.git,displayPrimary:o||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:xa(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),r}function yd(e){return String(e.type||e.id||"").trim()}function Kx(e){var t;return e.category!=="cli"||!yd(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 Hx(e){var n;const t=new Set,r=[];for(const a of e||[]){if(!Kx(a))continue;const o=yd(a);if(!o||t.has(o))continue;t.add(o);const l=String(a.displayName||a.name||o),c=a.detectedPath||((n=a.lastDetection)==null?void 0:n.path)||null;r.push({type:o,label:l,icon:a.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c})}return r}function Yn(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 ho(e,t){const r=new Set(t.map(n=>n.type));return Yn(e).filter(n=>r.has(n))}function Ux(e){return e.map(t=>t.type)}function zx(e,t){const r=Yn(e),n=t.trim();return!n||r.includes(n)?r:[...r,n]}function Vx(e,t){return Yn(e).filter(r=>r!==t)}function rl(e,t,r){const n=Yn(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 l=r==="up"?Math.max(0,a-1):Math.min(o.length,a+1);return o.splice(l,0,t),o}function nl({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 al({value:e,availableProviders:t,onChange:r,disabled:n=!1,saveButton:a}){const[o,l]=i.useState(""),c=i.useMemo(()=>new Map(t.map(x=>[x.type,x])),[t]),d=i.useMemo(()=>ho(e,t),[e,t]),m=e.length-d.length,u=t.filter(x=>!d.includes(x.type)),h=()=>{o&&(r(zx(d,o)),l(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:d.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):d.map((x,S)=>{const b=c.get(x);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:["#",S+1]}),(b==null?void 0:b.icon)&&s.jsx("span",{"aria-hidden":"true",children:b.icon}),s.jsx("span",{className:"font-mono text-[12px] text-text-primary",children:x}),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:b?`${b.label} · ${b.statusLabel}`:x})]}),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||S===0,title:"Move up",onClick:()=>r(rl(d,x,"up")),children:s.jsx(nl,{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||S===d.length-1,title:"Move down",onClick:()=>r(rl(d,x,"down")),children:s.jsx(nl,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>r(Vx(d,x)),children:"Remove"})]})]},x)})}),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:x=>l(x.target.value),disabled:n||u.length===0,children:[s.jsx("option",{value:"",children:u.length?"Select provider…":"No additional detected CLI providers"}),u.map(x=>s.jsxs("option",{value:x.type,children:[x.label," (",x.type,")"]},x.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:n||!o,onClick:h,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 Gx(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 vd(e,t){const r=Gx(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const wd=[{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:"🏄"}],jd=[{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:"🧩"}],kd=[{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:"🟠"}],qx=wd,Yx=jd,Xx=kd;function ts(...e){return mm(pm(e))}function Jx({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:ts("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:l,children:c}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(Jx,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:ts("mx-auto flex w-full flex-col gap-4",o,l),children:c})})]})}const fo="adhdev:themechange";function Qx(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Ds(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Es(e){return e==="system"?Qx():e}function Sd(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function xn(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(fo,{detail:{preference:e,theme:t}}))}function Zx(){const e=Ds(),t=Es(e);Sd(t),xn(e,t)}function er(){const[e,t]=i.useState(Ds),[r,n]=i.useState(()=>Es(Ds()));i.useEffect(()=>{Sd(r)},[r]),i.useEffect(()=>{const l=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const m=d.matches?"light":"dark";n(m),xn("system",m)}};return l.addEventListener("change",c),()=>l.removeEventListener("change",c)},[e]),i.useEffect(()=>{const l=d=>{const m=d.detail||{},u=m.preference,h=m.theme;t(u==="dark"||u==="light"||u==="system"?u:Ds()),n(h==="dark"||h==="light"?h:Es(Ds()))},c=d=>{if(d.key!=="theme")return;const m=Ds(),u=Es(m);t(m),n(u)};return window.addEventListener(fo,l),window.addEventListener("storage",c),()=>{window.removeEventListener(fo,l),window.removeEventListener("storage",c)}},[]);const a=i.useCallback(l=>{const c=Es(l);t(l),n(c);try{localStorage.setItem("theme",l)}catch{}xn(l,c)},[]),o=i.useCallback(()=>{t(l=>{const c=l==="dark"?"light":l==="light"?"system":"dark",d=Es(c);n(d);try{localStorage.setItem("theme",c)}catch{}return xn(c,d),c})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const ol={dark:"Dark",light:"Light",system:"System"};function eb({collapsed:e}){const{preference:t,cycleTheme:r}=er(),n=t==="dark"?s.jsx(cp,{size:16}):t==="light"?s.jsx(lp,{size:16}):s.jsx(dp,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${ol[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:ol[t]})]})}function ba(e,t){return e?typeof e=="function"?e(t):e:null}function tb({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:l,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const[m,u]=i.useState(!1),[h,x]=i.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),S=()=>u(!0),b=()=>u(!1),p=()=>{x(C=>{const T=!C;try{localStorage.setItem(d,T?"1":"0")}catch{}return T})},g=i.useMemo(()=>({collapsed:h,mobileMenuOpen:m,openMobileMenu:S,closeMobileMenu:b,toggleCollapsed:p}),[h,m]),v=C=>`nav-item${C.active?" active":""} cursor-pointer ${h?"justify-center py-2.5 px-0":""}${C.className?` ${C.className}`:""}`,f=C=>s.jsxs("div",{className:v(C),id:`nav-${C.id}`,onClick:()=>{C.onSelect(),b()},title:h?C.title??(typeof C.label=="string"?C.label:void 0):C.title,children:[s.jsx("span",{className:"nav-icon",children:C.icon}),!h&&C.label]},C.id);return s.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${h?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:S,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:b,onKeyDown:C=>C.key==="Escape"&&b()}),s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${h?"justify-center gap-0":""}`,children:ba(t,g)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:b,children:s.jsx(wt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(f)}),n.map(C=>s.jsxs("div",{className:C.className??"border-t border-border-subtle pt-2 mt-2",children:[!h&&C.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:C.title}):null,C.items.map(f)]},C.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(f),ba(o,g),s.jsx(eb,{collapsed:h}),ba(l,g)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function St({title:e,icon:t,description:r,accentColor:n,className:a,children:o}){return s.jsxs("div",{className:ts("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 Dn({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:ts("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 sb={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"},rb={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Os({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:ts("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",sb[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:rb[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 Lt({label:e,hint:t,children:r,className:n}){return s.jsxs("div",{className:ts("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 ga(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:ts("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 nb={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"},ab={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function ob({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:ts("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",nb[e],r),children:[s.jsx("span",{className:ts("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",ab[e])}),n]})}function hs({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 ib({onPrefChange:e}){const[t,r]=jh(),[n,a]=i.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);i.useEffect(()=>{const l=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return l(),window.addEventListener("focus",l),document.addEventListener("visibilitychange",l),()=>{window.removeEventListener("focus",l),document.removeEventListener("visibilitychange",l)}},[]);const o=(l,c)=>{r({[l]:c}),e==null||e(l,c)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(hs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Hn,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:l=>o("globalEnabled",l)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(hs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_t,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:l=>o("browserNotifications",l)}),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:()=>{Bc().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(hs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(up,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:l=>o("completionAlert",l)}),s.jsx(hs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(mp,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:l=>o("approvalAlert",l)}),s.jsx(hs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(zs,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:l=>o("disconnectAlert",l)})]}),!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 En(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function lb(e,t){const r=En(e),n=En(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 Nd(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function Sr(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||lb(r,t)>=0)return!1;const n=En(r),a=En(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function cb(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function ya(e,t){return e instanceof Error?e.message:t}function db({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const o=e.filter(l=>l.type==="adhdev-daemon");return o.length===0?s.jsx(Dn,{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(l=>s.jsx(mb,{ide:l,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},l.id))})}function il({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:o}){const l=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return Tr.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 ${l}`,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 ub(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...qx,...Yx,...Xx].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 mb({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var H,$;const[o,l]=i.useState("idle"),[c,d]=i.useState(""),[m,u]=i.useState(null),[h,x]=i.useState("idle"),[S,b]=i.useState(""),p=e.version||null,g=((H=e.machine)==null?void 0:H.platform)||(($=e.system)==null?void 0:$.platform)||"",v=At(e,{fallbackId:e.id}),f=g==="win32"?"🪟":g==="darwin"?"🍎":"🐧",C=t.filter(I=>I.daemonId===e.id&&I.transport==="cdp-page"),T=t.filter(I=>I.daemonId===e.id&&I.transport==="pty"),k=t.filter(I=>I.daemonId===e.id&&I.transport==="acp"),A=e.p2p,_=async()=>{if(r){l("upgrading"),d("Starting upgrade...");try{const I=cb(await r(e.id,"daemon_upgrade",{}));I.alreadyLatest?(l("done"),d(`Already on v${I.version||"latest"}.`)):I.upgraded||I.success?(l("done"),d(`Upgrade to v${I.version||"latest"} started. Daemon is restarting...`)):(l("error"),d(I.error||"Upgrade failed"))}catch(I){l("error"),d(ya(I,"Connection lost during upgrade"))}}},N=async()=>{if(u(null),!!n){x("loading");try{await n(e.id),x("done"),b("Machine disconnected.")}catch(I){x("error"),b(ya(I,"Failed to disconnect"))}}},w=async()=>{if(u(null),!!a){x("loading");try{await a(e.id),x("done"),b("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(I){x("error"),b(ya(I,"Failed to revoke token"))}}},D="0.9.81",M=Nd(e,D),j=Sr(e,D),W=C.length+T.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:f}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:v}),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),"…"]}),p&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${M?"":"bg-bg-secondary"}`,style:M?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",p,!M&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&M&&s.jsx("button",{onClick:_,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":`${j?"↑ Update now":`↑ Update${` to v${D}`}`}`}),n&&s.jsx("button",{onClick:()=>u("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>u("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(ob,{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:[A&&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 ${A.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${A.state==="connecting"||A.state==="new"?"animate-pulse":""}`,style:A.state==="connecting"||A.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",A.state==="connected"?"connected":A.state==="connecting"||A.state==="new"?"connecting...":A.state||"off"]}),A.peers!==void 0&&A.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",A.peers," peer",A.peers!==1?"s":"",")"]})]}),A&&W>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),W>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[C.map(I=>{const y=ub(I.type),F=I.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:y.icon}),s.jsx("span",{children:y.name}),F!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${F?"bg-green-400":"animate-pulse"}`,style:F?void 0:{background:"var(--status-warning)"},title:F?"CDP connected":"CDP connecting..."})]},I.id)}),T.map(I=>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:I.cliName||"CLI"})]},I.id)),k.map(I=>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:I.cliName||"ACP"})]},I.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(c||S)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||h==="error"?"text-red-400":o==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:S||c})]}),m==="disconnect"&&s.jsx(il,{title:"🔌 Disconnect Machine",message:`Disconnect "${v}" from ADHDev?
|
|
43
43
|
|
|
44
44
|
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
45
45
|
|
|
@@ -50,8 +50,8 @@ This will:
|
|
|
50
50
|
• Delete the machine registration
|
|
51
51
|
• Require restarting ADHDev on that machine
|
|
52
52
|
|
|
53
|
-
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:w,onCancel:()=>u(null)})]})}const mb=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function pb(){const{preference:e,setPreference:t}=er();return s.jsx("div",{className:"flex gap-2",children:mb.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 hb(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 fb(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function va(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function ll(e){const{r:t,g:r,b:n}=fb(e);return .2126*va(t)+.7152*va(r)+.0722*va(n)}function cl(e,t){const r=ll(e),n=ll(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function Nd(e){const t=hb(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return cl(t,r)>=cl(t,n)?r:n}const xo={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},bo={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},xb=[{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"}}}],Cd="adhdev-chat-theme",Id="adhdev-chat-theme-custom";function bn(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Cd)||"ember"}catch{return"ember"}}function Ft(e){try{const t=localStorage.getItem(Id);if(t){const r=JSON.parse(t);return{...e==="dark"?xo:bo,...r[e]}}}catch{}return e==="dark"?xo:bo}function Zr(e,t){try{localStorage.setItem(Id,JSON.stringify({dark:e,light:t}))}catch{}}function Rt(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 $n(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 bb={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=bb[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",$n(r,24)),n.style.setProperty("--accent-on-primary",Nd(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${$n(r,18)})`),n.style.setProperty("--border-accent",Rt(r,.35)),n.style.setProperty("--nav-active-bg",Rt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Rt(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",Rt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Rt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Rt(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",Rt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Rt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",$n(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Nd(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${$n(e.accentColor,40)})`),t.style.setProperty("--border-accent",Rt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Rt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Rt(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 ${Rt(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 si(){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 gb(e){try{localStorage.setItem(Cd,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ws()?"dark":"light";vs(Ft(t))}else si(),Nr(e,ws()?"dark":"light")}function yb(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=bn();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ws()?"dark":"light";vs(Ft(t))}else si(),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 It({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 ur({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 vb({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=i.useState(()=>Ft(r));i.useEffect(()=>{a(Ft(r))},[r]);const o=i.useCallback((l,c)=>{a(d=>{const m={...d,[l]:c},h=Ft(r==="dark"?"light":"dark");return r==="dark"?Zr(m,h):Zr(h,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(ur,{title:"App Background",children:[s.jsx(It,{label:"Background",value:n.bgPrimary,onChange:l=>o("bgPrimary",l)}),s.jsx(It,{label:"Surface",value:n.bgSecondary,onChange:l=>o("bgSecondary",l)}),s.jsx(It,{label:"Card",value:n.surfacePrimary,onChange:l=>o("surfacePrimary",l)})]}),s.jsxs(ur,{title:"App Text",children:[s.jsx(It,{label:"Primary",value:n.textPrimary,onChange:l=>o("textPrimary",l)}),s.jsx(It,{label:"Secondary",value:n.textSecondary,onChange:l=>o("textSecondary",l)}),s.jsx(It,{label:"Muted",value:n.textMuted,onChange:l=>o("textMuted",l)})]}),s.jsxs(ur,{title:"Borders & Accent",children:[s.jsx(It,{label:"Border subtle",value:n.borderSubtle,onChange:l=>o("borderSubtle",l)}),s.jsx(It,{label:"Border default",value:n.borderDefault,onChange:l=>o("borderDefault",l)}),s.jsx(It,{label:"Accent",value:n.accentColor,onChange:l=>o("accentColor",l)})]})]}),s.jsxs("div",{children:[s.jsxs(ur,{title:"Chat Bubbles",children:[s.jsx(It,{label:"User bubble",value:n.userBubble,onChange:l=>o("userBubble",l)}),s.jsx(It,{label:"User text",value:n.userText,onChange:l=>o("userText",l)}),s.jsx(It,{label:"Agent bubble",value:n.assistantBubble,onChange:l=>o("assistantBubble",l)}),s.jsx(It,{label:"Agent text",value:n.assistantText,onChange:l=>o("assistantText",l)})]}),s.jsxs(ur,{title:"Chat Layout",children:[s.jsx(It,{label:"Chat BG",value:n.containerBg,onChange:l=>o("containerBg",l)}),s.jsx(It,{label:"Send button",value:n.sendButton,onChange:l=>o("sendButton",l)}),s.jsx(It,{label:"Input border",value:n.inputBorder,onChange:l=>o("inputBorder",l)}),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:l=>o("bubbleRadius",Number(l.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 l=e?xo:bo,d=Ft(e?"light":"dark");e?Zr(l,d):Zr(d,l),a(l),vs(l),t(l)},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 wb(){const[e,t]=i.useState(bn),[r,n]=i.useState(!0),[a,o]=i.useState(()=>Ft("dark"));i.useEffect(()=>{n(ws());const d=new MutationObserver(()=>{const h=ws();n(h);const x=bn();x==="custom"?vs(Ft(h?"dark":"light")):Nr(x,h?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const h=ws();n(h);const x=bn();x==="custom"?vs(Ft(h?"dark":"light")):Nr(x,h?"dark":"light")};return m.addEventListener("change",u),()=>{d.disconnect(),m.removeEventListener("change",u)}},[]),i.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?vs(Ft(r?"dark":"light")):(si(),Nr(e,r?"dark":"light"))},[e,r]),i.useEffect(()=>{o(Ft(r?"dark":"light"))},[r]);const l=d=>{t(d),gb(d)},c=[...xb,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:c.map(d=>{const m=e===d.id,u=r?d.preview.dark:d.preview.light,h=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>l(d.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:u.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"Hello! How can I help?"}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.userBubble,color:h},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[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:d.id==="custom"?"🎨 Custom":d.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:d.description})]})]})]},d.id)})}),e==="custom"&&s.jsx(vb,{dark:r,onColorsChange:d=>o(d)})]})}const ri="adhdev_mobileDashboardMode_v1",go="adhdev:mobile-dashboard-mode-change";function ni(){try{return localStorage.getItem(ri)==="workspace"?"workspace":"chat"}catch{return"chat"}}function jb(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??ni())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==ri||t()};return window.addEventListener(go,r),window.addEventListener("storage",n),()=>{window.removeEventListener(go,r),window.removeEventListener("storage",n)}}function kb(e){try{localStorage.setItem(ri,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(go,{detail:e}))}function Sb(){const[e,t]=i.useState(!0);return i.useEffect(()=>{t(ni()==="chat")},[]),s.jsx(hs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(es,{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),kb(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const wa=new Map,dl=new Map;function Nb(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 Cb(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 Td(){const{sendCommand:e}=jt(),{injectEntries:t,getIdes:r}=Mr();return i.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??jf,l=dl.get(n)||0;if(!(a!=null&&a.force)&&l>0&&Date.now()-l<o)return;const c=wa.get(n);if(c)return c;const d=(async()=>{const m=await e(n,"get_machine_runtime_stats"),u=Nb(m);if(!u)return;const h=r().find(S=>S.id===n),x=Cb(h,n,u.machine,u.timestamp||Date.now());t([x]),dl.set(n,Date.now())})().finally(()=>{wa.delete(n)});return wa.set(n,d),d},[r,t,e])}function Ib(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 Tb(e,t){const{sendData:r}=jt(),{injectEntries:n,getIdes:a}=Mr(),o=Array.from(new Set(e.filter(Boolean))).join("|");i.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const l=o?o.split("|"):[];if(l.length===0)return;const c=l.map(d=>Qt.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const h=a().find(S=>S.id===d),x=Ib(h,d,u);n([x])}));return()=>{c.forEach(d=>d())}},[o,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function Mb(e,t){const{sendData:r}=jt(),[n,a]=i.useState(null),[o,l]=i.useState(!1);return i.useEffect(()=>{if(!e){a(null),l(!1);return}if(!(t!=null&&t.enabled)||!r){l(!1);return}a(null),l(!0);let c=null;const d=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),l(!1)});return d.initialSendAccepted?c=setTimeout(()=>{l(!1)},Cf):l(!1),()=>{c&&clearTimeout(c),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,r]),{diagnostics:n,loading:o,applyDiagnostics:a}}function Ab(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Md(e){const{sendData:t}=jt(),[r,n]=i.useState({});return i.useEffect(()=>{const a=Ab(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}},l=>{n({status:l.status,modalMessage:l.modalMessage,modalButtons:l.modalButtons}),Hs.record({interactionId:l.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:l.status,modalButtonCount:Array.isArray(l.modalButtons)?l.modalButtons.length:0}})});return o.initialSendAccepted||n({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const Ad="adhdev_hiddenTabs",_d="adhdev_autoHiddenMeshTabs";function _b(){try{const e=localStorage.getItem(Ad);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function us(e){try{localStorage.setItem(Ad,JSON.stringify([...e]))}catch{}}function Lb(){try{const e=localStorage.getItem(_d);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ul(e){try{localStorage.setItem(_d,JSON.stringify([...e]))}catch{}}function yr(e){return Go(e)}function Xn(e,t){return Ks(t).some(r=>e.has(r))}function Rb(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 Pb(e,t,r=new Set){return e.filter(n=>{if(!Rb(n))return!1;const a=yr(n);return r.has(a)?!1:!Xn(t,n)})}function Db(){const[e,t]=i.useState(_b),[r,n]=i.useState(Lb),a=i.useCallback(x=>{const S=yr(x);t(b=>{const p=new Set(b);return p.has(S)?p.delete(S):p.add(S),us(p),p})},[]),o=i.useCallback(x=>{const S=yr(x);t(b=>{if(b.has(S))return b;const p=new Set(b);return p.add(S),us(p),p})},[]),l=i.useCallback(x=>{const S=yr(x);t(b=>{if(b.has(S))return b;const p=new Set(b);return p.add(S),us(p),p}),n(b=>{if(b.has(S))return b;const p=new Set(b);return p.add(S),ul(p),p})},[]),c=i.useCallback(x=>{const S=yr(x);t(b=>{if(!b.has(S))return b;const p=new Set(b);return p.delete(S),us(p),p}),n(b=>{if(b.has(S))return b;const p=new Set(b);return p.add(S),ul(p),p})},[]),d=i.useCallback(()=>{t(x=>{if(x.size===0)return x;const S=new Set;return us(S),S})},[]),m=i.useCallback((x,S)=>{t(b=>{const p=new Set(b);for(const g of S)p.add(g);return us(p),p})},[]),u=i.useCallback((x,S)=>{t(b=>{const p=new Set(b);for(const g of S)p.delete(g);return us(p),p})},[]),h=i.useCallback(x=>Xn(e,x),[e]);return{hiddenTabs:e,autoHiddenTabs:r,toggleTarget:a,hideTarget:o,autoHideTarget:l,showTarget:c,showAllTabs:d,hideAllForDaemon:m,showAllForDaemon:u,isHidden:h}}function Ld(e){return e instanceof Error?e.message:String(e||"")}function Rd(e){const t=Ld(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 Pd(e){const t=Ld(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Dd({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!at(e)||st(e))return;const o=Zs(e);if(o===t)return;const l=e.sessionId;l&&a(c=>({...c,[l]:t}));try{await n(_s(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Gt(e),mode:t})}catch(c){const d=Pd(c);l&&!d&&a(m=>{const u={...m};return o===Ed(r,l)?delete u[l]:u[l]=o,u}),Rd(c)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",c instanceof Error?c.message:String(c)):console.error("Failed to switch CLI view mode:",c)}}function ml(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 Eb(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=ml(a,t),l=Array.isArray(a.childSessions)?a.childSessions.map(d=>ml(d,t)):a.childSessions,c=l!==a.childSessions;return o!==a||c?(r=!0,{...o,...c?{childSessions:l}:{}}):a});return r?n:e}function Ed(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 $b(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))Ed(t,a)===o&&(delete n[a],r=!0);return r?n:e}function Bb({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){i.useEffect(()=>{$c()},[]);const a=i.useMemo(()=>e.map(o=>({id:o.tabKey,name:cd(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return Nh(a),i.useEffect(()=>{if(Object.keys(t).length===0)return;const l=setTimeout(()=>{r(c=>{const d=Date.now(),m={};for(const[u,h]of Object.entries(c))d-h<5e3&&(m[u]=h);return Object.keys(m).length===Object.keys(c).length?c:m})},5500);return()=>clearTimeout(l)},[t,r]),i.useEffect(()=>{const o=setInterval(()=>{const l=Date.now()-3e5;n(c=>{const d=c.filter(m=>m.timestamp>l).slice(-100);return d.length===c.length?c:d})},6e4);return()=>clearInterval(o)},[n]),null}function pl(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=pl(t==null?void 0:t.receivedAt)||pl(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function yo(e,t=0){return js(e)||e.lastUpdated||t||0}function $d(e){return js(e)||e.lastUpdated||0}function Bd(e,t,r=$d){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 l=e.displaySecondary.localeCompare(t.displaySecondary);return l!==0?l:e.tabKey.localeCompare(t.tabKey)}function vo(e){var r;const t=yt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function Ob(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!vo(e)&&!e.title.trim()}function Fb(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(vo(r))-Number(vo(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:Bd(t,r)})[0]||null}function Wt(e,t){const r=e.filter(l=>l.routeId===t);if(r.length===0)return null;const n=r.find(l=>l.streamSource==="native")||null,a=r.filter(l=>l.streamSource==="agent-stream"),o=Fb(a);return n?o&&Ob(n)?o:n:o||r[0]||null}function Wb(e){const t=String(e.daemonId||"").trim(),r=String(e.id||"").trim();return!t||r.startsWith(`${t}:`)?r:`${t}:${r}`}function Kb(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=Wb(n),o=r.get(a);if(!o){r.set(a,n);continue}const l=(o.workspace?1:0)+(o.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>l||(n.timestamp||0)>(o.timestamp||0))&&r.set(a,n)}return Array.from(r.values())}function ja(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function Hb(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 hl(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Hb(Us(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 Ub(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||""),hl(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||""),hl(r.activeChat)].join(":"))].join("|")}function zb(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 Vb(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const o of Ks({routeId:n.routeId}))r.set(o,a);for(const o of Ks({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of Ks({tabKey:n.tabKey}))r.set(o,n)}return r}function Gb(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function qb(e){const t=Gb(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=Us(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Yb({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=i.useMemo(()=>Kb(e),[e]),o=i.useMemo(()=>xd(e),[e]),l=i.useRef([]),c=i.useRef([]),d=i.useRef([]),m=i.useRef(new Map),u=i.useRef(new Map),h=i.useMemo(()=>{const I=new Map,k=[];for(const w of a){const{connectionState:D="new",machineName:M}=bd(w,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),j=Ub(w),W=m.current.get(w.id);if(W&&W.ide===w&&W.sourceSignature===j&&W.connectionState===D&&W.machineName===M){I.set(w.id,W),k.push(...W.conversations);continue}const H=ti(w,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),$={ide:w,sourceSignature:j,connectionState:D,machineName:M,conversations:H};I.set(w.id,$),k.push(...H)}m.current=I;const A=new Map,_=w=>{const D=qb(w),M=u.current.get(w.tabKey);if(M&&M.signature===D)return A.set(w.tabKey,M),M.timestamp;const j={signature:D,timestamp:$d(w)||(M==null?void 0:M.timestamp)||0};return A.set(w.tabKey,j),j.timestamp},N=[...k].sort((w,D)=>Bd(w,D,_));return u.current=A,N},[a,t,o]),x=i.useMemo(()=>{const I=zb(h,r);return ja(l.current,I)?l.current:(l.current=I,I)},[h,r]),S=i.useMemo(()=>{const I=new Map,k=Array.from(new Set(x.map(A=>A.routeId)));for(const A of k){const _=Wt(x,A);_&&I.set(A,_)}return I},[x]),b=i.useMemo(()=>{const I=new Map;for(const k of x){const A=S.get(k.routeId),_=k.streamSource==="native"&&A?A:k;for(const N of Ks({providerSessionId:k.providerSessionId,sessionId:k.sessionId,tabKey:k.tabKey}))I.set(N,_)}return I},[x,S]),p=i.useMemo(()=>Vb(x,S),[x,S]),g=i.useCallback(I=>{if(I)return b.get(I)},[b]),v=i.useCallback(I=>{if(I)return p.get(I)},[p]),f=i.useMemo(()=>{const I=x.filter(k=>!Xn(n,k));return ja(c.current,I)?c.current:(c.current=I,I)},[x,n]),T=i.useMemo(()=>{const I=f.map(k=>k.tabKey);return ja(d.current,I)?d.current:(d.current=I,I)},[f]);return{chatIdes:a,conversations:x,visibleConversations:f,visibleTabKeys:T,resolveConversationBySessionId:g,resolveConversationByTarget:v}}function Xb({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=i.useMemo(()=>{var c;return e||!t?null:((c=r(t))==null?void 0:c.tabKey)??null},[e,r,t]),o=i.useMemo(()=>{var c;return!e||!t?null:((c=r(t))==null?void 0:c.tabKey)??null},[e,r,t]),l=i.useCallback(()=>{t&&n(c=>{const d=new URLSearchParams(c);return d.delete("activeTab"),d},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:l}}function Jb({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){i.useEffect(()=>{it.setIdes(e)},[e]),i.useEffect(()=>{it.setResolveAction((a,o,l)=>{t(a,o,l).catch(()=>{})})},[t]),i.useEffect(()=>{const a=it.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 l=o.duration||5e3;setTimeout(()=>r(c=>c.filter(d=>d.id!==o.id)),l)});return()=>{a()}},[r]),i.useEffect(()=>{const a=od.on("status_event",o=>{it.handleRawEvent(o,"ws")});return()=>{a()}},[]),i.useEffect(()=>{var o;const a=l=>{var p;const c=l.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const d=c.targetSessionId||c.targetKey||c.daemonId,m=n(d),u=(m==null?void 0:m.routeId)||c.daemonId;if(!u)return;const h=Number(c.buttonIndex),x=c.button||((p=m==null?void 0:m.modalButtons)==null?void 0:p[h])||"Approve",S=String(x).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),b=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(S);t(u,"resolve_action",{action:b?"approve":"reject",button:x,...Number.isFinite(h)&&{buttonIndex:h},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(g=>console.error("[SW Action] approval failed:",g))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var l;return(l=navigator.serviceWorker)==null?void 0:l.removeEventListener("message",a)}},[n,t])}const Qb="adhdev_dashboardLayout_v1",Zb="adhdev_dashboardDockview_v1",eg="adhdev_dashboardDockviewHiddenRestore_v1",mr={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function ai(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function tg(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Od(e){return`${Qb}:${e}`}function sg(e){const t=Od(e);return ai(t,null)}function rg(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=Od(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Fd(e){return`${Zb}:${e}`}function ng(e){const t=Fd(e);return ai(t,null)}function ag(e,t){try{const r=Fd(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Wd(e){return`${eg}:${e}`}function og(e){const t=Wd(e);return ai(t,{})}function ig(e,t){try{const r=Wd(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function lg(){return{groupAssignments:[...mr.groupAssignments],focusedGroup:mr.focusedGroup,groupActiveTabIds:{...mr.groupActiveTabIds},groupTabOrders:{...mr.groupTabOrders},groupSizes:[...mr.groupSizes]}}function cg(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function dg(){const[e]=i.useState(()=>tg(typeof window<"u"?window.innerWidth:1280)),[t,r]=i.useState(()=>new Map),[n,a]=i.useState(0),[o,l]=i.useState({}),[c,d]=i.useState({}),[m,u]=i.useState([]),[h,x]=i.useState(()=>typeof window<"u"&&window.innerWidth<768),[S,b]=i.useState(!1),p=i.useCallback(()=>{if(S)return;const w=sg(e)??lg();r(new Map(w.groupAssignments)),a(w.focusedGroup),l(w.groupActiveTabIds),d(w.groupTabOrders),u(w.groupSizes),b(!0)},[S,e]);i.useEffect(()=>{S&&rg(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:c,groupSizes:m})},[S,e,t,n,o,c,m]),i.useEffect(()=>{const w=window.matchMedia("(max-width: 767px)"),D=M=>x(M.matches);return w.addEventListener("change",D),()=>w.removeEventListener("change",D)},[]);const g=i.useCallback(w=>{r(w)},[]),v=i.useCallback(w=>{a(w)},[]),f=i.useCallback(w=>{l(w)},[]),T=i.useCallback(w=>{d(w)},[]),I=i.useCallback(w=>{u(w)},[]),k=i.useCallback(w=>{v(w)},[v]),A=i.useCallback((w,D)=>{l(M=>(M[w]??null)===(D??null)?M:{...M,[w]:D})},[]),_=i.useCallback((w,D)=>{d(M=>{const j=M[w];return cg(j,D)?M:{...M,[w]:D}})},[]),N=i.useCallback((w,D)=>{const M=D.get(w)??0;return A(M,w),k(M),M},[k,A]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:g,focusedGroup:n,updateFocusedGroup:v,focusGroup:k,groupActiveTabIds:o,updateGroupActiveTabIds:f,setGroupActiveTab:A,groupTabOrders:c,updateGroupTabOrders:T,setGroupTabOrder:_,groupSizes:m,updateGroupSizes:I,isMobile:h,hasHydratedStoredLayout:S,hydrateStoredLayout:p,focusConversationTab:N}}function ug(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Vo(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function mg({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:l,setSearchParams:c,historyModalOpen:d,activeConv:m,isRefreshingHistory:u,ides:h,handleRefreshHistory:x}){const S=i.useRef(!1),b=i.useRef(!1),p=i.useRef(null),g=i.useRef(!1);i.useEffect(()=>{if(!e||S.current||t.length===0)return;if(!a){o();return}const v=r(e);v&&(l(v.tabKey,n),S.current=!0,b.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),c(f=>{const T=new URLSearchParams(f);return T.delete("activeTab"),T},{replace:!0}))},[e,t,r,n,a,o,l,c]),i.useEffect(()=>{if(!(b.current||a)&&t.length!==0){if(!e){o(),b.current=!0;return}if(S.current){b.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(b.current||a)&&(o(),b.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,o]),i.useEffect(()=>{if(!d){g.current=!1;return}if(!m||g.current||u)return;const v=h.find(f=>f.id===m.routeId);v&&(!v.chats||v.chats.length===0||ug(v.chats,m))&&(g.current=!0,x())},[d,m,u,h,x])}function ka(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=Vo(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Kd({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[l,c]=i.useState(!1),[d,m]=i.useState(!1),u=i.useCallback(async b=>{try{await e("standalone","launch_ide",{ideType:b,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),h=i.useCallback(async(b,p)=>{try{const g=b||(t==null?void 0:t.daemonId)||"",v=await e(g,"switch_chat",{id:p,sessionId:p,...xs(t)}),f=v==null?void 0:v.result;if((v==null?void 0:v.success)===!0||f==="switched"||f==="switched-by-title")return;f===!1||f==="not_found"?lr(a,"⚠️ Session tab not found — try refreshing history"):typeof f=="string"&&f.startsWith("error:")?lr(a,`⚠️ Switch error: ${f}`):lr(a,"⚠️ Session switch failed")}catch(g){console.error("Switch failed",g),lr(a,`❌ Switch failed: ${g.message||"connection error"}`)}},[t,e,a]),x=i.useCallback(async()=>{if(!(!t||l)){c(!0);try{const b=Gs(t);await e(b,"new_chat",{...xs(t)}),o(p=>({...p,[t.tabKey]:Date.now()}))}catch(b){console.error("New chat failed",b)}finally{c(!1)}}},[t,l,e,o]),S=i.useCallback(async()=>{var b,p;if(!(!t||d)){m(!0);try{const g=Gs(t),v=async()=>e(g,"list_chats",{forceExpand:!0,...xs(t)});let f=await v(),T=(f==null?void 0:f.chats)||((b=f==null?void 0:f.result)==null?void 0:b.chats);ka(T,t)&&(await new Promise(I=>setTimeout(I,450)),f=await v(),T=(f==null?void 0:f.chats)||((p=f==null?void 0:f.result)==null?void 0:p.chats)),f!=null&&f.success&&Array.isArray(T)&&(n(t.routeId,T),ka(T,t)&&!ka(r,t)&&lr(a,"⚠️ History dialog did not fully open — try once more"))}catch(g){console.error("Refresh history failed",g)}finally{m(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:h,handleNewChat:x,handleRefreshHistory:S}}function pg(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 hg(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function fl(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 en(e,t){const r=new Set(t),n=t.length>0?[0]:[];for(const[l,c]of e)!r.has(l)||c<=0||n.includes(c)||n.push(c);n.sort((l,c)=>l-c);const a={};n.forEach((l,c)=>{a[l]=c}),n.length===0&&(a[0]=0);const o=new Map;for(const[l,c]of e){if(!r.has(l)||c<=0)continue;const d=a[c];typeof d=="number"&&d>0&&o.set(l,d)}return{assignments:o,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function xl(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 fg(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 xg(e,t,r){if(t.length<=1)return[];const n=t.map(l=>e[l]).filter(l=>Number.isFinite(l)),a=n.length===t.length?n:Array(r).fill(100/r),o=a.reduce((l,c)=>l+c,0);return o>0?a.map(l=>l/o*100):Array(r).fill(100/r)}function bl(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 gl(e){return Array(e).fill(100/e)}function bg({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:l,isMobile:c,visibleConversations:d,visibleTabKeys:m}){const u=i.useRef(null),h=i.useMemo(()=>en(e,m),[e,m]),x=h.assignments,S=i.useMemo(()=>c?1:h.groupCount,[h.groupCount,c]),b=S>1,p=i.useCallback((k,A)=>{t(_=>{const N=new Map(en(_,m).assignments);return A===0?N.delete(k):N.set(k,A),N}),n(_=>({..._,[A]:k})),r(A)},[t,m,n,r]),g=i.useCallback(k=>{t(A=>{const _=en(A,m).assignments,N=new Map;for(const[w,D]of _)D!==k&&(D>k?N.set(w,D-1):N.set(w,D));return N}),l(A=>{if(A.length<=1)return[];const _=[...A];_.splice(k,1);const N=_.reduce((w,D)=>w+D,0);return N>0?_.map(w=>w/N*100):[]}),r(0)},[t,m,l,r]),v=i.useCallback((k,A)=>{A.preventDefault();const _=u.current;if(!_)return;const N=A.clientX,w=_.offsetWidth,D=o.length===S?[...o]:gl(S),M=W=>{const $=(W.clientX-N)/w*100,C=[...D];C[k]=Math.max(15,D[k]+$),C[k+1]=Math.max(15,D[k+1]-$),l(C)},j=()=>{document.removeEventListener("mousemove",M),document.removeEventListener("mouseup",j),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",M),document.addEventListener("mouseup",j)},[o,S,l]),f=i.useCallback((k,A,_)=>{if(S>=4)return;const N=_==="left"?A:A+1;t(w=>{const D=en(w,m).assignments,M=new Map;for(const j of d){const W=D.get(j.tabKey)??0,H=W>=N?W+1:W;H>0&&M.set(j.tabKey,H)}return N>0&&M.set(k,N),M}),l(w=>{const D=w.length===S?[...w]:gl(S),M=D[A]??100/S,j=Math.max(15,M/2),W=Math.max(15,M/2),H=[...D];H[A]=j,H.splice(N,0,W);const $=H.reduce((C,y)=>C+y,0);return H.map(C=>C/$*100)}),n(w=>{const D=bl(w,N);return D[N]=k,D}),a(w=>{const D=bl(w,N);return D[N]=[k],D}),r(N)},[S,t,m,d,l,n,a,r]);i.useEffect(()=>{pg(e,x)||t(x)},[e,x,t]),i.useEffect(()=>{const{mapping:k,usedGroups:A}=h;n(_=>{const N=xl(_,k);return fl(_,N)?_:N}),a(_=>{const N=xl(_,k);return fl(_,N)?_:N}),r(_=>{const N=c?0:fg(_,A,k);return _===N?_:N}),l(_=>{const N=c?[]:xg(_,A,h.groupCount);return hg(_,N)?_:N})},[h,c,n,a,r,l]);const T=i.useMemo(()=>{const k=Array.from({length:S},()=>[]);for(const A of d){const _=x.get(A.tabKey)??0,N=Math.min(_,S-1);k[N].push(A)}return k},[d,x,S]),I=i.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:x,numGroups:S,isSplitMode:b,groupedConvs:T,moveTabToGroup:p,closeGroup:g,handleResizeStart:v,splitTabRelative:f,clearAllSplits:I}}function Sa(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 gg(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 tn(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function oi(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=Sa(t.channel)||Sa(e.updateChannel)||Sa(e.releaseChannel)||void 0,n=gg(t.npmTag)||(r==="preview"?"next":r==="stable"?"latest":void 0),a=tn(t.targetVersion)||tn(e.serverVersion)||void 0,o=tn(t.minVersion)||void 0,l=tn(t.updateCommand)||(r?`adhdev update --channel ${r}`:void 0);return{...r?{channel:r}:{},...n?{npmTag:n}:{},...a?{targetVersion:a}:{},...o?{minVersion:o}:{},...l?{updateCommand:l}:{}}}function $s(e,t=null){return oi(e).targetVersion||t}function Hd(e){return oi(e).channel||null}function Ud(e){const t=oi(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 yg({ides:e,sendDaemonCommand:t}){const r="0.9.81",n=i.useMemo(()=>e.filter(h=>h.type!=="adhdev-daemon"?!1:Sd(h,$s(h,r))).sort((h,x)=>Number(Sr(x,$s(x,r)))-Number(Sr(h,$s(h,r)))),[r,e]),a=i.useMemo(()=>n.some(h=>Sr(h,$s(h,r))),[r,n]),o=i.useMemo(()=>n.map(h=>$s(h,r)).find(h=>typeof h=="string"&&h.trim().length>0)||r,[r,n]),[l,c]=i.useState(!1),[d,m]=i.useState({}),u=i.useCallback(async h=>{var S,b;const x=e.find(p=>p.id===h);if(x){m(p=>({...p,[h]:"upgrading"}));try{const p=await t(h,"daemon_upgrade",Ud(x));(S=p==null?void 0:p.result)!=null&&S.upgraded||(b=p==null?void 0:p.result)!=null&&b.success?m(g=>({...g,[h]:"done"})):m(g=>({...g,[h]:"error"}))}catch{m(p=>({...p,[h]:"error"}))}}},[e,t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:l,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const zd=80;function gn(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function vg(e){return{...e,createdAt:gn(e.createdAt),updatedAt:gn(e.updatedAt,e.createdAt),lastEventAt:gn(e.lastEventAt,e.updatedAt||e.createdAt)}}function wg(e){const t=Go(e);return t==="unknown:"?e.id:t}function jg(e){return[e.type,Zc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function kg(e,t=zd){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=wg(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 Sg(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 l=zn(a,t),c=l.inboxBucket==="needs_attention"?"needs_attention":l.inboxBucket==="task_complete"&&l.unread?"task_complete":null;if(!c)continue;const d=gn(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),m=jg({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(vg({id:m,dedupKey:m,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Hc(a),preview:Zh(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return kg(n)}function Ng(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function Cg(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=zd}=e,a=i.useMemo(()=>Sg(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=i.useMemo(()=>Ng(a),[a]);return{notifications:a,unreadCount:o}}function Ig({notifications:e,sendDaemonCommand:t}){const r=i.useCallback(o=>{const l=e.find(d=>d.id===o),c=Math.max(Date.now(),(l==null?void 0:l.updatedAt)||0);l!=null&&l.sessionId&&t(l.machineId||l.routeId,"mark_session_seen",{sessionId:l.sessionId,seenAt:c}).catch(()=>{})},[e,t]),n=i.useCallback(o=>{const l=e.find(c=>c.id===o);l!=null&&l.sessionId&&t(l.machineId||l.routeId,"mark_notification_unread",{sessionId:l.sessionId,notificationId:l.id}).catch(()=>{})},[e,t]),a=i.useCallback(o=>{const l=e.find(c=>c.id===o);l!=null&&l.sessionId&&t(l.machineId||l.routeId,"delete_notification",{sessionId:l.sessionId,notificationId:l.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}const Tg=i.createContext(null);function Vd(){return i.useContext(Tg)}function Jn(...e){const t=new Set,r=[],n=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const l=o.toLowerCase();t.has(l)||(t.add(l),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 Mg(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 Qn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=Mg(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 Ag(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 _g(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Zn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=_g(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,l=o.includes("\\")?"\\":"/",c=(m,u)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${u}`:m==="/"||m==="\\"?`${l}${u}`:`${m.replace(/[\\/]+$/,"")}${l}${u}`,d=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,u)=>m.name.localeCompare(u.name)):[];return{path:o,directories:d}}function Lg(e,t){const r={meshId:t.meshId||"",workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp"};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand)\s*\}\}/g,(n,a)=>r[a]||"")}function Gd(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:Lg(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function Rg(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 Zt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function qd(e){return $r(e)||e.tabKey||e.routeId||null}function Yd(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 l=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(t&&l.includes(t)||r&&l.includes(r)||n&&o.routeId===n)});if(a!=null&&a.tabKey)return a.tabKey;if(n){const o=Wt(e.conversations,n)||e.conversations.find(l=>l.routeId===n);if(o!=null&&o.tabKey)return o.tabKey}return t||r||n||null}function ns(e){return String(e||"").trim()}function Xd(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Bn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Pg(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Dg(e,t){const r=ns(e.providerSessionId),n=ns(e.targetSessionId),a=t.find(o=>{const l=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(ns).filter(Boolean);return!!(r&&l.includes(r)||n&&l.includes(n))});return a?a.tabKey:n||r||null}function Eg(e,t,r){if(t.event!=="agent:generating_completed")return null;const n=Xd(t.daemonId);if(n&&n!==e.machineId)return null;const a=ns(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=ns(e.resumeSessionId),l=ns(e.launchedSessionId),c=ns(t.providerSessionId),d=ns(t.targetSessionId);if(o&&o!==c&&o!==d||l&&l!==c&&l!==d)return null;const m=Bn(e.workspacePath);if(m){const u=Bn(t.workspaceName);if(u&&!Pg(u,m))return null}return Dg(t,r)}function yl(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function $g({ides:e,conversations:t,onOpenSession:r}){const[n,a]=i.useState(null),o=i.useRef(null),l=i.useCallback(()=>{o.current=null,a(null)},[]),c=i.useCallback(d=>{o.current=d,a(d)},[]);return i.useEffect(()=>{if(!n)return;const d=Bn(n.workspacePath),m=e.find(h=>{var g,v,f,T;if(!h||h.type==="adhdev-daemon"||Xd(h.daemonId||h.id)!==n.machineId||(_r(h)?"cli":Fs(h)?"acp":"ide")!==n.kind)return!1;const b=String(h.agentType||h.type||"");if(n.providerType&&b!==n.providerType)return!1;if(n.resumeSessionId)return String(h.providerSessionId||"")===n.resumeSessionId;if(n.launchedSessionId){const I=String(n.launchedSessionId||"");return[h.providerSessionId,h.sessionId,h.instanceId,h.id].map(A=>String(A||"")).filter(Boolean).includes(I)}if(d){const I=Bn(h.workspace||h.runtimeWorkspaceLabel);return I?I===d:!1}return Number(h.lastUpdated||h._lastUpdate||h.timestamp||((T=(f=(v=(g=h.activeChat)==null?void 0:g.messages)==null?void 0:v.at)==null?void 0:f.call(v,-1))==null?void 0:T.timestamp)||0)>=n.startedAt-5e3});if(!m)return;const u=Yd({entrySessionId:m.sessionId,entryInstanceId:m.instanceId,entryRouteId:m.id,conversations:t});u&&(l(),r(u))},[l,t,e,r,n]),i.useEffect(()=>it.onStatusEvent(d=>{const m=o.current;if(!m)return;const u=Eg(m,d,t);u&&(l(),r(u))}),[l,t,r]),i.useEffect(()=>{if(!n)return;const d=window.setTimeout(()=>{a(m=>!m||m.startedAt!==n.startedAt?m:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[n]),{trackPendingLaunch:c}}function Bg({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const l=Vd(),c=i.useCallback(async(p,g)=>Zn(e,p,g),[e]),d=i.useCallback(async(p,g)=>{if(!g.trim())return{ok:!1,error:"Choose a workspace path first."};try{const v=await e(p,"workspace_add",{path:g.trim()});return v!=null&&v.success?{ok:!0}:{ok:!1,error:(v==null?void 0:v.error)||"Could not save workspace"}}catch(v){return{ok:!1,error:v instanceof Error?v.message:"Could not save workspace"}}},[e]),m=i.useCallback(async(p,g,v)=>{var f;try{const T={ideType:g,enableCdp:!0};(f=v==null?void 0:v.workspacePath)!=null&&f.trim()&&(T.workspace=v.workspacePath.trim());const I=await e(p,"launch_ide",T);return!(I!=null&&I.success)&&(I==null?void 0:I.success)!==void 0?{ok:!1,error:(I==null?void 0:I.error)||"Could not launch IDE"}:(t({machineId:p,kind:"ide",providerType:g,workspacePath:(v==null?void 0:v.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(T){return{ok:!1,error:T instanceof Error?T.message:"Could not launch IDE"}}},[e,t]),u=i.useCallback(async(p,g,v,f)=>{var I,k,A;const T=Date.now();try{const _={cliType:v};(I=f==null?void 0:f.workspacePath)!=null&&I.trim()?_.dir=f.workspacePath.trim():f!=null&&f.workspaceId&&(_.workspaceId=f.workspaceId),(k=f==null?void 0:f.resumeSessionId)!=null&&k.trim()&&(_.resumeSessionId=f.resumeSessionId.trim()),Array.isArray(f==null?void 0:f.cliArgs)&&f.cliArgs.length>0&&(_.cliArgs=f.cliArgs),(A=f==null?void 0:f.initialModel)!=null&&A.trim()&&(_.initialModel=f.initialModel.trim());const N=await e(p,"launch_cli",_),w=(N==null?void 0:N.result)||N,D=(w==null?void 0:w.sessionId)||(w==null?void 0:w.id);return N!=null&&N.success&&D?(t({machineId:p,kind:g,providerType:v,workspacePath:(f==null?void 0:f.workspacePath)||null,resumeSessionId:(f==null?void 0:f.resumeSessionId)||null,launchedSessionId:D,startedAt:T}),{ok:!0}):N!=null&&N.success?(t({machineId:p,kind:g,providerType:v,workspacePath:(f==null?void 0:f.workspacePath)||null,resumeSessionId:(f==null?void 0:f.resumeSessionId)||null,startedAt:T}),{ok:!0}):{ok:!1,error:(N==null?void 0:N.error)||(w==null?void 0:w.error)||`Could not launch ${g.toUpperCase()} session`}}catch(_){return yl(_)?(t({machineId:p,kind:g,providerType:v,workspacePath:(f==null?void 0:f.workspacePath)||null,resumeSessionId:(f==null?void 0:f.resumeSessionId)||null,startedAt:T}),{ok:!0}):{ok:!1,error:_ instanceof Error?_.message:`Could not launch ${g.toUpperCase()} session`}}},[r,e,t]),h=i.useCallback(async p=>{var g;if(l!=null&&l.listMeshes)return l.listMeshes(p);if(!p)return[];try{const v=await e(p,"list_meshes",{}),f=(v==null?void 0:v.result)??v;if((f==null?void 0:f.success)===!1)throw new Error((f==null?void 0:f.error)||"Could not load meshes");return(Array.isArray(f==null?void 0:f.meshes)?f.meshes:Array.isArray((g=f==null?void 0:f.result)==null?void 0:g.meshes)?f.result.meshes:[]).map(I=>{var k;return{id:String((I==null?void 0:I.id)||""),name:String((I==null?void 0:I.name)||(I==null?void 0:I.id)||"Untitled mesh"),repoIdentity:(I==null?void 0:I.repoIdentity)||(I==null?void 0:I.repo_identity)||null,workspace:Array.isArray(I==null?void 0:I.nodes)&&I.nodes.length>0?String(((k=I.nodes[0])==null?void 0:k.workspace)||""):null,nodesCount:Array.isArray(I==null?void 0:I.nodes)?I.nodes.length:void 0,status:(I==null?void 0:I.status)||null}}).filter(I=>I.id)}catch(v){throw console.error("List meshes failed",v),v}},[l,e]),x=i.useCallback(async(p,g,v)=>{if(!g.trim())return{ok:!1,error:"Choose a mesh first."};if(l!=null&&l.launchMeshCoordinator)return l.launchMeshCoordinator(p,g,v);const f=Date.now();try{const T={meshId:g.trim()};v.trim()&&(T.cliType=v.trim());const I=await e(p,"launch_mesh_coordinator",T),k=(I==null?void 0:I.result)??I;if((k==null?void 0:k.success)===!1||(I==null?void 0:I.success)===!1){const _=String((k==null?void 0:k.code)||(I==null?void 0:I.code)||""),N=Rg((k==null?void 0:k.meshCoordinatorSetup)||(k==null?void 0:k.manualSetup)||(I==null?void 0:I.meshCoordinatorSetup)||(I==null?void 0:I.manualSetup));return{ok:!1,error:(k==null?void 0:k.error)||(I==null?void 0:I.error)||"Could not launch mesh coordinator",code:_||void 0,manualSetup:N}}const A=(k==null?void 0:k.sessionId)||(k==null?void 0:k.id);return A?r(A):t({machineId:p,kind:"cli",providerType:(k==null?void 0:k.cliType)||v.trim()||void 0,workspacePath:(k==null?void 0:k.workspace)||null,startedAt:f}),{ok:!0}}catch(T){return yl(T)?(t({machineId:p,kind:"cli",providerType:v.trim()||void 0,startedAt:f}),{ok:!0}):{ok:!1,error:T instanceof Error?T.message:"Could not launch mesh coordinator"}}},[l,r,e,t]),S=i.useCallback(async(p,g)=>{if(!p||!g)return[];try{const v=await e(p,"list_saved_sessions",{providerType:g,kind:"cli",limit:30}),f=(v==null?void 0:v.result)??v;return Array.isArray(f==null?void 0:f.sessions)?f.sessions:[]}catch(v){return console.error("List saved sessions failed",v),[]}},[e]),b=i.useCallback(async p=>{await Dd({conversation:n,mode:p,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:d,handleLaunchMachineIde:m,handleLaunchMachineProvider:u,handleListMachineMeshes:h,handleLaunchMeshCoordinator:x,handleListMachineSavedSessions:S,setActiveCliViewMode:b}}function Og(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 Fg(e,t,r=Date.now()){return!e||!Og(t)?null:{tabKey:e,nonce:r}}function Wg({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:l}){const[c,d]=i.useState(null),[m,u]=i.useState(null),h=i.useMemo(()=>{var g,v;if(!e){if(c){const f=t.find(T=>T.tabKey===c);if(f)return f}return r[0]}const p=n[a];if(p){const f=t.find(T=>T.tabKey===p);if(f)return f}return((g=o[a])==null?void 0:g[0])||((v=o[0])==null?void 0:v[0])},[t,c,a,n,o,e,r]),x=i.useCallback(p=>{d(p)},[]),S=i.useCallback(p=>{d(p.tabKey),l(g=>{const v=new URLSearchParams(g),f=tf(p);return f?v.set("activeTab",f):v.delete("activeTab"),v},{replace:!0})},[l]),b=i.useCallback((p,g)=>{const v=Fg(p,g);v&&u(v)},[]);return{activeConv:h,openDesktopConversation:S,requestScrollToBottom:b,scrollToBottomRequest:m,setDesktopActiveTab:x}}function Kg(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 Hg(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 Ug({activeConv:e,isMobile:t,liveSessionInboxState:r,sendDaemonCommand:n}){const a=i.useRef(null),o=i.useRef(null),l=i.useRef(null),c=i.useRef(null),d=i.useRef(null);i.useEffect(()=>{const m=()=>{l.current&&(clearTimeout(l.current),l.current=null),c.current&&(clearTimeout(c.current),c.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const u=Tn(e,r),h=Hg({tabKey:e.tabKey,historySessionId:$r(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:js(e),liveState:u}),x=h.autoReadKey,S=Kg({autoReadKey:x,shouldMarkSeen:h.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!h.shouldMarkSeen){S.shouldCancelPending&&m(),a.current=x;return}if(!S.shouldSchedule)return;S.shouldCancelPending&&m();const b=()=>{if(document.visibilityState!=="visible"||a.current===x)return;a.current=x,o.current=null,l.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const g=h.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:g,completionMarker:h.completionMarker}).catch(()=>{})};if(o.current=S.nextPendingKey,document.visibilityState==="visible"){l.current=setTimeout(b,1500);const g=()=>{document.visibilityState!=="visible"&&l.current&&(clearTimeout(l.current),l.current=null)};d.current=g,document.addEventListener("visibilitychange",g);return}const p=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(b,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=p,document.addEventListener("visibilitychange",p)},[e,t,r,n]),i.useEffect(()=>()=>{l.current&&clearTimeout(l.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function Na(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 zg({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:l,setClearedTabs:c,setSearchParams:d}){var y;const[m,u]=i.useState(!1),[h,x]=i.useState([]),[S,b]=i.useState(()=>Ct()),[p,g]=i.useState(!1),[v,f]=i.useState(null),T=i.useRef(null),I=i.useMemo(()=>r||t||e,[e,r,t]),k=!!I&&at(I)&&!st(I),A=i.useMemo(()=>{if(!I||!k)return null;const F=I.daemonId||I.routeId||"",P=Gt(I),E=Na(I);return`${F}:${P}:${I.providerSessionId||""}:${E}`},[I,k]),_=i.useMemo(()=>!I||!k?"":Na(I),[I,k]),{isCreatingChat:N,isRefreshingHistory:w,handleSwitchSession:D,handleNewChat:M,handleRefreshHistory:j}=Kd({sendDaemonCommand:a,activeConv:I,chats:(y=n.find(F=>F.id===(I==null?void 0:I.routeId)))==null?void 0:y.chats,updateRouteChats:o,setToasts:l,setClearedTabs:c}),W=i.useCallback(()=>{u(!0)},[]),H=i.useCallback(()=>{u(!1)},[]),$=i.useCallback(async()=>{if(!(!I||!k||p)){g(!0);try{const F=I.daemonId||I.routeId,P=Gt(I),E=Na(I),G=await a(F,"list_saved_sessions",{agentType:P,providerType:P,kind:"cli",limit:50,...I.providerSessionId?{providerSessionId:I.providerSessionId}:{},...E?{workspace:E}:{}}),J=(G==null?void 0:G.result)??G;x(Array.isArray(J==null?void 0:J.sessions)?J.sessions:[])}catch(F){console.error("Refresh saved sessions failed",F),x([])}finally{g(!1)}}},[I,p,k,a]);i.useEffect(()=>{if(!m){T.current=null;return}if(!k){T.current=null,x([]),g(!1);return}!A||p||T.current!==A&&(T.current=A,$())},[$,m,p,k,A]);const C=i.useCallback(async F=>{if(!I||!k||!F.providerSessionId||!F.workspace)return;const P=I.daemonId||I.routeId,E=Gt(I);try{f(F.providerSessionId);const G=await a(P,"launch_cli",{cliType:E,dir:F.workspace,resumeSessionId:F.providerSessionId,initialModel:Dc(F.summaryMetadata,"model",{preferShortValue:!0})||void 0}),J=(G==null?void 0:G.result)??G,ye=typeof(J==null?void 0:J.sessionId)=="string"?J.sessionId:typeof(J==null?void 0:J.id)=="string"?J.id:"";ye&&d(he=>{const ne=new URLSearchParams(he);return ne.set("activeTab",ye),ne},{replace:!0}),H()}catch(G){console.error("Resume saved session failed",G)}finally{f(null)}},[H,I,k,a,d]);return{historyModalOpen:m,openHistoryModal:W,closeHistoryModal:H,historyTargetConv:I,isSavedSessionHistoryTarget:k,isHistoryCreatingChat:N,isHistoryRefreshingHistory:w,handleHistorySwitchSession:D,handleHistoryNewChat:M,handleHistoryRefresh:j,savedHistorySessions:h,savedHistoryFilters:S,setSavedHistoryFilters:b,missingWorkspaceResumePath:_,isSavedHistoryLoading:p,resumingSavedHistorySessionId:v,handleRefreshSavedHistory:$,handleResumeSavedHistorySession:C}}function Vg({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:l,resolveConversationByTarget:c}){const[d,m]=i.useState(null),[u,h]=i.useState(null),x=i.useMemo(()=>{if(e||!n)return null;const v=c(n);return v&&!at(v)&&!st(v)?v:null},[e,n,c]),S=i.useMemo(()=>{const v=d==null?void 0:d.routeId;if(!v)return null;const f=d!=null&&d.tabKey?o.find(T=>T.tabKey===d.tabKey):a?o.find(T=>T.tabKey===a):null;return(f==null?void 0:f.routeId)===v?f:Wt(o,v)},[o,d,a]),b=i.useMemo(()=>{if(S)return l.find(v=>v.id===S.routeId)},[l,S]);i.useEffect(()=>{x&&(m({routeId:x.routeId,tabKey:Ui(x)}),h(x),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,x]);const p=i.useCallback(v=>{v&&(m({routeId:v.routeId,tabKey:Ui(v)}),h(v))},[]),g=i.useCallback(()=>{m(null),h(null)},[]);return{remoteDialogConv:S,remoteDialogIdeEntry:b,remoteDialogActiveConv:u,setRemoteDialogActiveConv:h,openRemoteDialog:p,closeRemoteDialog:g}}function Gg({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:l,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:m}){const{remoteDialogConv:u,remoteDialogIdeEntry:h,remoteDialogActiveConv:x,setRemoteDialogActiveConv:S,openRemoteDialog:b,closeRemoteDialog:p}=Vg({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:l,resolveConversationByTarget:c}),[g,v]=i.useState(!1),[f,T]=i.useState(null),I=i.useCallback(async _=>{const N=_||d;!N||!at(N)&&!st(N)||(T(N),v(!0))},[d]),k=i.useCallback(()=>{v(!1),T(null)},[]),A=i.useCallback(async _=>{const N=f||d;if(!N||!at(N)&&!st(N)){k();return}v(!1);try{const w=Gt(N),D=N.routeId||N.daemonId||"";await m(D,"stop_cli",{cliType:w,targetSessionId:N.sessionId,mode:_})}catch(w){console.error("Stop CLI failed:",w)}finally{T(null)}},[d,k,f,m]);return{remoteDialogConv:u,remoteDialogIdeEntry:h,remoteDialogActiveConv:x,setRemoteDialogActiveConv:S,openRemoteDialog:b,closeRemoteDialog:p,cliStopDialogOpen:g,cliStopTargetConv:f,requestCliStop:I,cancelCliStop:k,confirmCliStop:A}}function Jd({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:o=!1}){var T,I;const l=As(),c=_s(e),d=o?null:Kc(e),m=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),u=!o&&e.streamSource==="agent-stream"&&!!e.agentName,h=!o&&!u&&(e.transport==="pty"||e.transport==="acp"),x=Vs(e),S=ef(e),b=(T=e.settings)==null?void 0:T.meshNodeFor,p=e.meshQueueStats,g=(I=e.settings)==null?void 0:I.meshCoordinatorFor;if(!m&&!u&&!h&&!d&&!b&&!p)return null;const v=i.useCallback(()=>{if(n){n();return}c&&l("/dashboard",{state:{openMachineId:c}})},[c,l,n]),f=i.useCallback(()=>{if(r){r();return}const k=qd(e);k&&l(Zt(k))},[e,l,r]);return s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[m&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:f,title:S,children:[s.jsx(_t,{size:12}),s.jsx("span",{children:S})]}):s.jsxs("span",{className:"conversation-meta-chip",title:S,children:[s.jsx(_t,{size:12}),s.jsx("span",{children:S})]})),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[s.jsx(zs,{size:12}),s.jsx("span",{children:x})]}),h&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[s.jsx(zs,{size:12}),s.jsx("span",{children:x})]}),d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:v,title:d,children:[s.jsx(is,{size:12}),s.jsx("span",{children:d})]}):s.jsxs("span",{className:"conversation-meta-chip",title:d,children:[s.jsx(is,{size:12}),s.jsx("span",{children:d})]})),b&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(is,{size:12}),s.jsx("span",{children:"Mesh Node"})]}),g&&p&&s.jsxs("span",{className:`conversation-meta-chip ${p.pending>0?"is-active":""}`,style:p.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${p.pending} pending, ${p.assigned} assigned, ${p.completed} completed, ${p.failed} failed`,children:[s.jsx(ep,{size:12}),s.jsxs("span",{children:[p.pending," Pending"]})]})]})}function Ca(e,t=!0){return(e??!0)&&t}const ii=i.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:l,handleRelaunch:c,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u=null,handleFocusAgent:h,isFocusingAgent:x,actionLogs:S,userName:b,scrollToBottomRequestNonce:p,isInputActive:g=!0,isVisible:v=!0}){const f=n,T=!n,I=Ca(v,f),k=Ca(v,T),A=Ca(v),_=Md(t),N=_.status||_.modalMessage||_.modalButtons?{...t,..._.status?{status:_.status}:{},..._.modalMessage!==void 0?{modalMessage:_.modalMessage}:{},..._.modalButtons!==void 0?{modalButtons:_.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Lc,{activeConv:N,onModalButton:l}),s.jsx(Jd,{conversation:N,className:"chat-pane-meta-row mx-3 mt-1",meshOnly:!0}),N.transport!=="pty"&&N.transport!=="acp"&&N.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(Ar,{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,N.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:f?"visible":"hidden",pointerEvents:f?"auto":"none"},children:s.jsx(fx,{activeConv:N,clearToken:r,terminalRef:o,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,isVisible:I,isInputActive:g&&I})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:T?"visible":"hidden",pointerEvents:T?"auto":"none"},children:s.jsx(po,{activeConv:N,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:h,isFocusingAgent:x,actionLogs:S,userName:b,scrollToBottomRequestNonce:p,isInputActive:g&&k,isVisible:k})})]}):s.jsx(po,{activeConv:N,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:h,isFocusingAgent:x,actionLogs:S,userName:b,scrollToBottomRequestNonce:p,isInputActive:g&&A,isVisible:A})]})},(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.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 qg({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:l,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:m,onOpenNativeConversation:u,onOpenMachine:h,onOpenHistory:x,onOpenRemote:S,onOpenMeshGraph:b,onStopCli:p,cliViewMode:g,onSetCliViewMode:v,handleSendChat:f,handleFocusAgent:T,handleModalButton:I,handleRelaunch:k}){var M;const A=i.useRef(null),_=at(e)&&!t,N=_&&g==="terminal",w=!!e.daemonId&&typeof((M=e.settings)==null?void 0:M.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.length>0,D=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 ${D} 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(Ao,{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:ut(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(Jd,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>h(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[_&&g&&s.jsx(Yo,{mode:g,onChange:v,compact:!0}),_&&p&&s.jsx("button",{onClick:()=>{p(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(wt,{size:14})}),w&&b&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>b(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(as,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(e),type:"button",children:s.jsx(_o,{size:14})}),!t&&!_&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e),type:"button",children:s.jsx(_t,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(ii,{activeConv:e,clearToken:0,isCliTerminal:N,ideEntry:n,terminalRef:A,handleModalButton:I,handleRelaunch:k,handleSendChat:f,isSendingChat:l,sendFeedbackMessage:c,handleFocusAgent:T,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const Ia={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 Yg(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Qd(){const[e,t]=i.useState("unix"),[r,n]=i.useState("powershell"),[a,o]=i.useState(!1),l=e==="unix"?"unix":r;i.useEffect(()=>{t(Yg())},[]);const c=i.useCallback(()=>{navigator.clipboard.writeText(Ia[l].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[l]);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:Ia[l].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Ia[l].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 Zd({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:_t},{key:"chats",label:"Chats",icon:es}];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 l=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 ${l?"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:l?{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":l,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${l?"text-accent-primary":"bg-transparent text-current"}`,style:l?{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 sn({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 Ls({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 pr({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 Xg({conversation:e,onCancel:t,onConfirm:r}){const n=ut(e),a=Is(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(wt,{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 rn({item:e,type:t,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onOpenMeshGraph:o,onCollectChatDebugBundle:l}){var D;const c=t==="needs_attention"||t==="task_complete",d=t==="working",m=t==="earlier",u=t==="task_complete",{isReconnecting:h,isConnecting:x}=Qs(e.conversation),S=ut(e.conversation),b=Is(e.conversation),p=ld(e.conversation,{requiresAction:t==="needs_attention"}),g=c?"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%)]":m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",v=c?"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":m?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",f=m?"text-text-secondary":"text-text-primary",T=m?"text-text-muted":"text-text-secondary",I=m?"text-text-secondary opacity-80":"text-text-muted",k=m?"text-text-muted opacity-80":"text-text-muted",A=!d&&!u,_=!!e.conversation.daemonId&&typeof((D=e.conversation.settings)==null?void 0:D.meshCoordinatorFor)=="string"&&e.conversation.settings.meshCoordinatorFor.length>0,N="text-[color:var(--status-warning)]",w=M=>{if(!l)return;M.preventDefault(),M.stopPropagation();const j=l==null?void 0:l(e.conversation);Promise.resolve(j).catch(W=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",W)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${g}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[c||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:c?{color:"var(--accent-on-primary)"}:void 0,children:r(S)}),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:M=>{M.preventDefault(),M.stopPropagation(),a()},"aria-label":`Hide ${S}`,title:"Hide conversation",children:[s.jsx(Lo,{size:11}),s.jsx("span",{children:"Hide"})]}),_&&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:M=>{M.preventDefault(),M.stopPropagation(),o(e.conversation)},"aria-label":`Open mesh graph for ${S}`,title:"Open live repo mesh graph",children:[s.jsx(as,{size:11}),s.jsx("span",{children:"Graph"})]})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>n(e.conversation),onContextMenu:w,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 ${f}`,children:S}),A&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${k}`,children:_c(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${T}`,children:[s.jsx("span",{className:"truncate",children:b}),s.jsx(qs,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),h?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${N} animate-pulse`,children:"Reconnecting…"})]}):x?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):p==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:N,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${I}`,children:e.preview})]}),c&&!u&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),u&&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 vl({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 Jg({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:l,getAvatarText:c,actionLogs:d,sendDaemonCommand:m,onOpenConversation:u,onShowAllHidden:h,onHideConversation:x,onOpenMeshGraph:S,onOpenNewSession:b,onOpenMachine:p,onOpenSettings:g,onSectionChange:v,wsStatus:f="connected",isStandalone:T=!1,onCollectChatDebugBundle:I}){const[k,A]=i.useState(null),_=f==="disconnected"||f==="reconnecting"||f==="offline"||f==="auth_failed",N=l.length>0,w=t.length>0||r.length>0||n.length>0||a.length>0,D=e==="machines"?"Machines":"Chats",M=T?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",j=T?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",W=i.useCallback(async C=>{const y=Gs(C);if(!y)return;const F=Array.isArray(C.messages)?C.messages:[],P=qc({activeConv:C,visibleMessages:F,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:F.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),E=await m(y,"get_chat_debug_bundle",{...xs(C),delivery:"daemon_file",frontendSnapshot:P}),G=Ln(E),J=Jc(G),ye=await Xc(J);ye==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),it.showToast(Yc(G,{locatorCopyStatus:ye}),ye==="failed"?"warning":"success")},[d,m]),H=I||W,$=i.useCallback(()=>{k&&(x==null||x(k),A(null))},[k,x]);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 ${M}`,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:D}),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(Hn,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:g,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(Kn,{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] ${j}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:_?s.jsx(pr,{icon:s.jsx(vl,{}),title:f==="offline"?"Network offline":f==="auth_failed"?"Session expired":"Reconnecting",subtitle:f==="offline"?"Waiting for network…":f==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):l.length===0?s.jsx(pr,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:T?"Waiting for your daemon":"Connect your machines",subtitle:T?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.",children:!T&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Qd,{})})}):s.jsx(Ls,{children:l.map((C,y)=>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] ${y>0?"border-t border-border-subtle/70":""}`,onClick:()=>p(C.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(C.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:C.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:C.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[C.unread," new"]}):C.total>0?`${C.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:C.subtitle}),C.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[C.total," chat",C.total!==1?"s":"",C.unread>0?` · ${C.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},C.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(sn,{title:"Needs attention",className:"mb-0"}),s.jsx(Ls,{children:t.map((C,y)=>s.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:s.jsx(rn,{item:C,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:x?()=>A(C.conversation):void 0,onOpenMeshGraph:S,onCollectChatDebugBundle:H})},C.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(sn,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(Ls,{children:r.map((C,y)=>s.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:s.jsx(rn,{item:C,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:x?()=>A(C.conversation):void 0,onOpenMeshGraph:S,onCollectChatDebugBundle:H})},C.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(sn,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(Ls,{children:n.map((C,y)=>s.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:s.jsx(rn,{item:C,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:x?()=>A(C.conversation):void 0,onOpenMeshGraph:S,onCollectChatDebugBundle:H})},C.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(sn,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(Ls,{children:a.map((C,y)=>s.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:s.jsx(rn,{item:C,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:x?()=>A(C.conversation):void 0,onOpenMeshGraph:S,onCollectChatDebugBundle:H})},C.conversation.tabKey))}):w?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):_?s.jsx(pr,{icon:s.jsx(vl,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):N?s.jsx(pr,{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(es,{size:20})}),title:"No conversations yet",subtitle:ud,children:b&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:b,"aria-label":zt,title:zt,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:zt})]})}):s.jsx(pr,{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(Ls,{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:h,children:"Restore all"})]})})})]}),e==="chats"&&b&&w&&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:b,"aria-label":zt,title:zt,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"})]})}),k&&s.jsx(Xg,{conversation:k,onCancel:()=>A(null),onConfirm:$}),s.jsx(Zd,{section:e,onSectionChange:v})]})}function Qg(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 eu(e){const t=[e.workspace||"Workspace unknown"],r=Cs(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Qg(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function ea({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:o="",confirmLabel:l="Use this folder",onClose:c,onNavigate:d,onConfirm:m}){const[u,h]=i.useState(r);i.useEffect(()=>{h(r)},[r]);const x=Ag(r),S=u.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(wt,{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:()=>{!x||a||d(x)},disabled:!x||a,children:[s.jsx(Ao,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:b=>h(b.target.value),onKeyDown:b=>{b.key!=="Enter"||!S||a||(b.preventDefault(),d(S))},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:()=>{!S||a||d(S)},disabled:!S||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(b=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(b.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(Ns,{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:b.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:b.path})]})]},b.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(S||r),disabled:!S&&!r||a,children:l})]})]})})}function li({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:l="Launch",busyLabel:c="Launching…",busy:d=!1,showArgsInput:m,argsValue:u,onArgsChange:h,showModelInput:x,modelValue:S,onModelChange:b,historyProviderNode:p,onConfirm:g,onCancel:v}){const f=n==null?void 0:n.find(T=>T.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:v,"aria-label":"Close launch confirmation",children:s.jsx(wt,{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:T=>o(T.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:n.map(T=>s.jsx("option",{value:T.key,children:T.label},T.key))}),(f==null?void 0:f.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:f.description})]}),p,r.map(T=>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:T.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:T.value})]},`${T.label}:${T.value}`)),x&&b&&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:S||"",onChange:T=>b(T.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),m&&h&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:u||"",onChange:T=>h(T.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:v,disabled:d,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:g,disabled:d,children:[s.jsx(Po,{size:14}),d?c:l]})]})]})})}function wl(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ks(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,o=[];a&&o.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const d of t.workspaces||[])o.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${wl(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const l=(r==null?void 0:r.trim())||"",c=l?(t.workspaces||[]).find(d=>d.path===l):null;if(l&&!c&&o.push({key:`custom:${l}`,label:wl(l),description:l,workspaceId:null,workspacePath:l}),n){const d=`saved:${n}`;if(o.some(m=>m.key===d))return{options:o,selectedKey:d}}return c?{options:o,selectedKey:`saved:${c.id}`}:l?{options:o,selectedKey:`custom:${l}`}:{options:o,selectedKey:"__home__"}}function Zg(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function ey(e){return[Zg(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function ty(e){return e.lastLaunchedAt?Un(e.lastLaunchedAt):""}function tu(e){return{metaText:ey(e),updatedLabel:ty(e)}}function Ta(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function sy({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var rt,pt,xt,vt;const l=Er(),[c,d]=i.useState(!1),m=(((rt=e.detectedIdes)==null?void 0:rt.length)||0)>0,u=i.useMemo(()=>(e.workspaces||[]).map(Te=>({id:Te.id,path:Te.path,label:Te.label})),[e]),h=e.defaultWorkspaceId||null,[x,S]=i.useState(h||((pt=u[0])==null?void 0:pt.id)||""),[b,p]=i.useState(""),[g,v]=i.useState(""),[f,T]=i.useState([]),[I,k]=i.useState(!1),[A,_]=i.useState(""),[N,w]=i.useState(!1),[D,M]=i.useState(Ta(m,t.length,r.length)),j=i.useRef(null),[W,H]=i.useState(null),$=i.useRef("__home__"),[C,y]=i.useState("__home__"),[F,P]=i.useState(""),[E,G]=i.useState(""),[J,ye]=i.useState(""),[he,ne]=i.useState([]),[ue,Se]=i.useState(()=>Ct().textQuery),[ve,X]=i.useState(()=>Ct().workspaceQuery),[xe,fe]=i.useState(()=>Ct().modelQuery),[we,be]=i.useState(()=>Ct().resumableOnly),[Ce,ee]=i.useState(()=>Ct().sortMode),[me,ie]=i.useState(!1),[pe,le]=i.useState(!1),B=i.useRef(null),z=i.useRef(null);i.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&l(e.id,{minFreshMs:3e4}).catch(()=>{})},[l,e]);const de=x==="__custom__"?b.trim():((xt=u.find(Te=>Te.id===x))==null?void 0:xt.path)||"",re=x==="__custom__"&&!!de&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),R=x!=="__custom__"&&((vt=u.find(Te=>Te.id===x))==null?void 0:vt.path)||"",q=i.useMemo(()=>(e.recentLaunches||[]).map(Te=>Te.workspace),[e]),ce=i.useCallback(async Te=>{k(!0),_("");try{const Ve=await a(Te);v(Ve.path),p(Ve.path),T(Ve.directories)}catch(Ve){_(Ve instanceof Error?Ve.message:"Could not load folder")}finally{k(!1)}},[a]),Ne=i.useCallback(()=>{var Ve;S("__custom__"),w(!0);const Te=Qn(e.platform,Jn(b.trim(),R,q,e.defaultWorkspacePath,(Ve=u.find(tt=>tt.id===h))==null?void 0:Ve.path,u.map(tt=>tt.path)));ce(Te)},[b,h,ce,q,R,e.platform,u]),je=i.useCallback(Te=>{if(Te!=null&&Te.workspaceId){S(Te.workspaceId),p("");return}if(Te!=null&&Te.workspacePath){S("__custom__"),p(Te.workspacePath);return}S(""),p("")},[]),O=i.useCallback(Te=>{if(S(Te),Te==="__custom__"){Ne();return}p("")},[Ne]),Ie=i.useCallback(Te=>{S("__custom__"),p(Te)},[]),Le=i.useCallback((Te,Ve)=>{j.current=Ve,$.current=Te.selectedWorkspaceKey||"__home__",y(Te.selectedWorkspaceKey||"__home__"),P(Te.initialArgs||""),G(Te.initialModel||""),ye(""),ne([]);const tt=Te.providerType?`${e.id}:${Te.providerType}`:null;if(Cx(z.current,tt)){const Ge=Ct();Se(Ge.textQuery),X(Ge.workspaceQuery),fe(Ge.modelQuery),be(Ge.resumableOnly),ee(Ge.sortMode)}z.current=tt,H(Te),Te.providerType&&o&&(ie(!0),o(Te.providerType).then(Ge=>ne(Ge||[])).catch(Ge=>console.warn("Failed to load saved sessions",Ge)).finally(()=>ie(!1)))},[o,e.id]),He=i.useMemo(()=>md(he,{textQuery:ue,workspaceQuery:ve,modelQuery:xe,resumableOnly:we,sortMode:Ce}),[xe,we,he,Ce,ue,ve]);i.useEffect(()=>{J&&(He.some(Te=>Te.providerSessionId===J)||ye(""))},[He,J]);const ze=i.useCallback(()=>{j.current&&(le(!0),j.current().finally(()=>{j.current=null,le(!1),H(null)}))},[]),Xe=i.useCallback(()=>{j.current=null,H(null)},[]),Je=i.useCallback(Te=>{$.current=Te,y(Te)},[]);return i.useEffect(()=>{var Te;B.current!==e.id&&(B.current=e.id,S(h||((Te=u[0])==null?void 0:Te.id)||"__custom__"),p(""),v(""),T([]),_(""),w(!1),Se(Ct().textQuery),X(Ct().workspaceQuery),fe(Ct().modelQuery),be(Ct().resumableOnly),ee(Ct().sortMode),z.current=null,M(Ta(m,t.length,r.length)))},[r.length,t.length,h,m,e.id,u]),i.useEffect(()=>{var Te;x!=="__custom__"&&(x&&u.some(Ve=>Ve.id===x)||S(h||((Te=u[0])==null?void 0:Te.id)||"__custom__"))},[h,x,u]),i.useEffect(()=>{D==="ide"&&m||D==="cli"&&t.length>0||D==="acp"&&r.length>0||M(Ta(m,t.length,r.length))},[D,r.length,t.length,m]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:m,workspaceRows:u,defaultWorkspaceId:h,workspaceChoice:x,customWorkspacePath:b,browseCurrentPath:g,browseDirectories:f,browseBusy:I,browseError:A,browseDialogOpen:N,activeLauncherKind:D,launchConfirm:W,launchConfirmWorkspaceKeyRef:$,launchConfirmWorkspaceKey:C,launchConfirmArgs:F,launchConfirmModel:E,launchConfirmResumeId:J,launchConfirmSavedSessions:he,launchConfirmTextFilter:ue,launchConfirmWorkspaceFilter:ve,launchConfirmModelFilter:xe,launchConfirmResumableOnly:we,launchConfirmSortMode:Ce,filteredLaunchConfirmSavedSessions:He,launchConfirmSessionsLoading:me,launchConfirmBusy:pe,resolvedWorkspacePath:de,canCreateMissingWorkspace:re,openBrowseDialog:Ne,loadBrowsePath:ce,handleWorkspaceChoiceChange:O,chooseCustomWorkspacePath:Ie,setCustomWorkspacePath:p,setBrowseDialogOpen:w,setActiveLauncherKind:M,openLaunchConfirm:Le,handleConfirmLaunch:ze,closeLaunchConfirm:Xe,setWorkspaceSelectionFromOption:je,setLaunchConfirmWorkspaceKeyAndSync:Je,setLaunchConfirmArgs:P,setLaunchConfirmModel:G,setLaunchConfirmResumeId:ye,setLaunchConfirmTextFilter:Se,setLaunchConfirmWorkspaceFilter:X,setLaunchConfirmModelFilter:fe,setLaunchConfirmResumableOnly:be,setLaunchConfirmSortMode:ee}}function ry({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:l,machineAction:c,isStandalone:d,section:m,showBottomNav:u,onBack:h,onSectionChange:x,onOpenConversation:S,onOpenRecent:b,onOpenMachineDetails:p,onMachineUpgrade:g,onLaunchDetectedIde:v,onAddWorkspace:f,onBrowseDirectory:T,onLaunchWorkspaceProvider:I,onListSavedSessions:k}){const A=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",_=r.slice(0,4),N=t.slice(0,3),w=sy({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:c,onBrowseDirectory:T,onListSavedSessions:k}),D=i.useMemo(()=>_.map(C=>{const{metaText:y,updatedLabel:F}=tu(C);return{key:`recent-launch:${C.id}`,primary:C.label,secondary:y,updatedLabel:F,onClick:()=>{const{options:P,selectedKey:E}=ks({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspacePath:C.workspace});w.openLaunchConfirm({title:C.kind==="ide"?gs("restart-ide",C.label):C.providerSessionId?Qo(C.label):gs("start-fresh",C.label),description:C.kind==="ide"?ys("restart-ide"):C.providerSessionId?Zo():ys("start-fresh"),confirmLabel:C.kind==="ide"?Ys("restart-ide"):C.providerSessionId?Pn(!0):Ys("start-fresh"),busyLabel:C.kind==="ide"?Xs("restart-ide"):C.providerSessionId?Xo(!0):Xs("start-fresh"),workspaceOptions:P,selectedWorkspaceKey:E,details:[{label:"Mode",value:A(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const G=P.find(J=>J.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(G),await b({...C,workspace:(G==null?void 0:G.workspacePath)??null})})}}}),[w,b,_]),M=i.useMemo(()=>N.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:ut(C.conversation),secondary:ux(C.conversation,{timestampLabel:C.timestamp?_c(C.timestamp):null}),unread:C.unread,onClick:()=>S(C.conversation)})),[S,N]),j=w.showAllRecent?D:D.slice(0,4),W=D.length>0,H=M.length>0,$=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${$} 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:h,type:"button","aria-label":"Back",children:s.jsx(Ao,{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:At(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:[H&&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:M.map(C=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${C.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:C.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))})]}),W&&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:j.map(C=>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:C.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:C.primary}),C.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:C.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.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:()=>w.setShowAllRecent(C=>!C),children:w.showAllRecent?"Show fewer":`Show ${D.length-4} more`})})]}),(w.hasIdeOptions||n.length>0||a.length>0)&&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:"Start"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:s.jsxs("div",{className:"flex flex-col gap-2.5 w-full p-3.5 rounded-2xl border border-border-default/80 bg-surface-primary/90",children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),s.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),s.jsx("select",{value:w.workspaceChoice,onChange:C=>w.handleWorkspaceChoiceChange(C.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:w.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[w.workspaceRows.map(C=>s.jsxs("option",{value:C.id,children:[C.id===w.defaultWorkspaceId?"⭐ ":"",Vn(C.path,C.label)||C.path]},C.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),w.workspaceChoice==="__custom__"&&s.jsxs("div",{className:"flex flex-col gap-2.5",children:[s.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start gap-3",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(Ns,{size:17})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),s.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:w.resolvedWorkspacePath||w.browseCurrentPath||"No folder selected yet."})]})]})}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-secondary text-[12px] font-bold",onClick:w.openBrowseDialog,children:"Select workspace…"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-accent-primary/30 bg-accent-primary/10 text-text-primary text-[12px] font-bold disabled:opacity-40",onClick:()=>{w.resolvedWorkspacePath&&f(w.resolvedWorkspacePath)},disabled:!w.resolvedWorkspacePath||w.browseBusy,children:"Save as workspace"})]})]}),w.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[w.hasIdeOptions&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.activeLauncherKind==="ide"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>w.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.activeLauncherKind==="cli"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>w.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.activeLauncherKind==="acp"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>w.setActiveLauncherKind("acp"),children:"ACP"})]}),w.activeLauncherKind&&s.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[s.jsx("div",{className:"text-xs font-bold text-text-secondary",children:w.activeLauncherKind==="ide"?"Choose an IDE":w.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:w.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(C=>s.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:y,selectedKey:F}=ks({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspaceId:w.workspaceChoice!=="__custom__"?w.workspaceChoice:null,currentWorkspacePath:w.resolvedWorkspacePath});w.openLaunchConfirm({title:`Launch ${C.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:y,selectedWorkspaceKey:F,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const P=y.find(E=>E.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(P),v(C.type,{workspacePath:(P==null?void 0:P.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:C.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath||"Use selected workspace"})]},C.type)):(w.activeLauncherKind==="cli"?n:a).map(C=>s.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const y=w.activeLauncherKind==="cli"?"cli":"acp",{options:F,selectedKey:P}=ks({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspaceId:w.workspaceChoice!=="__custom__"?w.workspaceChoice:null,currentWorkspacePath:w.resolvedWorkspacePath});w.openLaunchConfirm({title:`Launch ${C.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${y.toUpperCase()}`,workspaceOptions:F,selectedWorkspaceKey:P,details:[{label:"Mode",value:y.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:y==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const E=F.find(G=>G.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(E),I(y,C.type,{workspaceId:(E==null?void 0:E.workspaceId)??null,workspacePath:(E==null?void 0:E.workspacePath)??null,args:w.launchConfirmArgs,model:w.launchConfirmModel,resumeSessionId:w.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[C.icon?`${C.icon} `:"",C.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath||"Use selected workspace"})]},C.type))})]}),c.message&&s.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${c.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[c.message,w.canCreateMissingWorkspace&&s.jsx("div",{className:"mt-2",children:s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>f(w.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),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:g,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",l]}),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:p,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"})]})]})]})]}),w.browseDialogOpen&&s.jsx(ea,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:w.browseCurrentPath,directories:w.browseDirectories,busy:w.browseBusy,error:w.browseError,confirmLabel:"Use this folder",onClose:()=>w.setBrowseDialogOpen(!1),onNavigate:C=>{w.loadBrowsePath(C)},onConfirm:C=>{w.chooseCustomWorkspacePath(C),w.setBrowseDialogOpen(!1)}}),w.launchConfirm&&s.jsx(li,{title:w.launchConfirm.title,description:w.launchConfirm.description,details:w.launchConfirm.details,workspaceOptions:w.launchConfirm.workspaceOptions,selectedWorkspaceKey:w.launchConfirmWorkspaceKey,onWorkspaceChange:w.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:w.launchConfirm.providerType?Pn(!!w.launchConfirmResumeId):w.launchConfirm.confirmLabel,busyLabel:w.launchConfirm.providerType?void 0:w.launchConfirm.busyLabel,busy:w.launchConfirmBusy,showArgsInput:w.launchConfirm.showArgsInput,argsValue:w.launchConfirmArgs,onArgsChange:w.setLaunchConfirmArgs,showModelInput:w.launchConfirm.showModelInput,modelValue:w.launchConfirmModel,onModelChange:w.setLaunchConfirmModel,historyProviderNode:w.launchConfirm.providerType&&(w.launchConfirmSessionsLoading||w.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"}),w.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:Jo()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:w.launchConfirmTextFilter,onChange:C=>w.setLaunchConfirmTextFilter(C.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:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:w.launchConfirmWorkspaceFilter,onChange:C=>w.setLaunchConfirmWorkspaceFilter(C.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:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:w.launchConfirmModelFilter,onChange:C=>w.setLaunchConfirmModelFilter(C.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:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),s.jsxs("select",{value:w.launchConfirmSortMode,onChange:C=>w.setLaunchConfirmSortMode(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.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:w.launchConfirmResumableOnly,onChange:C=>w.setLaunchConfirmResumableOnly(C.target.checked),disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:w.launchConfirmResumeId,onChange:C=>w.setLaunchConfirmResumeId(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Mx()}),w.filteredLaunchConfirmSavedSessions.map(C=>s.jsxs("option",{value:C.providerSessionId,disabled:!C.canResume,children:[C.title||C.providerSessionId," ",C.canResume?"":"(workspace missing)"]},C.providerSessionId))]}),!w.launchConfirmSessionsLoading&&w.launchConfirmSavedSessions.length>0&&w.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),w.launchConfirmResumeId&&(()=>{const C=w.filteredLaunchConfirmSavedSessions.find(F=>F.providerSessionId===w.launchConfirmResumeId);if(!C)return null;const y=eu(C);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:y.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:y.providerSessionId}),s.jsx("div",{className:"mt-1",children:y.metaLine}),y.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:y.updatedLabel}),y.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:y.preview})]})})()]}),onConfirm:w.handleConfirmLaunch,onCancel:w.closeLaunchConfirm}),u&&s.jsx(Zd,{section:m,onSectionChange:x})]})}function yn(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function ny(e,t=[]){const r=new Map(e.map(a=>[a.conversation.tabKey,a])),n=t.map(a=>r.get(a)).filter(a=>!!a);return n.length===e.length?n:yn(e)}function ay(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 oy(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:Cs(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 l;const a=_r(n)?"cli":Fs(n)?"acp":"ide",o=Cs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((l=n.activeChat)==null?void 0:l.title)||(_r(n)?n.cliName||n.type:Fs(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Fs(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 iy(e,t){const r=new Map;for(const n of t){const a=_s(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((h,x)=>x.timestamp-h.timestamp)[0]||null,l=(o==null?void 0:o.conversation)||null,c=io(n),d=a.filter(h=>h.unread||h.requiresAction).length,m=ay(n),u=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:At(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:d,total:a.length,latestConversation:l,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:c,preview:l?mx(l):"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,l=a.latestTimestamp||a.fallbackActivityAt||0;return l!==o?l-o:n.label.localeCompare(a.label)})}function ly(e){return e==="chat"}function nn(e,t){var r;if(!(typeof window>"u"))try{if(!(!!((r=import.meta.env)!=null&&r.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,t)}catch{}}function cy({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:l,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:x,onRequestedMobileSectionConsumed:S,setSelectedTabKey:b,setScreen:p,setSelectedMachineId:g,setSection:v,setMachineBackTarget:f,resetMachineAction:T}){const I=i.useRef(null),k=i.useCallback(A=>{if(!(A!=null&&A.sessionId))return;const _=Tn(A,l),N=Math.max(Date.now(),js(A),_.lastUpdated||0);nn("mark_read:start",{tabKey:A.tabKey,sessionId:A.sessionId,displayPrimary:ut(A),inboxBucket:_.inboxBucket,unread:_.unread,lastSeenAt:_.lastSeenAt,lastUpdated:_.lastUpdated,activityAt:js(A),readAt:N}),c(_s(A)||A.routeId,"mark_session_seen",{sessionId:A.sessionId,providerSessionId:A.providerSessionId,seenAt:N,completionMarker:_.completionMarker}).then(w=>{nn("mark_read:result",{tabKey:A.tabKey,sessionId:A.sessionId,result:w})}).catch(w=>{nn("mark_read:error",{tabKey:A.tabKey,sessionId:A.sessionId,error:w instanceof Error?w.message:String(w)})})},[l,c]);return i.useEffect(()=>{var _;if(!n){ly(o)&&p("inbox"),b(((_=e[0])==null?void 0:_.tabKey)||null),I.current=null;return}if(o!=="chat"){I.current=null;return}const A=`${n.tabKey}:${n.sessionId||""}`;I.current!==A&&(I.current=A,k(n))},[e,k,o,n,p,b]),i.useEffect(()=>{if(!d)return;const A=e.find(_=>_.tabKey===d);A&&(b(A.tabKey),p("chat"),m==null||m())},[e,m,d,p,b]),i.useEffect(()=>{if(!u)return;const A=t.find(_=>_.id===u);A&&(g(A.id),T(),v("machines"),f("inbox"),p("machine"),h==null||h())},[t,h,u,T,f,p,v,g]),i.useEffect(()=>{x&&(v(x),p("inbox"),S==null||S())},[S,x,p,v]),i.useEffect(()=>{const A=r.filter(_=>_.inboxBucket==="task_complete"||_.unread);A.length!==0&&nn("inbox_state",{screen:o,selectedTabKey:a,items:A.map(_=>{const N=Tn(_.conversation,l);return{liveState:N,tabKey:_.conversation.tabKey,sessionId:_.conversation.sessionId,displayPrimary:ut(_.conversation),serverBucket:N.inboxBucket,computedBucket:_.inboxBucket,serverUnread:N.unread,computedUnread:_.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:js(_.conversation)}})})},[r,l,o,a]),{markConversationRead:k}}function dy(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function jl(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function uy(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function my({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,o]=i.useState("idle"),[l,c]=i.useState(""),[d,m]=i.useState(null),u=i.useCallback(()=>{o("idle"),c(""),m(null)},[]),h=i.useCallback(async(f,T,I)=>{var k;try{o("loading"),c(`Launching ${T}…`);const A={ideType:T,enableCdp:!0};(k=I==null?void 0:I.workspacePath)!=null&&k.trim()&&(A.workspace=I.workspacePath.trim()),await e(f,"launch_ide",A),o("done"),c(`${T} launch requested`)}catch(A){o("error"),c(A instanceof Error?A.message:"Launch IDE failed"),console.error("Launch IDE failed",A)}},[e]),x=i.useCallback(async(f,T,I)=>{if(T.trim())try{o("loading"),c(I!=null&&I.createIfMissing?"Creating folder…":"Saving workspace…");const k=await e(f,"workspace_add",{path:T.trim(),createIfMissing:(I==null?void 0:I.createIfMissing)===!0});if(k!=null&&k.success){o("done"),c(I!=null&&I.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}o("error"),c((k==null?void 0:k.error)||"Could not save workspace")}catch(k){o("error"),c(k instanceof Error?k.message:"Could not save workspace")}},[e]),S=i.useCallback(async f=>{var T,I,k,A,_,N;try{o("loading"),c("Starting daemon upgrade…");const w=await e(f,"daemon_upgrade",{});if((T=w==null?void 0:w.result)!=null&&T.alreadyLatest){o("done"),c(`Already on v${((I=w==null?void 0:w.result)==null?void 0:I.version)||"latest"}.`);return}if((k=w==null?void 0:w.result)!=null&&k.upgraded||(A=w==null?void 0:w.result)!=null&&A.success){o("done"),c(`Upgrade to v${((_=w==null?void 0:w.result)==null?void 0:_.version)||"latest"} started. Daemon is restarting…`);return}o("error"),c(((N=w==null?void 0:w.result)==null?void 0:N.error)||"Upgrade failed")}catch(w){o("error"),c(w instanceof Error?w.message:"Upgrade failed")}},[e]),b=i.useCallback(async(f,T,I,k)=>{var N,w,D;const A=Date.now(),_={machineId:f,kind:T,providerType:I,workspaceId:(k==null?void 0:k.workspaceId)||null,workspacePath:(k==null?void 0:k.workspacePath)||null,resumeSessionId:(k==null?void 0:k.resumeSessionId)||null,startedAt:A};try{o("loading"),c(`Launching ${I}…`),m(_);const M={cliType:I};(N=k==null?void 0:k.workspacePath)!=null&&N.trim()?M.dir=k.workspacePath.trim():k!=null&&k.workspaceId&&(M.workspaceId=k.workspaceId),k!=null&&k.resumeSessionId&&(M.resumeSessionId=k.resumeSessionId),(w=k==null?void 0:k.args)!=null&&w.trim()&&(M.cliArgs=k.args.trim().split(/\s+/).filter(Boolean)),(D=k==null?void 0:k.model)!=null&&D.trim()&&(M.initialModel=k.model.trim());const j=await e(f,"launch_cli",M),W=(j==null?void 0:j.result)||j,H=(W==null?void 0:W.sessionId)||(W==null?void 0:W.id);if(j!=null&&j.success&&H){m(null),o("done"),c(`${I} launched`),t(Zt(H));return}if(j!=null&&j.success){o("loading"),c(`${I} launch requested — waiting for session…`);return}m(null),o("error"),c((j==null?void 0:j.error)||(W==null?void 0:W.error)||`Could not launch ${T.toUpperCase()} workspace`)}catch(M){if(uy(M)){o("loading"),c(`${I} launch requested — waiting for session…`);return}m(null),o("error"),c(M instanceof Error?M.message:`Could not launch ${T.toUpperCase()} workspace`)}},[t,e]),p=i.useCallback(async(f,T)=>{try{const I=await e(f,"list_saved_sessions",{providerType:T,kind:"cli",limit:30}),k=(I==null?void 0:I.result)??I;return Array.isArray(k==null?void 0:k.sessions)?k.sessions:[]}catch(I){return console.error("Failed to list saved sessions on mobile:",I),[]}},[e]),g=i.useCallback(async(f,T)=>Zn(e,f,T),[e]);i.useEffect(()=>{if(!d)return;const f=jl(d.workspacePath),T=r.find(k=>{var M,j,W,H;if(!k||k.type==="adhdev-daemon"||dy(k.daemonId||k.id)!==d.machineId||(k.transport==="acp"?"acp":k.transport==="pty"?"cli":null)!==d.kind||String(k.agentType||k.type||"")!==d.providerType)return!1;const w=String(k.providerSessionId||"");if(d.resumeSessionId&&w)return w===d.resumeSessionId;if(f){const $=jl(k.workspace||k.runtimeWorkspaceLabel);return $?$===f:!1}return Number(k.lastUpdated||k._lastUpdate||k.timestamp||((H=(W=(j=(M=k.activeChat)==null?void 0:M.messages)==null?void 0:j.at)==null?void 0:W.call(j,-1))==null?void 0:H.timestamp)||0)>=d.startedAt-5e3});if(!T)return;const I=Yd({entrySessionId:T.sessionId,entryInstanceId:T.instanceId,entryRouteId:T.id,conversations:n});I&&(m(null),o("done"),c(`${d.providerType} launched`),t(Zt(I)))},[n,r,t,d]),i.useEffect(()=>{if(!d)return;const f=window.setTimeout(()=>{m(T=>!T||T.startedAt!==d.startedAt?T:(o("error"),c("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(f)},[d]);const v=i.useCallback(async(f,T)=>{if(T.kind==="ide"&&T.providerType){await h(f,T.providerType,{workspacePath:T.workspace||null});return}(T.kind==="cli"||T.kind==="acp")&&T.providerType&&await b(f,T.kind,T.providerType,{workspacePath:T.workspace||null,resumeSessionId:T.providerSessionId||null})},[h,b]);return{machineAction:{state:a,message:l},resetMachineAction:u,handleLaunchDetectedIde:h,handleAddWorkspace:x,handleMachineUpgrade:S,handleLaunchWorkspaceProvider:b,handleListSavedSessions:p,handleBrowseDirectory:g,handleOpenRecent:v}}function py({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:l,setSelectedMachineId:c,setSection:d,setMachineBackTarget:m}){const u=i.useCallback(v=>{o(v.tabKey),l("chat"),n(v)},[n,l,o]),h=i.useCallback(v=>{const f=e.find(T=>T.routeId===v.routeId&&T.streamSource==="native");f&&(o(f.tabKey),l("chat"),n(f))},[e,n,l,o]),x=i.useCallback(()=>{n(t),l("inbox")},[n,t,l]),S=i.useCallback((v,f="inbox")=>{c(v),a(),d("machines"),m(f),l("machine")},[a,m,l,d,c]),b=i.useCallback(v=>{const f=_s(v);f&&S(f,"chat")},[S]),p=i.useCallback(()=>{a(),l(r)},[r,a,l]),g=i.useCallback(v=>{d(v),l("inbox")},[l,d]);return{openConversation:u,openNativeConversation:h,backFromConversation:x,openMachine:S,openConversationMachine:b,backFromMachine:p,changeMachineSection:g}}function Ts(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function hy(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function fy({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:l,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:x,onRequestedMobileSectionConsumed:S,onOpenHistory:b,onOpenRemote:p,onStopCli:g,wsStatus:v,isConnected:f,onShowAllHiddenConversations:T,onHideConversation:I,onOpenMeshGraph:k,onOpenNewSession:A,liveSessionInboxState:_,setCliViewModeOverrides:N}){const[w,D]=i.useState(()=>{var q;return((q=e[0])==null?void 0:q.tabKey)||null}),[M,j]=i.useState(()=>e[0]?"chat":"inbox"),[W,H]=i.useState("chats"),[$,C]=i.useState(null),[y,F]=i.useState("inbox"),P=i.useRef([]),E=As(),G="0.9.81",J=i.useMemo(()=>e.find(q=>q.tabKey===w)||e[0]||null,[e,w]),ye=i.useMemo(()=>J?r.find(q=>q.id===J.routeId):void 0,[r,J]),he=i.useMemo(()=>!J||st(J)||!at(J)?null:Zs(J),[J]),ne=i.useMemo(()=>r.filter(q=>q.type==="adhdev-daemon").sort(Fo),[r]),ue=i.useMemo(()=>ne.find(q=>q.id===$)||null,[ne,$]),Se=qn({sendDaemonCommand:a,activeConv:J||void 0,setActionLogs:o,isStandalone:l}),ve=my({sendDaemonCommand:a,navigate:E,ides:r,conversations:e}),X=i.useMemo(()=>e.map(q=>{const ce=M==="chat"&&(J==null?void 0:J.tabKey)===q.tabKey,Ne=zn(q,_,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ce}),je=js(q),O=id(q);return{conversation:q,timestamp:je,preview:O,unread:Ne.unread,requiresAction:Ne.requiresAction,isWorking:Ne.isWorking,inboxBucket:Ne.inboxBucket}}),[e,_,M,J]),{markConversationRead:xe}=cy({conversations:e,machineEntries:ne,items:X,selectedConversation:J,selectedTabKey:w,screen:M,liveSessionInboxState:_,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:x,onRequestedMobileSectionConsumed:S,setSelectedTabKey:D,setScreen:j,setSelectedMachineId:C,setSection:H,setMachineBackTarget:F,resetMachineAction:ve.resetMachineAction}),fe=py({conversations:e,selectedConversation:J,machineBackTarget:y,markConversationRead:xe,resetMachineAction:ve.resetMachineAction,setSelectedTabKey:D,setScreen:j,setSelectedMachineId:C,setSection:H,setMachineBackTarget:F}),we=i.useMemo(()=>yn(X.filter(q=>q.requiresAction)),[X]),be=i.useMemo(()=>yn(X.filter(q=>q.unread&&!q.requiresAction)),[X]),Ce=i.useMemo(()=>ny(X.filter(q=>!q.unread&&!q.requiresAction&&q.isWorking),P.current),[X]);i.useEffect(()=>{P.current=Ce.map(q=>q.conversation.tabKey)},[Ce]);const ee=i.useMemo(()=>yn(X.filter(q=>!q.unread&&!q.requiresAction&&!q.isWorking)),[X]),me=i.useMemo(()=>ue?X.filter(q=>_s(q.conversation)===ue.id):[],[X,ue]),ie=i.useMemo(()=>oy(ue,r),[r,ue]),pe=(ue==null?void 0:ue.version)||null,le=!!ue&&!!pe&&!0&&pe!==G,B=i.useMemo(()=>(ue==null?void 0:ue.availableProviders)||[],[ue]),z=i.useMemo(()=>B.filter(q=>Ts(q,"cli")).map(q=>({type:q.type,displayName:q.displayName||q.type,icon:q.icon})),[B]),de=i.useMemo(()=>B.filter(q=>Ts(q,"acp")).map(q=>({type:q.type,displayName:q.displayName||q.type,icon:q.icon})),[B]),re=i.useMemo(()=>iy(ne,X),[X,ne]),R=i.useCallback(async q=>{ue&&await ve.handleOpenRecent(ue.id,q)},[ve,ue]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&J?s.jsx(qg,{selectedConversation:J,isAcp:st(J),isStandalone:l,selectedIdeEntry:ye,actionLogs:n,userName:c,isSendingChat:Se.isSendingChat,sendFeedbackMessage:Se.sendFeedbackMessage,isFocusingAgent:Se.isFocusingAgent,handleModalButton:Se.handleModalButton,handleRelaunch:Se.handleRelaunch,onBack:fe.backFromConversation,onOpenNativeConversation:fe.openNativeConversation,onOpenMachine:fe.openConversationMachine,onOpenHistory:b,onOpenRemote:p,onOpenMeshGraph:k,onStopCli:g,cliViewMode:he,onSetCliViewMode:async q=>{await Dd({conversation:J,mode:q,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:N})},handleSendChat:Se.handleSendChat,handleFocusAgent:Se.handleFocusAgent}):M==="machine"&&ue?s.jsx(ry,{selectedMachineEntry:ue,selectedMachineConversations:me,selectedMachineRecentLaunches:ie,cliProviders:z,acpProviders:de,selectedMachineNeedsUpgrade:le,appVersion:G,machineAction:ve.machineAction,isStandalone:l,section:W,showBottomNav:y==="inbox",onBack:fe.backFromMachine,onSectionChange:fe.changeMachineSection,onOpenConversation:fe.openConversation,onOpenRecent:R,onOpenMachineDetails:()=>E(`/machines/${ue.id}`),onMachineUpgrade:()=>ve.handleMachineUpgrade(ue.id),onLaunchDetectedIde:(q,ce)=>ve.handleLaunchDetectedIde(ue.id,q,ce),onAddWorkspace:(q,ce)=>ve.handleAddWorkspace(ue.id,q,ce),onBrowseDirectory:q=>ve.handleBrowseDirectory(ue.id,q),onLaunchWorkspaceProvider:(q,ce,Ne)=>ve.handleLaunchWorkspaceProvider(ue.id,q,ce,Ne),onListSavedSessions:q=>ve.handleListSavedSessions(ue.id,q)}):s.jsx(Jg,{section:W,attentionItems:we,unreadItems:be,workingItems:Ce,completedItems:ee,hiddenConversations:t,machineCards:re,getAvatarText:hy,actionLogs:n,sendDaemonCommand:a,onOpenConversation:fe.openConversation,onShowAllHidden:T,onHideConversation:I,onOpenMeshGraph:k,onOpenNewSession:A,onOpenMachine:fe.openMachine,onOpenSettings:()=>E("/settings"),onSectionChange:H,wsStatus:v,isConnected:f,isStandalone:l})})}function Ma(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function xy({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const l=i.useRef(0),[c,d]=i.useState(!1),[m,u]=i.useState(null),h=i.useCallback(()=>{l.current=0,d(!1),u(null)},[]);i.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const x=i.useCallback(g=>{g.dataTransfer.types.includes("text/tab-key")&&(l.current+=1,d(!0))},[]),S=i.useCallback(g=>{if(!g.dataTransfer.types.includes("text/tab-key"))return;if(g.preventDefault(),!Ma(t,r)){u("merge");return}const v=g.currentTarget.getBoundingClientRect(),f=g.clientX-v.left,T=v.width/3;f<T?u("split-left"):f>T*2?u("split-right"):u("merge")},[t,r]),b=i.useCallback(()=>{l.current-=1,!(l.current>0)&&(l.current=0,d(!1),u(null))},[]),p=i.useCallback(g=>{l.current=0,d(!1);const v=g.dataTransfer.getData("text/tab-key"),f=v?e.some(I=>I.tabKey===v):!1,T=m;if(u(null),o(),!!v){if(g.preventDefault(),T==="split-left"&&Ma(t,r)){r==null||r(v,"split-left");return}if(T==="split-right"&&Ma(t,r)){r==null||r(v,"split-right");return}if(f){a(v);return}n==null||n(v)}},[e,m,t,r,n,a,o]);return{dragOver:c,dropAction:m,resetDragState:h,handleDragEnter:x,handleDragOver:S,handleDragLeave:b,handleDrop:p}}function by(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 gy({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,l]=i.useState(t??null),[c,d]=i.useState(r??[]),[m,u]=i.useState(null),h=i.useRef(null),x=i.useRef(null),S=i.useRef(n),b=i.useRef(a);i.useEffect(()=>{S.current=n},[n]),i.useEffect(()=>{b.current=a},[a]),i.useEffect(()=>{t&&t!==o&&l(t)},[t,o]),i.useEffect(()=>{d(_=>{const N=by(_,e);return N.length===_.length&&N.every((w,D)=>w===_[D])?_:N})},[e]);const p=i.useMemo(()=>{const _=m??c;if(_.length===0)return e;const N=new Map(_.map((w,D)=>[w,D]));return[...e].sort((w,D)=>{const M=N.get(w.tabKey)??999,j=N.get(D.tabKey)??999;return M-j})},[e,m,c]);i.useEffect(()=>{var N,w;if(p.length===0){o!==null&&(l(null),(N=S.current)==null||N.call(S,null));return}if(o&&p.some(D=>D.tabKey===o))return;const _=p[0].tabKey;_!==o&&(l(_),(w=S.current)==null||w.call(S,_))},[p,o]);const g=i.useMemo(()=>p.find(_=>_.tabKey===o),[p,o]),v=i.useCallback(_=>{var N;l(_),(N=S.current)==null||N.call(S,_)},[]),f=i.useCallback((_,N,w)=>{d(D=>{var H;const M=D.filter($=>$!==_),j=M.indexOf(N);if(j<0)return D;const W=w==="left"?j:j+1;return M.splice(W,0,_),(H=b.current)==null||H.call(b,M),M}),u(null)},[]),T=i.useCallback((_,N,w)=>{const M=(c.length>0?c:e.map(H=>H.tabKey)).filter(H=>H!==_),j=M.indexOf(N);if(j<0)return;const W=w==="left"?j:j+1;M.splice(W,0,_),h.current=M,u(M)},[c,e]),I=i.useCallback(()=>{var N;const _=h.current;_&&(d(_),(N=b.current)==null||N.call(b,_))},[]),k=i.useCallback(()=>{h.current=null,u(null)},[]),A=i.useCallback(_=>{d(N=>{var D;const w=N.filter(M=>M!==_);return w.push(_),(D=b.current)==null||D.call(b,w),w})},[]);return{activeTabId:o,activeConv:g,sortedConversations:p,previewOrderRef:h,draggingTabRef:x,selectTab:v,handleTabReorder:f,updatePreviewOrder:T,commitPreviewOrder:I,clearPreviewOrder:k,moveTabToEnd:A,setDraggingTabKey:_=>{x.current=_}}}function yy({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 ci({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 l=!r&&!n,c=n&&!!o,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",m=n?ud:r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:d}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children: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:zt,"aria-label":zt,children:[s.jsx(jc,{size:14}),s.jsx("span",{children:zt})]})}),l&&s.jsx(Qd,{}),l&&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 su="adhdev-tab-shortcuts";function ru(){try{return JSON.parse(localStorage.getItem(su)||"{}")}catch{return{}}}function nu({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,l]=i.useState(()=>ru()),[c,d]=i.useState(null),m=i.useCallback(h=>{const x=[];return h.metaKey&&x.push(a?"⌘":"Meta"),h.ctrlKey&&x.push("Ctrl"),h.altKey&&x.push(a?"⌥":"Alt"),h.shiftKey&&x.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(x.push(h.key.length===1?h.key.toUpperCase():h.key),x.join("+"))},[a]),u=i.useCallback(h=>{l(h);try{localStorage.setItem(su,JSON.stringify(h))}catch{}},[]);return i.useEffect(()=>{if(!e||!c)return;const h=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){d(null);return}const S=m(x);if(!S)return;const b={...o};for(const[p,g]of Object.entries(b))g===S&&delete b[p];b[c]=S,u(b),d(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,c,o,u,m]),i.useEffect(()=>{if(!e)return;const h=x=>{if(!(!x.ctrlKey&&!x.metaKey&&!x.altKey)){for(const[S,b]of Object.entries(o))if(t.includes(S)&&m(x)===b){x.preventDefault(),r(),n(S);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,o,t,r,n,m]),{isMac:a,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const Aa=e=>{e.preventDefault()},vy=i.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:l,draggingTabRef:c,onFocus:d,onSelectTab:m,onConversationActivated:u,onPreviewReorder:h,onReorderTab:x,onCommitPreviewOrder:S,onClearPreviewOrder:b,onDragStateReset:p,onDragTabKeyChange:g,onReceiveTab:v,onOpenContextMenu:f,longPressTimer:T,isGroupActive:I}){const k=Qs(t),A=k.isGenerating?"agent-tab-generating":k.isWaiting?"agent-tab-waiting":"",_=k.isReconnecting,N=i.useCallback(y=>{c.current=t.tabKey,g(t.tabKey),y.dataTransfer.setData("text/tab-key",t.tabKey),y.dataTransfer.effectAllowed="move"},[t.tabKey,c,g]),w=i.useCallback(()=>{c.current=null,g(null),S(),b(),p()},[c,g,S,b,p]),D=i.useCallback(y=>{const F=c.current;if(!(!F||F===t.tabKey)&&y.dataTransfer.types.includes("text/tab-key")){y.preventDefault(),y.stopPropagation();const P=y.currentTarget.getBoundingClientRect(),E=y.clientX<P.left+P.width/2?"left":"right";h(F,t.tabKey,E)}},[t.tabKey,c,h]),M=i.useCallback(y=>{y.preventDefault(),y.stopPropagation();const F=y.dataTransfer.getData("text/tab-key");if(F&&F!==t.tabKey){const P=y.currentTarget.getBoundingClientRect(),E=y.clientX<P.left+P.width/2?"left":"right";l.includes(F)?x(F,t.tabKey,E):v&&v(F)}b()},[t.tabKey,l,x,v,b]),j=i.useCallback(y=>{y.stopPropagation(),d(),m(t.tabKey),u(t)},[t,u,d,m]),W=i.useCallback(y=>{y.preventDefault(),f(y.clientX,y.clientY,t.tabKey)},[t.tabKey,f]),H=i.useCallback(y=>{const F=y.touches[0];T.current=setTimeout(()=>{f(F.clientX,F.clientY,t.tabKey)},600)},[t.tabKey,T,f]),$=i.useCallback(()=>{T.current&&clearTimeout(T.current)},[T]),C=["adhdev-dockview-tab",A,r&&"is-active",I&&"is-group-active",_&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:C,draggable:!0,onDragStart:N,onDragEnd:w,onDragOver:D,onDrop:M,onClick:j,onContextMenu:W,onTouchStart:H,onTouchEnd:$,onTouchMove:$,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:k.isGenerating?s.jsx("div",{className:"tab-spinner"}):k.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):_?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):k.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:ut(t),children:ut(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[_?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:bs(t)}):k.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[bs(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:bs(t)}),s.jsx(qs,{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 wy({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:l,onConversationActivated:c,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:h,onDragStateReset:x,onDragTabKeyChange:S,onReceiveTab:b,onHideTab:p,isGroupActive:g,allowTabShortcuts:v=!0}){const[f,T]=i.useState(null),I=i.useRef(null),k=i.useRef(null),A=i.useMemo(()=>e.map(W=>W.tabKey),[e]);Pr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(f==null?void 0:f.tabKey)||null});const{isMac:_,tabShortcuts:N,shortcutListening:w,setShortcutListening:D,saveShortcuts:M}=nu({enabled:v,sortedTabKeys:e.map(W=>W.tabKey),onFocus:o,onSelectTab:l});i.useEffect(()=>{if(!f)return;const W=H=>{const $=document.querySelector("[data-pane-context-menu]");$&&$.contains(H.target)||T(null)};return window.addEventListener("mousedown",W,!0),()=>window.removeEventListener("mousedown",W,!0)},[f]),i.useEffect(()=>{const W=k.current;if(!W)return;const H=$=>{Math.abs($.deltaY)<=Math.abs($.deltaX)||($.preventDefault(),W.scrollLeft+=$.deltaY)};return W.addEventListener("wheel",H,{passive:!1}),()=>W.removeEventListener("wheel",H)},[]);const j=i.useCallback((W,H,$)=>{T({x:W,y:H,tabKey:$})},[]);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(W=>s.jsx(vy,{conv:W,isActive:t===W.tabKey,isDraggedTab:a.current===W.tabKey,isTaskCompleteUnread:n.has(W.tabKey),shortcut:v?N[W.tabKey]:void 0,conversationKeys:A,draggingTabRef:a,onFocus:o,onSelectTab:l,onConversationActivated:c,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:h,onDragStateReset:x,onDragTabKeyChange:S,onReceiveTab:b,onOpenContextMenu:j,longPressTimer:I,isGroupActive:g},W.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),f&&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:f.x,top:f.y},children:[v&&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:Aa,onClick:W=>{W.stopPropagation(),D(f.tabKey),T(null)},children:["⌨ ",N[f.tabKey]?`Change shortcut (${N[f.tabKey]})`:"Set shortcut"]}),N[f.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:Aa,onClick:()=>{const W={...N};delete W[f.tabKey],M(W),T(null)},children:"✕ Remove shortcut"})]}),p&&s.jsxs(s.Fragment,{children:[v&&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:Aa,onClick:()=>{p(f.tabKey),T(null)},children:"🚫 Hide from Dashboard"})]})]}),v&&w&&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:W=>W.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. ",_?"⌘+1":"Ctrl+1",", ",_?"⌥+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 jy({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:l,hasRegisteredMachines:c,userName:d,groupIndex:m,onFocus:u,isSplitMode:h,numGroups:x,onMoveTab:S,onReceiveTab:b,style:p,onActiveTabChange:g,initialActiveTabId:v,initialTabOrder:f,onTabOrderChange:T,onHideTab:I,isFocused:k,allowTabShortcuts:A=!0,onOpenNewSession:_,liveSessionInboxState:N}){const{sendCommand:w}=jt(),D=i.useRef(null),{activeTabId:M,activeConv:j,sortedConversations:W,draggingTabRef:H,selectTab:$,handleTabReorder:C,updatePreviewOrder:y,commitPreviewOrder:F,clearPreviewOrder:P,moveTabToEnd:E,setDraggingTabKey:G}=gy({conversations:e,initialActiveTabId:v,initialTabOrder:f,onActiveTabChange:g,onTabOrderChange:T}),J=qn({sendDaemonCommand:a,activeConv:j,setActionLogs:o,isStandalone:l}),{dragOver:ye,dropAction:he,resetDragState:ne,handleDragEnter:ue,handleDragOver:Se,handleDragLeave:ve,handleDrop:X}=xy({conversations:e,numGroups:x,onMoveTab:S,onReceiveTab:b,onOwnTabDrop:E,onClearPreviewOrder:P}),xe=j&&!st(j)&&Zs(j)==="terminal",fe=i.useMemo(()=>j?t.find(ee=>ee.id===j.routeId):void 0,[t,j]),we=i.useMemo(()=>j?n.filter(ee=>ee.routeId===j.tabKey):[],[n,j]),be=i.useMemo(()=>new Set(W.filter(ee=>Zp(ee,N,{isOpenConversation:ee.tabKey===M})).map(ee=>ee.tabKey)),[M,N,W]);Pr("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:M,dragOver:ye});const Ce=i.useCallback(ee=>{ee.streamSource==="agent-stream"&&ee.agentType&&w(ee.routeId,Gc(),{agentType:ee.agentType,...ee.sessionId&&{targetSessionId:ee.sessionId}}).catch(()=>{})},[w]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...p,outline:ye?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(wy,{conversations:W,activeTabId:M,groupIndex:m,numGroups:x,unreadTabKeys:be,draggingTabRef:H,onFocus:u,onSelectTab:$,onConversationActivated:Ce,onPreviewReorder:y,onReorderTab:C,onCommitPreviewOrder:F,onClearPreviewOrder:P,onDragStateReset:ne,onDragTabKeyChange:G,onMoveTab:S,onReceiveTab:b,onHideTab:I,isGroupActive:k??!1,allowTabShortcuts:A}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ue,onDragOver:Se,onDragLeave:ve,onDrop:X,children:[ye&&s.jsx(yy,{dropAction:he,canSplit:!!(x<4&&S)}),j?s.jsx(ii,{activeConv:j,clearToken:r[j.tabKey]||0,isCliTerminal:!!xe,ideEntry:fe,terminalRef:D,handleModalButton:J.handleModalButton,handleRelaunch:J.handleRelaunch,handleSendChat:J.handleSendChat,isSendingChat:J.isSendingChat,sendFeedbackMessage:J.sendFeedbackMessage,handleFocusAgent:J.handleFocusAgent,isFocusingAgent:J.isFocusingAgent,actionLogs:we,userName:d,isInputActive:!h||!!k}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(ci,{conversationsCount:e.length,isSplitMode:h,isStandalone:l,hasRegisteredMachines:c,onOpenNewSession:_})})]})]})}function ky({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:l,actionLogs:c,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:h,userName:x,focusedGroup:S,focusGroup:b,moveTabToGroup:p,splitTabRelative:g,closeGroup:v,handleResizeStart:f,groupActiveTabIds:T,setGroupActiveTab:I,groupTabOrders:k,setGroupTabOrder:A,toggleHiddenTab:_,onOpenNewSession:N,allowTabShortcuts:w=!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((M,j)=>{const W=t&&n.length===r?`${n[j]}%`:void 0;return s.jsxs(Nt.Fragment,{children:[t&&j>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:H=>f(j-1,H),onDoubleClick:()=>v(j),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(jy,{style:t?{flexBasis:W??`${100/r}%`,flexGrow:W?0:1,flexShrink:W?0:1}:void 0,conversations:M,clearedTabs:o,ides:l,actionLogs:c,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:h,userName:x,groupIndex:j,isFocused:t&&S===j,onFocus:()=>b(j),isSplitMode:t,numGroups:r,onMoveTab:(H,$)=>{$==="left"&&j>0?p(H,j-1):$==="right"&&j<r-1?p(H,j+1):$==="split-left"&&r<4?g(H,j,"left"):$==="split-right"&&r<4&&g(H,j,"right")},onReceiveTab:H=>p(H,j),onActiveTabChange:H=>I(j,H),initialActiveTabId:T[j],initialTabOrder:k[j],onTabOrderChange:H=>A(j,H),onHideTab:_,onOpenNewSession:N,allowTabShortcuts:w,liveSessionInboxState:D})]},j)})})}function au({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=i.useState(null),[l,c]=i.useState(null);i.useEffect(()=>e?mt.onScreenshot("ide-page",(u,h)=>{if(u!==e)return;const x=new FileReader;x.onload=()=>o(x.result),x.readAsDataURL(h)}):void 0,[e]),i.useEffect(()=>{r!=="connected"&&o(null)},[r]),i.useEffect(()=>{var u;return e?((u=mt.onStatus)==null?void 0:u.call(mt,(h,x)=>{h===e&&x!=null&&x.screenshotUsage&&c(x.screenshotUsage)}))||(()=>{}):void 0},[e]),i.useEffect(()=>{o(null)},[e,t]),i.useEffect(()=>{const m=e?mt.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 d=i.useCallback(async(m,u)=>{const h=e?mt.get(e):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(m,u,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:l,handleRemoteAction:d}}const ou="adhdev-dashboard-action-shortcuts",Sy=1200,Ny=[["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 Cy(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function lt(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function iu(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:lt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:lt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:lt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:lt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:lt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:lt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:lt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:lt("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:lt("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:lt("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:lt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:lt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:lt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:lt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:lt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:lt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:lt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:lt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:lt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:lt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:lt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:lt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:lt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:lt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:lt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:lt("toggleCliView",e)}]}function wo(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function On(e){const t=Object.fromEntries(iu(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(ou)||"{}"),n={...t,...r};for(const[a,o]of Ny)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function lu(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Iy({enabled:e=!0,onTrigger:t}){const r=Cy(),[n,a]=i.useState(()=>On(r)),[o,l]=i.useState(null),[c,d]=i.useState([]),m=i.useRef({parts:[],timer:null}),u=i.useCallback(p=>{const g=[];return p.metaKey&&g.push(r?"⌘":"Meta"),p.ctrlKey&&g.push("Ctrl"),p.altKey&&g.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&g.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(g.push(lu(p.key)),g.join("+"))},[r]),h=i.useCallback(p=>{a(p);try{localStorage.setItem(ou,JSON.stringify(p))}catch{}},[]);i.useEffect(()=>{const p=On(r),g=Object.entries(n),v=Object.entries(p);g.length===v.length&&g.every(([f,T])=>p[f]===T)||h(p)},[n,r,h]);const x=i.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),S=i.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},Sy))},[]);i.useEffect(()=>{if(!o)return;const p=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){l(null),d([]);return}const v=u(g);if(!v)return;const T=!(g.metaKey||g.ctrlKey||g.altKey)&&/^[A-Z0-9]$/.test(v);if(c.length===0&&T){d([v]);return}const k=[...c,v].slice(0,2).join(" "),A={...n};for(const[_,N]of Object.entries(A))N===k&&delete A[_];A[o]=k,h(A),l(null),d([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,u,h,o,c]),i.useEffect(()=>{if(!e||o)return;const p=g=>{if(g.defaultPrevented)return;const v=u(g);if(!v)return;const f=g.metaKey||g.ctrlKey||g.altKey;if(wo(g.target))return;const T=m.current.parts,I=f?[v]:[...T.slice(-1),v].slice(-2),k=I.join(" "),A=I[I.length-1],_=Object.entries(n).filter(([,j])=>!!j),N=_.find(([,j])=>j===k);if(N){g.preventDefault(),x(),t(N[0]);return}if(_.some(([,j])=>j.startsWith(`${k} `))){g.preventDefault(),m.current.parts=I,S();return}const D=_.find(([,j])=>j===A);if(D){g.preventDefault(),x(),t(D[0]);return}if(_.some(([,j])=>j.startsWith(`${A} `))){g.preventDefault(),m.current.parts=[A],S();return}x()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,S,e,u,t,x,o]),i.useEffect(()=>()=>x(),[x]);const b=i.useMemo(()=>iu(r),[r]);return{isMac:r,actionDefinitions:b,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:l,setShortcutListeningDraft:d,saveShortcuts:h}}function Ty({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 cu(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function kl({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!cu(n):!0}function My({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:cu(r)}const du=1e3,Ay=4;function Sl(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Nl(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function _y({detachDelayMs:e=du,stillnessThresholdPx:t=Ay,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,l=null,c=null,d=null,m=null,u=!1;const h=()=>{m!=null&&(a(m),m=null)},x=()=>{h(),c=null},S=()=>{h(),o=null,l=null,c=null,d=null,u=!1},b=()=>{!o||!c||!d||u||m!=null||(m=n(()=>{m=null,!(!o||!c||!d||u)&&Sl(d,l)&&(Nl(c,d,t)||(u=!0,r({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},p=v=>{if(!(!o||u)){if(!Sl(v,l)){d={clientX:v.clientX,clientY:v.clientY},x();return}(!c||Nl(c,v,t))&&(h(),c={clientX:v.clientX,clientY:v.clientY}),d={clientX:v.clientX,clientY:v.clientY},b()}},g=v=>{!o||u||(v&&(d={clientX:v.clientX,clientY:v.clientY}),x())};return{startDrag:v=>{h(),o=v.panelId,l=v.selfPanelBounds??null,c=null,d={clientX:v.clientX,clientY:v.clientY},u=!1},markSelfPanel:p,markNonSelfPanel:g,markNoDropTarget:g,markDockTarget:g,endDrag:S,isDragging:()=>o!=null,hasDetached:()=>u,dispose:S}}function Ly(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function an(e){return e.isActive}function Cl(e){return e.isVisible}const uu=i.createContext(null);function ta(){const e=i.useContext(uu);if(!e)throw new Error("DashboardDockviewContext missing");return e}function vn(e){return ut(e)||e.tabKey}function Ry(e){return`remote:${e}`}function Bt(e){return e.startsWith("remote:")}function Il(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Py(e){e.preventDefault()}function _a(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 La(e,t){e.classList.remove(eo.className,to.className),e.classList.add(t==="light"?eo.className:to.className)}function Tl(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 Dy(e){const[,t]=i.useState(0);i.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 Ey(e,t,r){var l;const n=[t];let a;for(const c of n){let d;for(const m of c){const u=e.addPanel({id:m.tabKey,component:"conversation",title:vn(m),params:{kind:"conversation",tabKey:m.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});d||(d=u.id)}a=d??a}return r??((l=t[0])==null?void 0:l.tabKey)??null}function Ml(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])Bt(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!==vn(a)&&o.api.setTitle(vn(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:vn(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 Al(e,t,r){var d,m;const n=r?Ry(r):null;for(const u of[...e.panels])Bt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=Wt(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),l=dd(a);if(o){o.title!==l&&o.api.setTitle(l);return}const c=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((m=e.panels.find(u=>!Bt(u.id)))==null?void 0:m.id);e.addPanel({id:n,component:"remote",title:l,params:{kind:"remote",routeId:r},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function $y({params:e,api:t}){var S;const r=ta(),n=i.useRef(null),[a,o]=i.useState(()=>an(t)),[l,c]=i.useState(()=>Cl(t)),d=r.conversationsByTabKey.get(e.tabKey),m=qn({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});i.useEffect(()=>{o(an(t)),c(Cl(t));const b=[t.onDidActiveChange(p=>o(p.isActive)),t.onDidActiveGroupChange(p=>{if(!an(t)&&!p.isActive){o(!1);return}o(an(t))}),t.onDidVisibilityChange(p=>c(p.isVisible))];return()=>{for(const p of b)p.dispose()}},[t]);const u=i.useMemo(()=>d?r.ides.find(b=>b.id===d.routeId):void 0,[r.ides,d]),h=i.useMemo(()=>d?r.actionLogs.filter(b=>b.routeId===d.tabKey):[],[r.actionLogs,d]);if(!d)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(ci,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const x=!st(d)&&Zs(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(ii,{activeConv:d,clearToken:r.clearedTabs[d.tabKey]||0,isCliTerminal:x,ideEntry:u,terminalRef:n,handleModalButton:m.handleModalButton,handleRelaunch:m.handleRelaunch,handleSendChat:m.handleSendChat,isSendingChat:m.isSendingChat,handleFocusAgent:m.handleFocusAgent,isFocusingAgent:m.isFocusingAgent,actionLogs:h,userName:r.userName,scrollToBottomRequestNonce:((S=r.scrollToBottomRequest)==null?void 0:S.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:l})})}function By({params:e}){var d;const t=ta(),r=i.useMemo(()=>Wt([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=i.useMemo(()=>t.ides.find(m=>m.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((d=r==null?void 0:r.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:l,handleRemoteAction:c}=au({doId:a,targetSessionId:r?Vc(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(Ac,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:o,screenshotUsage:l,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 Oy(){const e=ta();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(ci,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function Fy(e){var S,b;Dy(e);const t=ta(),r=i.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=Wt([...t.conversationsByTabKey.values()],e.params.routeId),g=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,v=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${g?" is-active":""}${v?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(p==null?void 0:p.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:p!=null&&p.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:p.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const n=t.conversationsByTabKey.get(e.params.tabKey);if(!n)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 a=((b=e.api.group.activePanel)==null?void 0:b.id)===e.api.id,o=e.api.isGroupActive,l=zn(n,t.liveSessionInboxState,{isOpenConversation:a}),c=l.isReconnecting,d=l.isConnecting,m=l.isGenerating,u=l.isWaiting,h=l.unread,x=t.tabShortcuts[n.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${o?" is-group-active":""}${c?" is-reconnecting":""}`,title:ut(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:p=>{var g;p.preventDefault(),r(p),t.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((g=p.target)==null?void 0:g.ownerDocument)??document})},children:[h&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:m?s.jsx("div",{className:"tab-spinner"}):u?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):c?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):d?s.jsx("div",{className:"tab-connecting-spinner"}):n.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:ut(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:c?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:bs(n)}):d?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:bs(n)}):s.jsx("span",{children:bs(n)})})]}),x&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:x,children:x})]})}function Wy({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:l,hasRegisteredMachines:c,initialDataLoaded:d,userName:m,toggleHiddenTab:u,actionShortcuts:h,registerActionHandlers:x,onActiveTabChange:S,onOpenNewSession:b,onRequestScrollToBottom:p,requestedActiveTabKey:g,requestedRemoteIdeId:v,onRequestedActiveTabConsumed:f,scrollToBottomRequest:T,liveSessionInboxState:I,layoutProfile:k}){var tt,Ge,ot;const{theme:A}=er(),{sendCommand:_}=jt(),N=i.useRef(null),w=i.useRef(null),D=i.useRef(null),M=i.useRef(!1),j=i.useRef(!1),W=i.useRef(!1),H=i.useRef(null),$=i.useRef([]),[C,y]=i.useState(null),[F,P]=i.useState(0),E=i.useRef(typeof window>"u"?{}:og(k)),G=i.useMemo(()=>new Map(e.map(U=>[U.tabKey,U])),[e]),J=i.useMemo(()=>{const U=N.current;return U?U.groups.some(V=>{try{const Z=V.model.location.type;return Z!=="floating"&&Z!=="popout"?!1:V.panels.some(ae=>G.has(ae.id))}catch{return!1}}):!1},[G,F,e]),ye=i.useCallback(()=>{var U;(U=N.current)==null||U.focus()},[]),he=i.useCallback((U,V)=>{p==null||p(U,V)},[p]),ne=i.useCallback(U=>{const V=document,Z=U.document;for(const oe of V.querySelectorAll('link[rel="stylesheet"]')){const ke=Z.createElement("link");ke.rel="stylesheet",ke.href=oe.href,oe.crossOrigin&&(ke.crossOrigin=oe.crossOrigin),Z.head.appendChild(ke)}for(const oe of V.querySelectorAll("style")){const ke=Z.createElement("style");ke.textContent=oe.textContent,Z.head.appendChild(ke)}const ae=[];for(const oe of V.styleSheets)try{for(const ke of oe.cssRules)ke instanceof CSSStyleRule&&(ke.selectorText===":root"||ke.selectorText==="html")&&ae.push(ke.cssText)}catch{}if(ae.length>0){const oe=Z.createElement("style");oe.textContent=ae.join(`
|
|
54
|
-
`),Z.head.appendChild(oe)}const K=V.documentElement.getAttribute("data-theme");K&&Z.documentElement.setAttribute("data-theme",K),Z.documentElement.style.colorScheme=K==="light"?"light":"dark",Z.body.className=V.body.className;const Y=V.documentElement.getAttribute("style");Y&&Z.documentElement.setAttribute("style",Y);const se=Z.getElementById("dv-popout-window");se instanceof HTMLElement&&(se.classList.add("adhdev-dockview"),La(se,A))},[A]),ue=i.useCallback(()=>{var V;const U=N.current;if(U)for(const Z of U.groups)try{const ae=(V=Z.element)==null?void 0:V.ownerDocument;if(!ae||ae===document)continue;const K=ae.getElementById("dv-popout-window");K instanceof HTMLElement&&(K.classList.add("adhdev-dockview"),La(K,A));const Y=document.documentElement.getAttribute("data-theme");Y&&ae.documentElement.setAttribute("data-theme",Y),ae.documentElement.style.colorScheme=Y==="light"?"light":"dark",ae.body.className=document.body.className;const se=document.documentElement.getAttribute("style");se?ae.documentElement.setAttribute("style",se):ae.documentElement.removeAttribute("style")}catch{}},[A]),Se=i.useCallback(U=>{const V=N.current;if(!V)return;const Z=V.getPanel(U);Z&&V.addPopoutGroup(Z,{popoutUrl:"/popout.html",onDidOpen:({window:ae})=>{ne(ae),me();const K=G.get(U);ae.document.title=K?`${ut(K)} — ADHDev`:"ADHDev — Popout"}})},[G,ne]),ve=i.useCallback(U=>{const V=N.current,Z=V==null?void 0:V.getPanel(U);if(!V||!Z)return;const ae=V.groups.filter(K=>{var Y;try{return((Y=K.element)==null?void 0:Y.ownerDocument)===document}catch{return!0}});ae.length>0?Z.api.moveTo({group:ae[0],position:"center"}):Z.api.moveTo({position:"center"}),Z.api.setActive()},[]),X=i.useCallback(U=>{var ae;const V=N.current;if(!V)return!1;const Z=V.getPanel(U);if(!Z)return!1;try{return((ae=Z.group.element)==null?void 0:ae.ownerDocument)!==document}catch{return!1}},[]),xe=i.useCallback(U=>{X(U)&&ve(U),u(U)},[X,ve,u]),fe=i.useCallback(U=>{const V=N.current,Z=V==null?void 0:V.getPanel(U);!V||!Z||V.addFloatingGroup(Z,{width:600,height:500})},[]),we=i.useCallback(U=>{var Z;const V=(Z=N.current)==null?void 0:Z.getPanel(U);if(!V)return!1;try{return V.group.model.location.type==="floating"}catch{return!1}},[]),be=i.useCallback(()=>{var V,Z;const U=(Z=(V=N.current)==null?void 0:V.activePanel)==null?void 0:Z.id;return!U||Bt(U)?null:G.has(U)?U:null},[G]),Ce=i.useCallback(U=>{const V=N.current,Z=V==null?void 0:V.getPanel(U);if(!V||!Z)return;const ae=V.groups.filter(K=>{try{return K.model.location.type==="grid"}catch{return!0}});ae.length>0?Z.api.moveTo({group:ae[0],position:"center"}):Z.api.moveTo({position:"center"}),Z.api.setActive()},[]),ee=i.useCallback(()=>{var Y;const U=N.current;if(!U)return;const Z=U.groups.filter(se=>{var oe;try{return((oe=se.element)==null?void 0:oe.ownerDocument)===document&&se.model.location.type==="grid"}catch{return!1}})[0]||null,ae=[...U.panels];for(const se of ae){const oe=(Y=se.group.element)==null?void 0:Y.ownerDocument,ke=se.group.model.location.type;oe===document&&ke==="grid"||(Z&&Z.id!==se.group.id?se.api.moveTo({group:Z,position:"center"}):se.api.moveTo({position:"center"}))}const K=U.activePanel;K&&(K.group.model.openPanel(K),K.api.setActive()),_a(document)},[]),me=i.useCallback(()=>{var V,Z;const U=N.current;if(U)for(const ae of U.groups){const K=(V=ae.element)==null?void 0:V.ownerDocument;if(!K||K===document)continue;const Y=K.getElementById("dv-popout-window");if(!(Y instanceof HTMLElement))continue;let se=null,oe=K.title||"ADHDev",ke="Popout workspace";const Pe=ae.activePanel;if(Pe)if(se=Pe.id,Bt(Pe.id)){const Me=((Z=Pe.params)==null?void 0:Z.routeId)||Pe.id.slice(7),Qe=Wt([...G.values()],Me);oe=
|
|
53
|
+
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:w,onCancel:()=>u(null)})]})}const pb=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function hb(){const{preference:e,setPreference:t}=er();return s.jsx("div",{className:"flex gap-2",children:pb.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 fb(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 xb(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function va(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function ll(e){const{r:t,g:r,b:n}=xb(e);return .2126*va(t)+.7152*va(r)+.0722*va(n)}function cl(e,t){const r=ll(e),n=ll(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function Cd(e){const t=fb(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return cl(t,r)>=cl(t,n)?r:n}const xo={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},bo={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},bb=[{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"}}}],Id="adhdev-chat-theme",Td="adhdev-chat-theme-custom";function bn(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Id)||"ember"}catch{return"ember"}}function Ft(e){try{const t=localStorage.getItem(Td);if(t){const r=JSON.parse(t);return{...e==="dark"?xo:bo,...r[e]}}}catch{}return e==="dark"?xo:bo}function Zr(e,t){try{localStorage.setItem(Td,JSON.stringify({dark:e,light:t}))}catch{}}function Rt(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 $n(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 gb={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=gb[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",$n(r,24)),n.style.setProperty("--accent-on-primary",Cd(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${$n(r,18)})`),n.style.setProperty("--border-accent",Rt(r,.35)),n.style.setProperty("--nav-active-bg",Rt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Rt(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",Rt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Rt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Rt(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",Rt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Rt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",$n(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Cd(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${$n(e.accentColor,40)})`),t.style.setProperty("--border-accent",Rt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Rt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Rt(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 ${Rt(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 si(){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 yb(e){try{localStorage.setItem(Id,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ws()?"dark":"light";vs(Ft(t))}else si(),Nr(e,ws()?"dark":"light")}function vb(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=bn();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ws()?"dark":"light";vs(Ft(t))}else si(),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 It({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 ur({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 wb({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=i.useState(()=>Ft(r));i.useEffect(()=>{a(Ft(r))},[r]);const o=i.useCallback((l,c)=>{a(d=>{const m={...d,[l]:c},h=Ft(r==="dark"?"light":"dark");return r==="dark"?Zr(m,h):Zr(h,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(ur,{title:"App Background",children:[s.jsx(It,{label:"Background",value:n.bgPrimary,onChange:l=>o("bgPrimary",l)}),s.jsx(It,{label:"Surface",value:n.bgSecondary,onChange:l=>o("bgSecondary",l)}),s.jsx(It,{label:"Card",value:n.surfacePrimary,onChange:l=>o("surfacePrimary",l)})]}),s.jsxs(ur,{title:"App Text",children:[s.jsx(It,{label:"Primary",value:n.textPrimary,onChange:l=>o("textPrimary",l)}),s.jsx(It,{label:"Secondary",value:n.textSecondary,onChange:l=>o("textSecondary",l)}),s.jsx(It,{label:"Muted",value:n.textMuted,onChange:l=>o("textMuted",l)})]}),s.jsxs(ur,{title:"Borders & Accent",children:[s.jsx(It,{label:"Border subtle",value:n.borderSubtle,onChange:l=>o("borderSubtle",l)}),s.jsx(It,{label:"Border default",value:n.borderDefault,onChange:l=>o("borderDefault",l)}),s.jsx(It,{label:"Accent",value:n.accentColor,onChange:l=>o("accentColor",l)})]})]}),s.jsxs("div",{children:[s.jsxs(ur,{title:"Chat Bubbles",children:[s.jsx(It,{label:"User bubble",value:n.userBubble,onChange:l=>o("userBubble",l)}),s.jsx(It,{label:"User text",value:n.userText,onChange:l=>o("userText",l)}),s.jsx(It,{label:"Agent bubble",value:n.assistantBubble,onChange:l=>o("assistantBubble",l)}),s.jsx(It,{label:"Agent text",value:n.assistantText,onChange:l=>o("assistantText",l)})]}),s.jsxs(ur,{title:"Chat Layout",children:[s.jsx(It,{label:"Chat BG",value:n.containerBg,onChange:l=>o("containerBg",l)}),s.jsx(It,{label:"Send button",value:n.sendButton,onChange:l=>o("sendButton",l)}),s.jsx(It,{label:"Input border",value:n.inputBorder,onChange:l=>o("inputBorder",l)}),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:l=>o("bubbleRadius",Number(l.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 l=e?xo:bo,d=Ft(e?"light":"dark");e?Zr(l,d):Zr(d,l),a(l),vs(l),t(l)},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 jb(){const[e,t]=i.useState(bn),[r,n]=i.useState(!0),[a,o]=i.useState(()=>Ft("dark"));i.useEffect(()=>{n(ws());const d=new MutationObserver(()=>{const h=ws();n(h);const x=bn();x==="custom"?vs(Ft(h?"dark":"light")):Nr(x,h?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const h=ws();n(h);const x=bn();x==="custom"?vs(Ft(h?"dark":"light")):Nr(x,h?"dark":"light")};return m.addEventListener("change",u),()=>{d.disconnect(),m.removeEventListener("change",u)}},[]),i.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?vs(Ft(r?"dark":"light")):(si(),Nr(e,r?"dark":"light"))},[e,r]),i.useEffect(()=>{o(Ft(r?"dark":"light"))},[r]);const l=d=>{t(d),yb(d)},c=[...bb,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:c.map(d=>{const m=e===d.id,u=r?d.preview.dark:d.preview.light,h=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>l(d.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:u.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"Hello! How can I help?"}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.userBubble,color:h},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[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:d.id==="custom"?"🎨 Custom":d.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:d.description})]})]})]},d.id)})}),e==="custom"&&s.jsx(wb,{dark:r,onColorsChange:d=>o(d)})]})}const ri="adhdev_mobileDashboardMode_v1",go="adhdev:mobile-dashboard-mode-change";function ni(){try{return localStorage.getItem(ri)==="workspace"?"workspace":"chat"}catch{return"chat"}}function kb(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??ni())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==ri||t()};return window.addEventListener(go,r),window.addEventListener("storage",n),()=>{window.removeEventListener(go,r),window.removeEventListener("storage",n)}}function Sb(e){try{localStorage.setItem(ri,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(go,{detail:e}))}function Nb(){const[e,t]=i.useState(!0);return i.useEffect(()=>{t(ni()==="chat")},[]),s.jsx(hs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(es,{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),Sb(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const wa=new Map,dl=new Map;function Cb(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 Ib(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 Md(){const{sendCommand:e}=jt(),{injectEntries:t,getIdes:r}=Mr();return i.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??kf,l=dl.get(n)||0;if(!(a!=null&&a.force)&&l>0&&Date.now()-l<o)return;const c=wa.get(n);if(c)return c;const d=(async()=>{const m=await e(n,"get_machine_runtime_stats"),u=Cb(m);if(!u)return;const h=r().find(S=>S.id===n),x=Ib(h,n,u.machine,u.timestamp||Date.now());t([x]),dl.set(n,Date.now())})().finally(()=>{wa.delete(n)});return wa.set(n,d),d},[r,t,e])}function Tb(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 Mb(e,t){const{sendData:r}=jt(),{injectEntries:n,getIdes:a}=Mr(),o=Array.from(new Set(e.filter(Boolean))).join("|");i.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const l=o?o.split("|"):[];if(l.length===0)return;const c=l.map(d=>Qt.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const h=a().find(S=>S.id===d),x=Tb(h,d,u);n([x])}));return()=>{c.forEach(d=>d())}},[o,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function Ab(e,t){const{sendData:r}=jt(),[n,a]=i.useState(null),[o,l]=i.useState(!1);return i.useEffect(()=>{if(!e){a(null),l(!1);return}if(!(t!=null&&t.enabled)||!r){l(!1);return}a(null),l(!0);let c=null;const d=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),l(!1)});return d.initialSendAccepted?c=setTimeout(()=>{l(!1)},If):l(!1),()=>{c&&clearTimeout(c),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,r]),{diagnostics:n,loading:o,applyDiagnostics:a}}function _b(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Ad(e){const{sendData:t}=jt(),[r,n]=i.useState({});return i.useEffect(()=>{const a=_b(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}},l=>{n({status:l.status,modalMessage:l.modalMessage,modalButtons:l.modalButtons}),Hs.record({interactionId:l.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:l.status,modalButtonCount:Array.isArray(l.modalButtons)?l.modalButtons.length:0}})});return o.initialSendAccepted||n({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const _d="adhdev_hiddenTabs",Ld="adhdev_autoHiddenMeshTabs";function Lb(){try{const e=localStorage.getItem(_d);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function us(e){try{localStorage.setItem(_d,JSON.stringify([...e]))}catch{}}function Rb(){try{const e=localStorage.getItem(Ld);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ul(e){try{localStorage.setItem(Ld,JSON.stringify([...e]))}catch{}}function yr(e){return Go(e)}function Xn(e,t){return Ks(t).some(r=>e.has(r))}function Pb(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 Db(e,t,r=new Set){return e.filter(n=>{if(!Pb(n))return!1;const a=yr(n);return r.has(a)?!1:!Xn(t,n)})}function Eb(){const[e,t]=i.useState(Lb),[r,n]=i.useState(Rb),a=i.useCallback(x=>{const S=yr(x);t(b=>{const p=new Set(b);return p.has(S)?p.delete(S):p.add(S),us(p),p})},[]),o=i.useCallback(x=>{const S=yr(x);t(b=>{if(b.has(S))return b;const p=new Set(b);return p.add(S),us(p),p})},[]),l=i.useCallback(x=>{const S=yr(x);t(b=>{if(b.has(S))return b;const p=new Set(b);return p.add(S),us(p),p}),n(b=>{if(b.has(S))return b;const p=new Set(b);return p.add(S),ul(p),p})},[]),c=i.useCallback(x=>{const S=yr(x);t(b=>{if(!b.has(S))return b;const p=new Set(b);return p.delete(S),us(p),p}),n(b=>{if(b.has(S))return b;const p=new Set(b);return p.add(S),ul(p),p})},[]),d=i.useCallback(()=>{t(x=>{if(x.size===0)return x;const S=new Set;return us(S),S})},[]),m=i.useCallback((x,S)=>{t(b=>{const p=new Set(b);for(const g of S)p.add(g);return us(p),p})},[]),u=i.useCallback((x,S)=>{t(b=>{const p=new Set(b);for(const g of S)p.delete(g);return us(p),p})},[]),h=i.useCallback(x=>Xn(e,x),[e]);return{hiddenTabs:e,autoHiddenTabs:r,toggleTarget:a,hideTarget:o,autoHideTarget:l,showTarget:c,showAllTabs:d,hideAllForDaemon:m,showAllForDaemon:u,isHidden:h}}function Rd(e){return e instanceof Error?e.message:String(e||"")}function Pd(e){const t=Rd(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 Dd(e){const t=Rd(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Ed({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!at(e)||st(e))return;const o=Zs(e);if(o===t)return;const l=e.sessionId;l&&a(c=>({...c,[l]:t}));try{await n(_s(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Gt(e),mode:t})}catch(c){const d=Dd(c);l&&!d&&a(m=>{const u={...m};return o===$d(r,l)?delete u[l]:u[l]=o,u}),Pd(c)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",c instanceof Error?c.message:String(c)):console.error("Failed to switch CLI view mode:",c)}}function ml(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 $b(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=ml(a,t),l=Array.isArray(a.childSessions)?a.childSessions.map(d=>ml(d,t)):a.childSessions,c=l!==a.childSessions;return o!==a||c?(r=!0,{...o,...c?{childSessions:l}:{}}):a});return r?n:e}function $d(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 Bb(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))$d(t,a)===o&&(delete n[a],r=!0);return r?n:e}function Ob({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){i.useEffect(()=>{Bc()},[]);const a=i.useMemo(()=>e.map(o=>({id:o.tabKey,name:dd(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return Ch(a),i.useEffect(()=>{if(Object.keys(t).length===0)return;const l=setTimeout(()=>{r(c=>{const d=Date.now(),m={};for(const[u,h]of Object.entries(c))d-h<5e3&&(m[u]=h);return Object.keys(m).length===Object.keys(c).length?c:m})},5500);return()=>clearTimeout(l)},[t,r]),i.useEffect(()=>{const o=setInterval(()=>{const l=Date.now()-3e5;n(c=>{const d=c.filter(m=>m.timestamp>l).slice(-100);return d.length===c.length?c:d})},6e4);return()=>clearInterval(o)},[n]),null}function pl(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=pl(t==null?void 0:t.receivedAt)||pl(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function yo(e,t=0){return js(e)||e.lastUpdated||t||0}function Bd(e){return js(e)||e.lastUpdated||0}function Od(e,t,r=Bd){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 l=e.displaySecondary.localeCompare(t.displaySecondary);return l!==0?l:e.tabKey.localeCompare(t.tabKey)}function vo(e){var r;const t=yt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function Fb(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!vo(e)&&!e.title.trim()}function Wb(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(vo(r))-Number(vo(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:Od(t,r)})[0]||null}function Wt(e,t){const r=e.filter(l=>l.routeId===t);if(r.length===0)return null;const n=r.find(l=>l.streamSource==="native")||null,a=r.filter(l=>l.streamSource==="agent-stream"),o=Wb(a);return n?o&&Fb(n)?o:n:o||r[0]||null}function Kb(e){const t=String(e.daemonId||"").trim(),r=String(e.id||"").trim();return!t||r.startsWith(`${t}:`)?r:`${t}:${r}`}function Hb(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=Kb(n),o=r.get(a);if(!o){r.set(a,n);continue}const l=(o.workspace?1:0)+(o.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>l||(n.timestamp||0)>(o.timestamp||0))&&r.set(a,n)}return Array.from(r.values())}function ja(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function Ub(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 hl(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Ub(Us(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 zb(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||""),hl(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||""),hl(r.activeChat)].join(":"))].join("|")}function Vb(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 Gb(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const o of Ks({routeId:n.routeId}))r.set(o,a);for(const o of Ks({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of Ks({tabKey:n.tabKey}))r.set(o,n)}return r}function qb(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Yb(e){const t=qb(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=Us(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Xb({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=i.useMemo(()=>Hb(e),[e]),o=i.useMemo(()=>bd(e),[e]),l=i.useRef([]),c=i.useRef([]),d=i.useRef([]),m=i.useRef(new Map),u=i.useRef(new Map),h=i.useMemo(()=>{const T=new Map,k=[];for(const w of a){const{connectionState:D="new",machineName:M}=gd(w,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),j=zb(w),W=m.current.get(w.id);if(W&&W.ide===w&&W.sourceSignature===j&&W.connectionState===D&&W.machineName===M){T.set(w.id,W),k.push(...W.conversations);continue}const H=ti(w,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),$={ide:w,sourceSignature:j,connectionState:D,machineName:M,conversations:H};T.set(w.id,$),k.push(...H)}m.current=T;const A=new Map,_=w=>{const D=Yb(w),M=u.current.get(w.tabKey);if(M&&M.signature===D)return A.set(w.tabKey,M),M.timestamp;const j={signature:D,timestamp:Bd(w)||(M==null?void 0:M.timestamp)||0};return A.set(w.tabKey,j),j.timestamp},N=[...k].sort((w,D)=>Od(w,D,_));return u.current=A,N},[a,t,o]),x=i.useMemo(()=>{const T=Vb(h,r);return ja(l.current,T)?l.current:(l.current=T,T)},[h,r]),S=i.useMemo(()=>{const T=new Map,k=Array.from(new Set(x.map(A=>A.routeId)));for(const A of k){const _=Wt(x,A);_&&T.set(A,_)}return T},[x]),b=i.useMemo(()=>{const T=new Map;for(const k of x){const A=S.get(k.routeId),_=k.streamSource==="native"&&A?A:k;for(const N of Ks({providerSessionId:k.providerSessionId,sessionId:k.sessionId,tabKey:k.tabKey}))T.set(N,_)}return T},[x,S]),p=i.useMemo(()=>Gb(x,S),[x,S]),g=i.useCallback(T=>{if(T)return b.get(T)},[b]),v=i.useCallback(T=>{if(T)return p.get(T)},[p]),f=i.useMemo(()=>{const T=x.filter(k=>!Xn(n,k));return ja(c.current,T)?c.current:(c.current=T,T)},[x,n]),C=i.useMemo(()=>{const T=f.map(k=>k.tabKey);return ja(d.current,T)?d.current:(d.current=T,T)},[f]);return{chatIdes:a,conversations:x,visibleConversations:f,visibleTabKeys:C,resolveConversationBySessionId:g,resolveConversationByTarget:v}}function Jb({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=i.useMemo(()=>{var c;return e||!t?null:((c=r(t))==null?void 0:c.tabKey)??null},[e,r,t]),o=i.useMemo(()=>{var c;return!e||!t?null:((c=r(t))==null?void 0:c.tabKey)??null},[e,r,t]),l=i.useCallback(()=>{t&&n(c=>{const d=new URLSearchParams(c);return d.delete("activeTab"),d},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:l}}function Qb({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){i.useEffect(()=>{it.setIdes(e)},[e]),i.useEffect(()=>{it.setResolveAction((a,o,l)=>{t(a,o,l).catch(()=>{})})},[t]),i.useEffect(()=>{const a=it.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 l=o.duration||5e3;setTimeout(()=>r(c=>c.filter(d=>d.id!==o.id)),l)});return()=>{a()}},[r]),i.useEffect(()=>{const a=id.on("status_event",o=>{it.handleRawEvent(o,"ws")});return()=>{a()}},[]),i.useEffect(()=>{var o;const a=l=>{var p;const c=l.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const d=c.targetSessionId||c.targetKey||c.daemonId,m=n(d),u=(m==null?void 0:m.routeId)||c.daemonId;if(!u)return;const h=Number(c.buttonIndex),x=c.button||((p=m==null?void 0:m.modalButtons)==null?void 0:p[h])||"Approve",S=String(x).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),b=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(S);t(u,"resolve_action",{action:b?"approve":"reject",button:x,...Number.isFinite(h)&&{buttonIndex:h},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(g=>console.error("[SW Action] approval failed:",g))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var l;return(l=navigator.serviceWorker)==null?void 0:l.removeEventListener("message",a)}},[n,t])}const Zb="adhdev_dashboardLayout_v1",eg="adhdev_dashboardDockview_v1",tg="adhdev_dashboardDockviewHiddenRestore_v1",mr={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function ai(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function sg(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Fd(e){return`${Zb}:${e}`}function rg(e){const t=Fd(e);return ai(t,null)}function ng(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=Fd(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Wd(e){return`${eg}:${e}`}function ag(e){const t=Wd(e);return ai(t,null)}function og(e,t){try{const r=Wd(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Kd(e){return`${tg}:${e}`}function ig(e){const t=Kd(e);return ai(t,{})}function lg(e,t){try{const r=Kd(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function cg(){return{groupAssignments:[...mr.groupAssignments],focusedGroup:mr.focusedGroup,groupActiveTabIds:{...mr.groupActiveTabIds},groupTabOrders:{...mr.groupTabOrders},groupSizes:[...mr.groupSizes]}}function dg(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function ug(){const[e]=i.useState(()=>sg(typeof window<"u"?window.innerWidth:1280)),[t,r]=i.useState(()=>new Map),[n,a]=i.useState(0),[o,l]=i.useState({}),[c,d]=i.useState({}),[m,u]=i.useState([]),[h,x]=i.useState(()=>typeof window<"u"&&window.innerWidth<768),[S,b]=i.useState(!1),p=i.useCallback(()=>{if(S)return;const w=rg(e)??cg();r(new Map(w.groupAssignments)),a(w.focusedGroup),l(w.groupActiveTabIds),d(w.groupTabOrders),u(w.groupSizes),b(!0)},[S,e]);i.useEffect(()=>{S&&ng(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:c,groupSizes:m})},[S,e,t,n,o,c,m]),i.useEffect(()=>{const w=window.matchMedia("(max-width: 767px)"),D=M=>x(M.matches);return w.addEventListener("change",D),()=>w.removeEventListener("change",D)},[]);const g=i.useCallback(w=>{r(w)},[]),v=i.useCallback(w=>{a(w)},[]),f=i.useCallback(w=>{l(w)},[]),C=i.useCallback(w=>{d(w)},[]),T=i.useCallback(w=>{u(w)},[]),k=i.useCallback(w=>{v(w)},[v]),A=i.useCallback((w,D)=>{l(M=>(M[w]??null)===(D??null)?M:{...M,[w]:D})},[]),_=i.useCallback((w,D)=>{d(M=>{const j=M[w];return dg(j,D)?M:{...M,[w]:D}})},[]),N=i.useCallback((w,D)=>{const M=D.get(w)??0;return A(M,w),k(M),M},[k,A]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:g,focusedGroup:n,updateFocusedGroup:v,focusGroup:k,groupActiveTabIds:o,updateGroupActiveTabIds:f,setGroupActiveTab:A,groupTabOrders:c,updateGroupTabOrders:C,setGroupTabOrder:_,groupSizes:m,updateGroupSizes:T,isMobile:h,hasHydratedStoredLayout:S,hydrateStoredLayout:p,focusConversationTab:N}}function mg(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Vo(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function pg({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:l,setSearchParams:c,historyModalOpen:d,activeConv:m,isRefreshingHistory:u,ides:h,handleRefreshHistory:x}){const S=i.useRef(!1),b=i.useRef(!1),p=i.useRef(null),g=i.useRef(!1);i.useEffect(()=>{if(!e||S.current||t.length===0)return;if(!a){o();return}const v=r(e);v&&(l(v.tabKey,n),S.current=!0,b.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),c(f=>{const C=new URLSearchParams(f);return C.delete("activeTab"),C},{replace:!0}))},[e,t,r,n,a,o,l,c]),i.useEffect(()=>{if(!(b.current||a)&&t.length!==0){if(!e){o(),b.current=!0;return}if(S.current){b.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(b.current||a)&&(o(),b.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,o]),i.useEffect(()=>{if(!d){g.current=!1;return}if(!m||g.current||u)return;const v=h.find(f=>f.id===m.routeId);v&&(!v.chats||v.chats.length===0||mg(v.chats,m))&&(g.current=!0,x())},[d,m,u,h,x])}function ka(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=Vo(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Hd({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[l,c]=i.useState(!1),[d,m]=i.useState(!1),u=i.useCallback(async b=>{try{await e("standalone","launch_ide",{ideType:b,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),h=i.useCallback(async(b,p)=>{try{const g=b||(t==null?void 0:t.daemonId)||"",v=await e(g,"switch_chat",{id:p,sessionId:p,...xs(t)}),f=v==null?void 0:v.result;if((v==null?void 0:v.success)===!0||f==="switched"||f==="switched-by-title")return;f===!1||f==="not_found"?lr(a,"⚠️ Session tab not found — try refreshing history"):typeof f=="string"&&f.startsWith("error:")?lr(a,`⚠️ Switch error: ${f}`):lr(a,"⚠️ Session switch failed")}catch(g){console.error("Switch failed",g),lr(a,`❌ Switch failed: ${g.message||"connection error"}`)}},[t,e,a]),x=i.useCallback(async()=>{if(!(!t||l)){c(!0);try{const b=Gs(t);await e(b,"new_chat",{...xs(t)}),o(p=>({...p,[t.tabKey]:Date.now()}))}catch(b){console.error("New chat failed",b)}finally{c(!1)}}},[t,l,e,o]),S=i.useCallback(async()=>{var b,p;if(!(!t||d)){m(!0);try{const g=Gs(t),v=async()=>e(g,"list_chats",{forceExpand:!0,...xs(t)});let f=await v(),C=(f==null?void 0:f.chats)||((b=f==null?void 0:f.result)==null?void 0:b.chats);ka(C,t)&&(await new Promise(T=>setTimeout(T,450)),f=await v(),C=(f==null?void 0:f.chats)||((p=f==null?void 0:f.result)==null?void 0:p.chats)),f!=null&&f.success&&Array.isArray(C)&&(n(t.routeId,C),ka(C,t)&&!ka(r,t)&&lr(a,"⚠️ History dialog did not fully open — try once more"))}catch(g){console.error("Refresh history failed",g)}finally{m(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:h,handleNewChat:x,handleRefreshHistory:S}}function hg(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 fg(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function fl(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 en(e,t){const r=new Set(t),n=t.length>0?[0]:[];for(const[l,c]of e)!r.has(l)||c<=0||n.includes(c)||n.push(c);n.sort((l,c)=>l-c);const a={};n.forEach((l,c)=>{a[l]=c}),n.length===0&&(a[0]=0);const o=new Map;for(const[l,c]of e){if(!r.has(l)||c<=0)continue;const d=a[c];typeof d=="number"&&d>0&&o.set(l,d)}return{assignments:o,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function xl(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 xg(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 bg(e,t,r){if(t.length<=1)return[];const n=t.map(l=>e[l]).filter(l=>Number.isFinite(l)),a=n.length===t.length?n:Array(r).fill(100/r),o=a.reduce((l,c)=>l+c,0);return o>0?a.map(l=>l/o*100):Array(r).fill(100/r)}function bl(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 gl(e){return Array(e).fill(100/e)}function gg({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:l,isMobile:c,visibleConversations:d,visibleTabKeys:m}){const u=i.useRef(null),h=i.useMemo(()=>en(e,m),[e,m]),x=h.assignments,S=i.useMemo(()=>c?1:h.groupCount,[h.groupCount,c]),b=S>1,p=i.useCallback((k,A)=>{t(_=>{const N=new Map(en(_,m).assignments);return A===0?N.delete(k):N.set(k,A),N}),n(_=>({..._,[A]:k})),r(A)},[t,m,n,r]),g=i.useCallback(k=>{t(A=>{const _=en(A,m).assignments,N=new Map;for(const[w,D]of _)D!==k&&(D>k?N.set(w,D-1):N.set(w,D));return N}),l(A=>{if(A.length<=1)return[];const _=[...A];_.splice(k,1);const N=_.reduce((w,D)=>w+D,0);return N>0?_.map(w=>w/N*100):[]}),r(0)},[t,m,l,r]),v=i.useCallback((k,A)=>{A.preventDefault();const _=u.current;if(!_)return;const N=A.clientX,w=_.offsetWidth,D=o.length===S?[...o]:gl(S),M=W=>{const $=(W.clientX-N)/w*100,I=[...D];I[k]=Math.max(15,D[k]+$),I[k+1]=Math.max(15,D[k+1]-$),l(I)},j=()=>{document.removeEventListener("mousemove",M),document.removeEventListener("mouseup",j),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",M),document.addEventListener("mouseup",j)},[o,S,l]),f=i.useCallback((k,A,_)=>{if(S>=4)return;const N=_==="left"?A:A+1;t(w=>{const D=en(w,m).assignments,M=new Map;for(const j of d){const W=D.get(j.tabKey)??0,H=W>=N?W+1:W;H>0&&M.set(j.tabKey,H)}return N>0&&M.set(k,N),M}),l(w=>{const D=w.length===S?[...w]:gl(S),M=D[A]??100/S,j=Math.max(15,M/2),W=Math.max(15,M/2),H=[...D];H[A]=j,H.splice(N,0,W);const $=H.reduce((I,y)=>I+y,0);return H.map(I=>I/$*100)}),n(w=>{const D=bl(w,N);return D[N]=k,D}),a(w=>{const D=bl(w,N);return D[N]=[k],D}),r(N)},[S,t,m,d,l,n,a,r]);i.useEffect(()=>{hg(e,x)||t(x)},[e,x,t]),i.useEffect(()=>{const{mapping:k,usedGroups:A}=h;n(_=>{const N=xl(_,k);return fl(_,N)?_:N}),a(_=>{const N=xl(_,k);return fl(_,N)?_:N}),r(_=>{const N=c?0:xg(_,A,k);return _===N?_:N}),l(_=>{const N=c?[]:bg(_,A,h.groupCount);return fg(_,N)?_:N})},[h,c,n,a,r,l]);const C=i.useMemo(()=>{const k=Array.from({length:S},()=>[]);for(const A of d){const _=x.get(A.tabKey)??0,N=Math.min(_,S-1);k[N].push(A)}return k},[d,x,S]),T=i.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:x,numGroups:S,isSplitMode:b,groupedConvs:C,moveTabToGroup:p,closeGroup:g,handleResizeStart:v,splitTabRelative:f,clearAllSplits:T}}function Sa(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 yg(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 tn(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function oi(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=Sa(t.channel)||Sa(e.updateChannel)||Sa(e.releaseChannel)||void 0,n=yg(t.npmTag)||(r==="preview"?"next":r==="stable"?"latest":void 0),a=tn(t.targetVersion)||tn(e.serverVersion)||void 0,o=tn(t.minVersion)||void 0,l=tn(t.updateCommand)||(r?`adhdev update --channel ${r}`:void 0);return{...r?{channel:r}:{},...n?{npmTag:n}:{},...a?{targetVersion:a}:{},...o?{minVersion:o}:{},...l?{updateCommand:l}:{}}}function $s(e,t=null){return oi(e).targetVersion||t}function Ud(e){return oi(e).channel||null}function zd(e){const t=oi(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 vg({ides:e,sendDaemonCommand:t}){const r="0.9.81",n=i.useMemo(()=>e.filter(h=>h.type!=="adhdev-daemon"?!1:Nd(h,$s(h,r))).sort((h,x)=>Number(Sr(x,$s(x,r)))-Number(Sr(h,$s(h,r)))),[r,e]),a=i.useMemo(()=>n.some(h=>Sr(h,$s(h,r))),[r,n]),o=i.useMemo(()=>n.map(h=>$s(h,r)).find(h=>typeof h=="string"&&h.trim().length>0)||r,[r,n]),[l,c]=i.useState(!1),[d,m]=i.useState({}),u=i.useCallback(async h=>{var S,b;const x=e.find(p=>p.id===h);if(x){m(p=>({...p,[h]:"upgrading"}));try{const p=await t(h,"daemon_upgrade",zd(x));(S=p==null?void 0:p.result)!=null&&S.upgraded||(b=p==null?void 0:p.result)!=null&&b.success?m(g=>({...g,[h]:"done"})):m(g=>({...g,[h]:"error"}))}catch{m(p=>({...p,[h]:"error"}))}}},[e,t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:l,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const Vd=80;function gn(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function wg(e){return{...e,createdAt:gn(e.createdAt),updatedAt:gn(e.updatedAt,e.createdAt),lastEventAt:gn(e.lastEventAt,e.updatedAt||e.createdAt)}}function jg(e){const t=Go(e);return t==="unknown:"?e.id:t}function kg(e){return[e.type,ed(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Sg(e,t=Vd){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=jg(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 Ng(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 l=zn(a,t),c=l.inboxBucket==="needs_attention"?"needs_attention":l.inboxBucket==="task_complete"&&l.unread?"task_complete":null;if(!c)continue;const d=gn(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),m=kg({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(wg({id:m,dedupKey:m,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Uc(a),preview:ef(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return Sg(n)}function Cg(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function Ig(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=Vd}=e,a=i.useMemo(()=>Ng(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=i.useMemo(()=>Cg(a),[a]);return{notifications:a,unreadCount:o}}function Tg({notifications:e,sendDaemonCommand:t}){const r=i.useCallback(o=>{const l=e.find(d=>d.id===o),c=Math.max(Date.now(),(l==null?void 0:l.updatedAt)||0);l!=null&&l.sessionId&&t(l.machineId||l.routeId,"mark_session_seen",{sessionId:l.sessionId,seenAt:c}).catch(()=>{})},[e,t]),n=i.useCallback(o=>{const l=e.find(c=>c.id===o);l!=null&&l.sessionId&&t(l.machineId||l.routeId,"mark_notification_unread",{sessionId:l.sessionId,notificationId:l.id}).catch(()=>{})},[e,t]),a=i.useCallback(o=>{const l=e.find(c=>c.id===o);l!=null&&l.sessionId&&t(l.machineId||l.routeId,"delete_notification",{sessionId:l.sessionId,notificationId:l.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}const Mg=i.createContext(null);function Gd(){return i.useContext(Mg)}function Jn(...e){const t=new Set,r=[],n=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const l=o.toLowerCase();t.has(l)||(t.add(l),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 Ag(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 Qn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=Ag(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 _g(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 Lg(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Zn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=Lg(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,l=o.includes("\\")?"\\":"/",c=(m,u)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${u}`:m==="/"||m==="\\"?`${l}${u}`:`${m.replace(/[\\/]+$/,"")}${l}${u}`,d=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,u)=>m.name.localeCompare(u.name)):[];return{path:o,directories:d}}function Rg(e,t){const r={meshId:t.meshId||"",workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp"};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand)\s*\}\}/g,(n,a)=>r[a]||"")}function qd(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:Rg(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function Pg(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 Zt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Yd(e){return $r(e)||e.tabKey||e.routeId||null}function Xd(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 l=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(t&&l.includes(t)||r&&l.includes(r)||n&&o.routeId===n)});if(a!=null&&a.tabKey)return a.tabKey;if(n){const o=Wt(e.conversations,n)||e.conversations.find(l=>l.routeId===n);if(o!=null&&o.tabKey)return o.tabKey}return t||r||n||null}function ns(e){return String(e||"").trim()}function Jd(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Bn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Dg(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Eg(e,t){const r=ns(e.providerSessionId),n=ns(e.targetSessionId),a=t.find(o=>{const l=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(ns).filter(Boolean);return!!(r&&l.includes(r)||n&&l.includes(n))});return a?a.tabKey:n||r||null}function $g(e,t,r){if(t.event!=="agent:generating_completed")return null;const n=Jd(t.daemonId);if(n&&n!==e.machineId)return null;const a=ns(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=ns(e.resumeSessionId),l=ns(e.launchedSessionId),c=ns(t.providerSessionId),d=ns(t.targetSessionId);if(o&&o!==c&&o!==d||l&&l!==c&&l!==d)return null;const m=Bn(e.workspacePath);if(m){const u=Bn(t.workspaceName);if(u&&!Dg(u,m))return null}return Eg(t,r)}function yl(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Bg({ides:e,conversations:t,onOpenSession:r}){const[n,a]=i.useState(null),o=i.useRef(null),l=i.useCallback(()=>{o.current=null,a(null)},[]),c=i.useCallback(d=>{o.current=d,a(d)},[]);return i.useEffect(()=>{if(!n)return;const d=Bn(n.workspacePath),m=e.find(h=>{var g,v,f,C;if(!h||h.type==="adhdev-daemon"||Jd(h.daemonId||h.id)!==n.machineId||(_r(h)?"cli":Fs(h)?"acp":"ide")!==n.kind)return!1;const b=String(h.agentType||h.type||"");if(n.providerType&&b!==n.providerType)return!1;if(n.resumeSessionId)return String(h.providerSessionId||"")===n.resumeSessionId;if(n.launchedSessionId){const T=String(n.launchedSessionId||"");return[h.providerSessionId,h.sessionId,h.instanceId,h.id].map(A=>String(A||"")).filter(Boolean).includes(T)}if(d){const T=Bn(h.workspace||h.runtimeWorkspaceLabel);return T?T===d:!1}return Number(h.lastUpdated||h._lastUpdate||h.timestamp||((C=(f=(v=(g=h.activeChat)==null?void 0:g.messages)==null?void 0:v.at)==null?void 0:f.call(v,-1))==null?void 0:C.timestamp)||0)>=n.startedAt-5e3});if(!m)return;const u=Xd({entrySessionId:m.sessionId,entryInstanceId:m.instanceId,entryRouteId:m.id,conversations:t});u&&(l(),r(u))},[l,t,e,r,n]),i.useEffect(()=>it.onStatusEvent(d=>{const m=o.current;if(!m)return;const u=$g(m,d,t);u&&(l(),r(u))}),[l,t,r]),i.useEffect(()=>{if(!n)return;const d=window.setTimeout(()=>{a(m=>!m||m.startedAt!==n.startedAt?m:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[n]),{trackPendingLaunch:c}}function Og({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const l=Gd(),c=i.useCallback(async(p,g)=>Zn(e,p,g),[e]),d=i.useCallback(async(p,g)=>{if(!g.trim())return{ok:!1,error:"Choose a workspace path first."};try{const v=await e(p,"workspace_add",{path:g.trim()});return v!=null&&v.success?{ok:!0}:{ok:!1,error:(v==null?void 0:v.error)||"Could not save workspace"}}catch(v){return{ok:!1,error:v instanceof Error?v.message:"Could not save workspace"}}},[e]),m=i.useCallback(async(p,g,v)=>{var f;try{const C={ideType:g,enableCdp:!0};(f=v==null?void 0:v.workspacePath)!=null&&f.trim()&&(C.workspace=v.workspacePath.trim());const T=await e(p,"launch_ide",C);return!(T!=null&&T.success)&&(T==null?void 0:T.success)!==void 0?{ok:!1,error:(T==null?void 0:T.error)||"Could not launch IDE"}:(t({machineId:p,kind:"ide",providerType:g,workspacePath:(v==null?void 0:v.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(C){return{ok:!1,error:C instanceof Error?C.message:"Could not launch IDE"}}},[e,t]),u=i.useCallback(async(p,g,v,f)=>{var T,k,A;const C=Date.now();try{const _={cliType:v};(T=f==null?void 0:f.workspacePath)!=null&&T.trim()?_.dir=f.workspacePath.trim():f!=null&&f.workspaceId&&(_.workspaceId=f.workspaceId),(k=f==null?void 0:f.resumeSessionId)!=null&&k.trim()&&(_.resumeSessionId=f.resumeSessionId.trim()),Array.isArray(f==null?void 0:f.cliArgs)&&f.cliArgs.length>0&&(_.cliArgs=f.cliArgs),(A=f==null?void 0:f.initialModel)!=null&&A.trim()&&(_.initialModel=f.initialModel.trim());const N=await e(p,"launch_cli",_),w=(N==null?void 0:N.result)||N,D=(w==null?void 0:w.sessionId)||(w==null?void 0:w.id);return N!=null&&N.success&&D?(t({machineId:p,kind:g,providerType:v,workspacePath:(f==null?void 0:f.workspacePath)||null,resumeSessionId:(f==null?void 0:f.resumeSessionId)||null,launchedSessionId:D,startedAt:C}),{ok:!0}):N!=null&&N.success?(t({machineId:p,kind:g,providerType:v,workspacePath:(f==null?void 0:f.workspacePath)||null,resumeSessionId:(f==null?void 0:f.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:(N==null?void 0:N.error)||(w==null?void 0:w.error)||`Could not launch ${g.toUpperCase()} session`}}catch(_){return yl(_)?(t({machineId:p,kind:g,providerType:v,workspacePath:(f==null?void 0:f.workspacePath)||null,resumeSessionId:(f==null?void 0:f.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:_ instanceof Error?_.message:`Could not launch ${g.toUpperCase()} session`}}},[r,e,t]),h=i.useCallback(async p=>{var g;if(l!=null&&l.listMeshes)return l.listMeshes(p);if(!p)return[];try{const v=await e(p,"list_meshes",{}),f=(v==null?void 0:v.result)??v;if((f==null?void 0:f.success)===!1)throw new Error((f==null?void 0:f.error)||"Could not load meshes");return(Array.isArray(f==null?void 0:f.meshes)?f.meshes:Array.isArray((g=f==null?void 0:f.result)==null?void 0:g.meshes)?f.result.meshes:[]).map(T=>{var k;return{id:String((T==null?void 0:T.id)||""),name:String((T==null?void 0:T.name)||(T==null?void 0:T.id)||"Untitled mesh"),repoIdentity:(T==null?void 0:T.repoIdentity)||(T==null?void 0:T.repo_identity)||null,workspace:Array.isArray(T==null?void 0:T.nodes)&&T.nodes.length>0?String(((k=T.nodes[0])==null?void 0:k.workspace)||""):null,nodesCount:Array.isArray(T==null?void 0:T.nodes)?T.nodes.length:void 0,status:(T==null?void 0:T.status)||null}}).filter(T=>T.id)}catch(v){throw console.error("List meshes failed",v),v}},[l,e]),x=i.useCallback(async(p,g,v)=>{if(!g.trim())return{ok:!1,error:"Choose a mesh first."};if(l!=null&&l.launchMeshCoordinator)return l.launchMeshCoordinator(p,g,v);const f=Date.now();try{const C={meshId:g.trim()};v.trim()&&(C.cliType=v.trim());const T=await e(p,"launch_mesh_coordinator",C),k=(T==null?void 0:T.result)??T;if((k==null?void 0:k.success)===!1||(T==null?void 0:T.success)===!1){const _=String((k==null?void 0:k.code)||(T==null?void 0:T.code)||""),N=Pg((k==null?void 0:k.meshCoordinatorSetup)||(k==null?void 0:k.manualSetup)||(T==null?void 0:T.meshCoordinatorSetup)||(T==null?void 0:T.manualSetup));return{ok:!1,error:(k==null?void 0:k.error)||(T==null?void 0:T.error)||"Could not launch mesh coordinator",code:_||void 0,manualSetup:N}}const A=(k==null?void 0:k.sessionId)||(k==null?void 0:k.id);return A?r(A):t({machineId:p,kind:"cli",providerType:(k==null?void 0:k.cliType)||v.trim()||void 0,workspacePath:(k==null?void 0:k.workspace)||null,startedAt:f}),{ok:!0}}catch(C){return yl(C)?(t({machineId:p,kind:"cli",providerType:v.trim()||void 0,startedAt:f}),{ok:!0}):{ok:!1,error:C instanceof Error?C.message:"Could not launch mesh coordinator"}}},[l,r,e,t]),S=i.useCallback(async(p,g)=>{if(!p||!g)return[];try{const v=await e(p,"list_saved_sessions",{providerType:g,kind:"cli",limit:30}),f=(v==null?void 0:v.result)??v;return Array.isArray(f==null?void 0:f.sessions)?f.sessions:[]}catch(v){return console.error("List saved sessions failed",v),[]}},[e]),b=i.useCallback(async p=>{await Ed({conversation:n,mode:p,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:d,handleLaunchMachineIde:m,handleLaunchMachineProvider:u,handleListMachineMeshes:h,handleLaunchMeshCoordinator:x,handleListMachineSavedSessions:S,setActiveCliViewMode:b}}function Fg(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 Wg(e,t,r=Date.now()){return!e||!Fg(t)?null:{tabKey:e,nonce:r}}function Kg({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:l}){const[c,d]=i.useState(null),[m,u]=i.useState(null),h=i.useMemo(()=>{var g,v;if(!e){if(c){const f=t.find(C=>C.tabKey===c);if(f)return f}return r[0]}const p=n[a];if(p){const f=t.find(C=>C.tabKey===p);if(f)return f}return((g=o[a])==null?void 0:g[0])||((v=o[0])==null?void 0:v[0])},[t,c,a,n,o,e,r]),x=i.useCallback(p=>{d(p)},[]),S=i.useCallback(p=>{d(p.tabKey),l(g=>{const v=new URLSearchParams(g),f=sf(p);return f?v.set("activeTab",f):v.delete("activeTab"),v},{replace:!0})},[l]),b=i.useCallback((p,g)=>{const v=Wg(p,g);v&&u(v)},[]);return{activeConv:h,openDesktopConversation:S,requestScrollToBottom:b,scrollToBottomRequest:m,setDesktopActiveTab:x}}function Hg(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 Ug(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 zg({activeConv:e,isMobile:t,liveSessionInboxState:r,sendDaemonCommand:n}){const a=i.useRef(null),o=i.useRef(null),l=i.useRef(null),c=i.useRef(null),d=i.useRef(null);i.useEffect(()=>{const m=()=>{l.current&&(clearTimeout(l.current),l.current=null),c.current&&(clearTimeout(c.current),c.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const u=Tn(e,r),h=Ug({tabKey:e.tabKey,historySessionId:$r(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:js(e),liveState:u}),x=h.autoReadKey,S=Hg({autoReadKey:x,shouldMarkSeen:h.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!h.shouldMarkSeen){S.shouldCancelPending&&m(),a.current=x;return}if(!S.shouldSchedule)return;S.shouldCancelPending&&m();const b=()=>{if(document.visibilityState!=="visible"||a.current===x)return;a.current=x,o.current=null,l.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const g=h.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:g,completionMarker:h.completionMarker}).catch(()=>{})};if(o.current=S.nextPendingKey,document.visibilityState==="visible"){l.current=setTimeout(b,1500);const g=()=>{document.visibilityState!=="visible"&&l.current&&(clearTimeout(l.current),l.current=null)};d.current=g,document.addEventListener("visibilitychange",g);return}const p=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(b,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=p,document.addEventListener("visibilitychange",p)},[e,t,r,n]),i.useEffect(()=>()=>{l.current&&clearTimeout(l.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function Na(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 Vg({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:l,setClearedTabs:c,setSearchParams:d}){var y;const[m,u]=i.useState(!1),[h,x]=i.useState([]),[S,b]=i.useState(()=>Ct()),[p,g]=i.useState(!1),[v,f]=i.useState(null),C=i.useRef(null),T=i.useMemo(()=>r||t||e,[e,r,t]),k=!!T&&at(T)&&!st(T),A=i.useMemo(()=>{if(!T||!k)return null;const F=T.daemonId||T.routeId||"",P=Gt(T),E=Na(T);return`${F}:${P}:${T.providerSessionId||""}:${E}`},[T,k]),_=i.useMemo(()=>!T||!k?"":Na(T),[T,k]),{isCreatingChat:N,isRefreshingHistory:w,handleSwitchSession:D,handleNewChat:M,handleRefreshHistory:j}=Hd({sendDaemonCommand:a,activeConv:T,chats:(y=n.find(F=>F.id===(T==null?void 0:T.routeId)))==null?void 0:y.chats,updateRouteChats:o,setToasts:l,setClearedTabs:c}),W=i.useCallback(()=>{u(!0)},[]),H=i.useCallback(()=>{u(!1)},[]),$=i.useCallback(async()=>{if(!(!T||!k||p)){g(!0);try{const F=T.daemonId||T.routeId,P=Gt(T),E=Na(T),G=await a(F,"list_saved_sessions",{agentType:P,providerType:P,kind:"cli",limit:50,...T.providerSessionId?{providerSessionId:T.providerSessionId}:{},...E?{workspace:E}:{}}),J=(G==null?void 0:G.result)??G;x(Array.isArray(J==null?void 0:J.sessions)?J.sessions:[])}catch(F){console.error("Refresh saved sessions failed",F),x([])}finally{g(!1)}}},[T,p,k,a]);i.useEffect(()=>{if(!m){C.current=null;return}if(!k){C.current=null,x([]),g(!1);return}!A||p||C.current!==A&&(C.current=A,$())},[$,m,p,k,A]);const I=i.useCallback(async F=>{if(!T||!k||!F.providerSessionId||!F.workspace)return;const P=T.daemonId||T.routeId,E=Gt(T);try{f(F.providerSessionId);const G=await a(P,"launch_cli",{cliType:E,dir:F.workspace,resumeSessionId:F.providerSessionId,initialModel:Ec(F.summaryMetadata,"model",{preferShortValue:!0})||void 0}),J=(G==null?void 0:G.result)??G,ye=typeof(J==null?void 0:J.sessionId)=="string"?J.sessionId:typeof(J==null?void 0:J.id)=="string"?J.id:"";ye&&d(he=>{const ne=new URLSearchParams(he);return ne.set("activeTab",ye),ne},{replace:!0}),H()}catch(G){console.error("Resume saved session failed",G)}finally{f(null)}},[H,T,k,a,d]);return{historyModalOpen:m,openHistoryModal:W,closeHistoryModal:H,historyTargetConv:T,isSavedSessionHistoryTarget:k,isHistoryCreatingChat:N,isHistoryRefreshingHistory:w,handleHistorySwitchSession:D,handleHistoryNewChat:M,handleHistoryRefresh:j,savedHistorySessions:h,savedHistoryFilters:S,setSavedHistoryFilters:b,missingWorkspaceResumePath:_,isSavedHistoryLoading:p,resumingSavedHistorySessionId:v,handleRefreshSavedHistory:$,handleResumeSavedHistorySession:I}}function Gg({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:l,resolveConversationByTarget:c}){const[d,m]=i.useState(null),[u,h]=i.useState(null),x=i.useMemo(()=>{if(e||!n)return null;const v=c(n);return v&&!at(v)&&!st(v)?v:null},[e,n,c]),S=i.useMemo(()=>{const v=d==null?void 0:d.routeId;if(!v)return null;const f=d!=null&&d.tabKey?o.find(C=>C.tabKey===d.tabKey):a?o.find(C=>C.tabKey===a):null;return(f==null?void 0:f.routeId)===v?f:Wt(o,v)},[o,d,a]),b=i.useMemo(()=>{if(S)return l.find(v=>v.id===S.routeId)},[l,S]);i.useEffect(()=>{x&&(m({routeId:x.routeId,tabKey:Ui(x)}),h(x),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,x]);const p=i.useCallback(v=>{v&&(m({routeId:v.routeId,tabKey:Ui(v)}),h(v))},[]),g=i.useCallback(()=>{m(null),h(null)},[]);return{remoteDialogConv:S,remoteDialogIdeEntry:b,remoteDialogActiveConv:u,setRemoteDialogActiveConv:h,openRemoteDialog:p,closeRemoteDialog:g}}function qg({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:l,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:m}){const{remoteDialogConv:u,remoteDialogIdeEntry:h,remoteDialogActiveConv:x,setRemoteDialogActiveConv:S,openRemoteDialog:b,closeRemoteDialog:p}=Gg({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:l,resolveConversationByTarget:c}),[g,v]=i.useState(!1),[f,C]=i.useState(null),T=i.useCallback(async _=>{const N=_||d;!N||!at(N)&&!st(N)||(C(N),v(!0))},[d]),k=i.useCallback(()=>{v(!1),C(null)},[]),A=i.useCallback(async _=>{const N=f||d;if(!N||!at(N)&&!st(N)){k();return}v(!1);try{const w=Gt(N),D=N.routeId||N.daemonId||"";await m(D,"stop_cli",{cliType:w,targetSessionId:N.sessionId,mode:_})}catch(w){console.error("Stop CLI failed:",w)}finally{C(null)}},[d,k,f,m]);return{remoteDialogConv:u,remoteDialogIdeEntry:h,remoteDialogActiveConv:x,setRemoteDialogActiveConv:S,openRemoteDialog:b,closeRemoteDialog:p,cliStopDialogOpen:g,cliStopTargetConv:f,requestCliStop:T,cancelCliStop:k,confirmCliStop:A}}function Qd({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:o=!1}){var C,T;const l=As(),c=_s(e),d=o?null:Hc(e),m=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),u=!o&&e.streamSource==="agent-stream"&&!!e.agentName,h=!o&&!u&&(e.transport==="pty"||e.transport==="acp"),x=Vs(e),S=tf(e),b=(C=e.settings)==null?void 0:C.meshNodeFor,p=e.meshQueueStats,g=(T=e.settings)==null?void 0:T.meshCoordinatorFor;if(!m&&!u&&!h&&!d&&!b&&!p)return null;const v=i.useCallback(()=>{if(n){n();return}c&&l("/dashboard",{state:{openMachineId:c}})},[c,l,n]),f=i.useCallback(()=>{if(r){r();return}const k=Yd(e);k&&l(Zt(k))},[e,l,r]);return s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[m&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:f,title:S,children:[s.jsx(_t,{size:12}),s.jsx("span",{children:S})]}):s.jsxs("span",{className:"conversation-meta-chip",title:S,children:[s.jsx(_t,{size:12}),s.jsx("span",{children:S})]})),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[s.jsx(zs,{size:12}),s.jsx("span",{children:x})]}),h&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[s.jsx(zs,{size:12}),s.jsx("span",{children:x})]}),d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:v,title:d,children:[s.jsx(is,{size:12}),s.jsx("span",{children:d})]}):s.jsxs("span",{className:"conversation-meta-chip",title:d,children:[s.jsx(is,{size:12}),s.jsx("span",{children:d})]})),b&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(is,{size:12}),s.jsx("span",{children:"Mesh Node"})]}),g&&p&&s.jsxs("span",{className:`conversation-meta-chip ${p.pending>0?"is-active":""}`,style:p.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${p.pending} pending, ${p.assigned} assigned, ${p.completed} completed, ${p.failed} failed`,children:[s.jsx(tp,{size:12}),s.jsxs("span",{children:[p.pending," Pending"]})]})]})}function Ca(e,t=!0){return(e??!0)&&t}const ii=i.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:l,handleRelaunch:c,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u=null,handleFocusAgent:h,isFocusingAgent:x,actionLogs:S,userName:b,scrollToBottomRequestNonce:p,isInputActive:g=!0,isVisible:v=!0}){const f=n,C=!n,T=Ca(v,f),k=Ca(v,C),A=Ca(v),_=Ad(t),N=_.status||_.modalMessage||_.modalButtons?{...t,..._.status?{status:_.status}:{},..._.modalMessage!==void 0?{modalMessage:_.modalMessage}:{},..._.modalButtons!==void 0?{modalButtons:_.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Rc,{activeConv:N,onModalButton:l}),s.jsx(Qd,{conversation:N,className:"chat-pane-meta-row mx-3 mt-1",meshOnly:!0}),N.transport!=="pty"&&N.transport!=="acp"&&N.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(Ar,{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,N.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:f?"visible":"hidden",pointerEvents:f?"auto":"none"},children:s.jsx(xx,{activeConv:N,clearToken:r,terminalRef:o,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,isVisible:T,isInputActive:g&&T})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(po,{activeConv:N,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:h,isFocusingAgent:x,actionLogs:S,userName:b,scrollToBottomRequestNonce:p,isInputActive:g&&k,isVisible:k})})]}):s.jsx(po,{activeConv:N,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:h,isFocusingAgent:x,actionLogs:S,userName:b,scrollToBottomRequestNonce:p,isInputActive:g&&A,isVisible:A})]})},(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.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 Yg({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:l,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:m,onOpenNativeConversation:u,onOpenMachine:h,onOpenHistory:x,onOpenRemote:S,onOpenMeshGraph:b,onStopCli:p,cliViewMode:g,onSetCliViewMode:v,handleSendChat:f,handleFocusAgent:C,handleModalButton:T,handleRelaunch:k}){var M;const A=i.useRef(null),_=at(e)&&!t,N=_&&g==="terminal",w=!!e.daemonId&&typeof((M=e.settings)==null?void 0:M.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.length>0,D=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 ${D} 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(Ao,{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:ut(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(Qd,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>h(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[_&&g&&s.jsx(Yo,{mode:g,onChange:v,compact:!0}),_&&p&&s.jsx("button",{onClick:()=>{p(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(wt,{size:14})}),w&&b&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>b(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(as,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(e),type:"button",children:s.jsx(_o,{size:14})}),!t&&!_&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e),type:"button",children:s.jsx(_t,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(ii,{activeConv:e,clearToken:0,isCliTerminal:N,ideEntry:n,terminalRef:A,handleModalButton:T,handleRelaunch:k,handleSendChat:f,isSendingChat:l,sendFeedbackMessage:c,handleFocusAgent:C,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const Ia={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 Xg(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Zd(){const[e,t]=i.useState("unix"),[r,n]=i.useState("powershell"),[a,o]=i.useState(!1),l=e==="unix"?"unix":r;i.useEffect(()=>{t(Xg())},[]);const c=i.useCallback(()=>{navigator.clipboard.writeText(Ia[l].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[l]);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:Ia[l].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Ia[l].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 eu({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:_t},{key:"chats",label:"Chats",icon:es}];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 l=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 ${l?"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:l?{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":l,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${l?"text-accent-primary":"bg-transparent text-current"}`,style:l?{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 sn({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 Ls({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 pr({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 Jg({conversation:e,onCancel:t,onConfirm:r}){const n=ut(e),a=Is(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(wt,{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 rn({item:e,type:t,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onOpenMeshGraph:o,onCollectChatDebugBundle:l}){var D;const c=t==="needs_attention"||t==="task_complete",d=t==="working",m=t==="earlier",u=t==="task_complete",{isReconnecting:h,isConnecting:x}=Qs(e.conversation),S=ut(e.conversation),b=Is(e.conversation),p=cd(e.conversation,{requiresAction:t==="needs_attention"}),g=c?"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%)]":m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",v=c?"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":m?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",f=m?"text-text-secondary":"text-text-primary",C=m?"text-text-muted":"text-text-secondary",T=m?"text-text-secondary opacity-80":"text-text-muted",k=m?"text-text-muted opacity-80":"text-text-muted",A=!d&&!u,_=!!e.conversation.daemonId&&typeof((D=e.conversation.settings)==null?void 0:D.meshCoordinatorFor)=="string"&&e.conversation.settings.meshCoordinatorFor.length>0,N="text-[color:var(--status-warning)]",w=M=>{if(!l)return;M.preventDefault(),M.stopPropagation();const j=l==null?void 0:l(e.conversation);Promise.resolve(j).catch(W=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",W)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${g}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[c||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:c?{color:"var(--accent-on-primary)"}:void 0,children:r(S)}),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:M=>{M.preventDefault(),M.stopPropagation(),a()},"aria-label":`Hide ${S}`,title:"Hide conversation",children:[s.jsx(Lo,{size:11}),s.jsx("span",{children:"Hide"})]}),_&&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:M=>{M.preventDefault(),M.stopPropagation(),o(e.conversation)},"aria-label":`Open mesh graph for ${S}`,title:"Open live repo mesh graph",children:[s.jsx(as,{size:11}),s.jsx("span",{children:"Graph"})]})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>n(e.conversation),onContextMenu:w,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 ${f}`,children:S}),A&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${k}`,children:Lc(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${C}`,children:[s.jsx("span",{className:"truncate",children:b}),s.jsx(qs,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),h?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${N} animate-pulse`,children:"Reconnecting…"})]}):x?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):p==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:N,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${T}`,children:e.preview})]}),c&&!u&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),u&&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 vl({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 Qg({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:l,getAvatarText:c,actionLogs:d,sendDaemonCommand:m,onOpenConversation:u,onShowAllHidden:h,onHideConversation:x,onOpenMeshGraph:S,onOpenNewSession:b,onOpenMachine:p,onOpenSettings:g,onSectionChange:v,wsStatus:f="connected",isStandalone:C=!1,onCollectChatDebugBundle:T}){const[k,A]=i.useState(null),_=f==="disconnected"||f==="reconnecting"||f==="offline"||f==="auth_failed",N=l.length>0,w=t.length>0||r.length>0||n.length>0||a.length>0,D=e==="machines"?"Machines":"Chats",M=C?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",j=C?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",W=i.useCallback(async I=>{const y=Gs(I);if(!y)return;const F=Array.isArray(I.messages)?I.messages:[],P=Yc({activeConv:I,visibleMessages:F,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:F.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),E=await m(y,"get_chat_debug_bundle",{...xs(I),delivery:"daemon_file",frontendSnapshot:P}),G=Ln(E),J=Qc(G),ye=await Jc(J);ye==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),it.showToast(Xc(G,{locatorCopyStatus:ye}),ye==="failed"?"warning":"success")},[d,m]),H=T||W,$=i.useCallback(()=>{k&&(x==null||x(k),A(null))},[k,x]);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 ${M}`,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:D}),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(Hn,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:g,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(Kn,{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] ${j}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:_?s.jsx(pr,{icon:s.jsx(vl,{}),title:f==="offline"?"Network offline":f==="auth_failed"?"Session expired":"Reconnecting",subtitle:f==="offline"?"Waiting for network…":f==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):l.length===0?s.jsx(pr,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:C?"Waiting for your daemon":"Connect your machines",subtitle:C?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.",children:!C&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Zd,{})})}):s.jsx(Ls,{children:l.map((I,y)=>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] ${y>0?"border-t border-border-subtle/70":""}`,onClick:()=>p(I.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(I.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:I.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:I.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[I.unread," new"]}):I.total>0?`${I.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:I.subtitle}),I.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[I.total," chat",I.total!==1?"s":"",I.unread>0?` · ${I.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},I.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(sn,{title:"Needs attention",className:"mb-0"}),s.jsx(Ls,{children:t.map((I,y)=>s.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:s.jsx(rn,{item:I,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:x?()=>A(I.conversation):void 0,onOpenMeshGraph:S,onCollectChatDebugBundle:H})},I.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(sn,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(Ls,{children:r.map((I,y)=>s.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:s.jsx(rn,{item:I,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:x?()=>A(I.conversation):void 0,onOpenMeshGraph:S,onCollectChatDebugBundle:H})},I.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(sn,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(Ls,{children:n.map((I,y)=>s.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:s.jsx(rn,{item:I,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:x?()=>A(I.conversation):void 0,onOpenMeshGraph:S,onCollectChatDebugBundle:H})},I.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(sn,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(Ls,{children:a.map((I,y)=>s.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:s.jsx(rn,{item:I,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:x?()=>A(I.conversation):void 0,onOpenMeshGraph:S,onCollectChatDebugBundle:H})},I.conversation.tabKey))}):w?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):_?s.jsx(pr,{icon:s.jsx(vl,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):N?s.jsx(pr,{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(es,{size:20})}),title:"No conversations yet",subtitle:md,children:b&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:b,"aria-label":zt,title:zt,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:zt})]})}):s.jsx(pr,{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(Ls,{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:h,children:"Restore all"})]})})})]}),e==="chats"&&b&&w&&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:b,"aria-label":zt,title:zt,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"})]})}),k&&s.jsx(Jg,{conversation:k,onCancel:()=>A(null),onConfirm:$}),s.jsx(eu,{section:e,onSectionChange:v})]})}function Zg(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function tu(e){const t=[e.workspace||"Workspace unknown"],r=Cs(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Zg(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function ea({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:o="",confirmLabel:l="Use this folder",onClose:c,onNavigate:d,onConfirm:m}){const[u,h]=i.useState(r);i.useEffect(()=>{h(r)},[r]);const x=_g(r),S=u.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(wt,{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:()=>{!x||a||d(x)},disabled:!x||a,children:[s.jsx(Ao,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:b=>h(b.target.value),onKeyDown:b=>{b.key!=="Enter"||!S||a||(b.preventDefault(),d(S))},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:()=>{!S||a||d(S)},disabled:!S||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(b=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(b.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(Ns,{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:b.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:b.path})]})]},b.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(S||r),disabled:!S&&!r||a,children:l})]})]})})}function li({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:l="Launch",busyLabel:c="Launching…",busy:d=!1,showArgsInput:m,argsValue:u,onArgsChange:h,showModelInput:x,modelValue:S,onModelChange:b,historyProviderNode:p,onConfirm:g,onCancel:v}){const f=n==null?void 0:n.find(C=>C.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:v,"aria-label":"Close launch confirmation",children:s.jsx(wt,{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:C=>o(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:n.map(C=>s.jsx("option",{value:C.key,children:C.label},C.key))}),(f==null?void 0:f.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:f.description})]}),p,r.map(C=>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:C.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:C.value})]},`${C.label}:${C.value}`)),x&&b&&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:S||"",onChange:C=>b(C.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),m&&h&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:u||"",onChange:C=>h(C.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:v,disabled:d,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:g,disabled:d,children:[s.jsx(Po,{size:14}),d?c:l]})]})]})})}function wl(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ks(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,o=[];a&&o.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const d of t.workspaces||[])o.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${wl(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const l=(r==null?void 0:r.trim())||"",c=l?(t.workspaces||[]).find(d=>d.path===l):null;if(l&&!c&&o.push({key:`custom:${l}`,label:wl(l),description:l,workspaceId:null,workspacePath:l}),n){const d=`saved:${n}`;if(o.some(m=>m.key===d))return{options:o,selectedKey:d}}return c?{options:o,selectedKey:`saved:${c.id}`}:l?{options:o,selectedKey:`custom:${l}`}:{options:o,selectedKey:"__home__"}}function ey(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function ty(e){return[ey(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function sy(e){return e.lastLaunchedAt?Un(e.lastLaunchedAt):""}function su(e){return{metaText:ty(e),updatedLabel:sy(e)}}function Ta(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function ry({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var rt,pt,xt,vt;const l=Er(),[c,d]=i.useState(!1),m=(((rt=e.detectedIdes)==null?void 0:rt.length)||0)>0,u=i.useMemo(()=>(e.workspaces||[]).map(Te=>({id:Te.id,path:Te.path,label:Te.label})),[e]),h=e.defaultWorkspaceId||null,[x,S]=i.useState(h||((pt=u[0])==null?void 0:pt.id)||""),[b,p]=i.useState(""),[g,v]=i.useState(""),[f,C]=i.useState([]),[T,k]=i.useState(!1),[A,_]=i.useState(""),[N,w]=i.useState(!1),[D,M]=i.useState(Ta(m,t.length,r.length)),j=i.useRef(null),[W,H]=i.useState(null),$=i.useRef("__home__"),[I,y]=i.useState("__home__"),[F,P]=i.useState(""),[E,G]=i.useState(""),[J,ye]=i.useState(""),[he,ne]=i.useState([]),[ue,Se]=i.useState(()=>Ct().textQuery),[ve,X]=i.useState(()=>Ct().workspaceQuery),[xe,fe]=i.useState(()=>Ct().modelQuery),[we,be]=i.useState(()=>Ct().resumableOnly),[Ce,ee]=i.useState(()=>Ct().sortMode),[me,ie]=i.useState(!1),[pe,le]=i.useState(!1),B=i.useRef(null),z=i.useRef(null);i.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&l(e.id,{minFreshMs:3e4}).catch(()=>{})},[l,e]);const de=x==="__custom__"?b.trim():((xt=u.find(Te=>Te.id===x))==null?void 0:xt.path)||"",re=x==="__custom__"&&!!de&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),R=x!=="__custom__"&&((vt=u.find(Te=>Te.id===x))==null?void 0:vt.path)||"",q=i.useMemo(()=>(e.recentLaunches||[]).map(Te=>Te.workspace),[e]),ce=i.useCallback(async Te=>{k(!0),_("");try{const Ve=await a(Te);v(Ve.path),p(Ve.path),C(Ve.directories)}catch(Ve){_(Ve instanceof Error?Ve.message:"Could not load folder")}finally{k(!1)}},[a]),Ne=i.useCallback(()=>{var Ve;S("__custom__"),w(!0);const Te=Qn(e.platform,Jn(b.trim(),R,q,e.defaultWorkspacePath,(Ve=u.find(tt=>tt.id===h))==null?void 0:Ve.path,u.map(tt=>tt.path)));ce(Te)},[b,h,ce,q,R,e.platform,u]),je=i.useCallback(Te=>{if(Te!=null&&Te.workspaceId){S(Te.workspaceId),p("");return}if(Te!=null&&Te.workspacePath){S("__custom__"),p(Te.workspacePath);return}S(""),p("")},[]),O=i.useCallback(Te=>{if(S(Te),Te==="__custom__"){Ne();return}p("")},[Ne]),Ie=i.useCallback(Te=>{S("__custom__"),p(Te)},[]),Le=i.useCallback((Te,Ve)=>{j.current=Ve,$.current=Te.selectedWorkspaceKey||"__home__",y(Te.selectedWorkspaceKey||"__home__"),P(Te.initialArgs||""),G(Te.initialModel||""),ye(""),ne([]);const tt=Te.providerType?`${e.id}:${Te.providerType}`:null;if(Ix(z.current,tt)){const Ge=Ct();Se(Ge.textQuery),X(Ge.workspaceQuery),fe(Ge.modelQuery),be(Ge.resumableOnly),ee(Ge.sortMode)}z.current=tt,H(Te),Te.providerType&&o&&(ie(!0),o(Te.providerType).then(Ge=>ne(Ge||[])).catch(Ge=>console.warn("Failed to load saved sessions",Ge)).finally(()=>ie(!1)))},[o,e.id]),He=i.useMemo(()=>pd(he,{textQuery:ue,workspaceQuery:ve,modelQuery:xe,resumableOnly:we,sortMode:Ce}),[xe,we,he,Ce,ue,ve]);i.useEffect(()=>{J&&(He.some(Te=>Te.providerSessionId===J)||ye(""))},[He,J]);const ze=i.useCallback(()=>{j.current&&(le(!0),j.current().finally(()=>{j.current=null,le(!1),H(null)}))},[]),Xe=i.useCallback(()=>{j.current=null,H(null)},[]),Je=i.useCallback(Te=>{$.current=Te,y(Te)},[]);return i.useEffect(()=>{var Te;B.current!==e.id&&(B.current=e.id,S(h||((Te=u[0])==null?void 0:Te.id)||"__custom__"),p(""),v(""),C([]),_(""),w(!1),Se(Ct().textQuery),X(Ct().workspaceQuery),fe(Ct().modelQuery),be(Ct().resumableOnly),ee(Ct().sortMode),z.current=null,M(Ta(m,t.length,r.length)))},[r.length,t.length,h,m,e.id,u]),i.useEffect(()=>{var Te;x!=="__custom__"&&(x&&u.some(Ve=>Ve.id===x)||S(h||((Te=u[0])==null?void 0:Te.id)||"__custom__"))},[h,x,u]),i.useEffect(()=>{D==="ide"&&m||D==="cli"&&t.length>0||D==="acp"&&r.length>0||M(Ta(m,t.length,r.length))},[D,r.length,t.length,m]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:m,workspaceRows:u,defaultWorkspaceId:h,workspaceChoice:x,customWorkspacePath:b,browseCurrentPath:g,browseDirectories:f,browseBusy:T,browseError:A,browseDialogOpen:N,activeLauncherKind:D,launchConfirm:W,launchConfirmWorkspaceKeyRef:$,launchConfirmWorkspaceKey:I,launchConfirmArgs:F,launchConfirmModel:E,launchConfirmResumeId:J,launchConfirmSavedSessions:he,launchConfirmTextFilter:ue,launchConfirmWorkspaceFilter:ve,launchConfirmModelFilter:xe,launchConfirmResumableOnly:we,launchConfirmSortMode:Ce,filteredLaunchConfirmSavedSessions:He,launchConfirmSessionsLoading:me,launchConfirmBusy:pe,resolvedWorkspacePath:de,canCreateMissingWorkspace:re,openBrowseDialog:Ne,loadBrowsePath:ce,handleWorkspaceChoiceChange:O,chooseCustomWorkspacePath:Ie,setCustomWorkspacePath:p,setBrowseDialogOpen:w,setActiveLauncherKind:M,openLaunchConfirm:Le,handleConfirmLaunch:ze,closeLaunchConfirm:Xe,setWorkspaceSelectionFromOption:je,setLaunchConfirmWorkspaceKeyAndSync:Je,setLaunchConfirmArgs:P,setLaunchConfirmModel:G,setLaunchConfirmResumeId:ye,setLaunchConfirmTextFilter:Se,setLaunchConfirmWorkspaceFilter:X,setLaunchConfirmModelFilter:fe,setLaunchConfirmResumableOnly:be,setLaunchConfirmSortMode:ee}}function ny({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:l,machineAction:c,isStandalone:d,section:m,showBottomNav:u,onBack:h,onSectionChange:x,onOpenConversation:S,onOpenRecent:b,onOpenMachineDetails:p,onMachineUpgrade:g,onLaunchDetectedIde:v,onAddWorkspace:f,onBrowseDirectory:C,onLaunchWorkspaceProvider:T,onListSavedSessions:k}){const A=I=>I==="ide"?"IDE":I==="cli"?"CLI":"ACP",_=r.slice(0,4),N=t.slice(0,3),w=ry({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:c,onBrowseDirectory:C,onListSavedSessions:k}),D=i.useMemo(()=>_.map(I=>{const{metaText:y,updatedLabel:F}=su(I);return{key:`recent-launch:${I.id}`,primary:I.label,secondary:y,updatedLabel:F,onClick:()=>{const{options:P,selectedKey:E}=ks({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspacePath:I.workspace});w.openLaunchConfirm({title:I.kind==="ide"?gs("restart-ide",I.label):I.providerSessionId?Qo(I.label):gs("start-fresh",I.label),description:I.kind==="ide"?ys("restart-ide"):I.providerSessionId?Zo():ys("start-fresh"),confirmLabel:I.kind==="ide"?Ys("restart-ide"):I.providerSessionId?Pn(!0):Ys("start-fresh"),busyLabel:I.kind==="ide"?Xs("restart-ide"):I.providerSessionId?Xo(!0):Xs("start-fresh"),workspaceOptions:P,selectedWorkspaceKey:E,details:[{label:"Mode",value:A(I.kind)},...I.providerType?[{label:"Provider",value:I.providerType}]:[]]},async()=>{const G=P.find(J=>J.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(G),await b({...I,workspace:(G==null?void 0:G.workspacePath)??null})})}}}),[w,b,_]),M=i.useMemo(()=>N.map(I=>({key:`recent-chat:${I.conversation.tabKey}`,primary:ut(I.conversation),secondary:mx(I.conversation,{timestampLabel:I.timestamp?Lc(I.timestamp):null}),unread:I.unread,onClick:()=>S(I.conversation)})),[S,N]),j=w.showAllRecent?D:D.slice(0,4),W=D.length>0,H=M.length>0,$=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${$} 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:h,type:"button","aria-label":"Back",children:s.jsx(Ao,{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:At(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:[H&&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:M.map(I=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${I.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:I.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:I.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:I.secondary})]},I.key))})]}),W&&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:j.map(I=>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:I.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:I.primary}),I.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:I.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:I.secondary})]},I.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:()=>w.setShowAllRecent(I=>!I),children:w.showAllRecent?"Show fewer":`Show ${D.length-4} more`})})]}),(w.hasIdeOptions||n.length>0||a.length>0)&&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:"Start"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:s.jsxs("div",{className:"flex flex-col gap-2.5 w-full p-3.5 rounded-2xl border border-border-default/80 bg-surface-primary/90",children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),s.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),s.jsx("select",{value:w.workspaceChoice,onChange:I=>w.handleWorkspaceChoiceChange(I.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:w.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[w.workspaceRows.map(I=>s.jsxs("option",{value:I.id,children:[I.id===w.defaultWorkspaceId?"⭐ ":"",Vn(I.path,I.label)||I.path]},I.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),w.workspaceChoice==="__custom__"&&s.jsxs("div",{className:"flex flex-col gap-2.5",children:[s.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start gap-3",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(Ns,{size:17})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),s.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:w.resolvedWorkspacePath||w.browseCurrentPath||"No folder selected yet."})]})]})}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-secondary text-[12px] font-bold",onClick:w.openBrowseDialog,children:"Select workspace…"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-accent-primary/30 bg-accent-primary/10 text-text-primary text-[12px] font-bold disabled:opacity-40",onClick:()=>{w.resolvedWorkspacePath&&f(w.resolvedWorkspacePath)},disabled:!w.resolvedWorkspacePath||w.browseBusy,children:"Save as workspace"})]})]}),w.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[w.hasIdeOptions&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.activeLauncherKind==="ide"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>w.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.activeLauncherKind==="cli"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>w.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.activeLauncherKind==="acp"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>w.setActiveLauncherKind("acp"),children:"ACP"})]}),w.activeLauncherKind&&s.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[s.jsx("div",{className:"text-xs font-bold text-text-secondary",children:w.activeLauncherKind==="ide"?"Choose an IDE":w.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:w.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(I=>s.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:y,selectedKey:F}=ks({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspaceId:w.workspaceChoice!=="__custom__"?w.workspaceChoice:null,currentWorkspacePath:w.resolvedWorkspacePath});w.openLaunchConfirm({title:`Launch ${I.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:y,selectedWorkspaceKey:F,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:I.name}]},async()=>{const P=y.find(E=>E.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(P),v(I.type,{workspacePath:(P==null?void 0:P.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:I.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath||"Use selected workspace"})]},I.type)):(w.activeLauncherKind==="cli"?n:a).map(I=>s.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const y=w.activeLauncherKind==="cli"?"cli":"acp",{options:F,selectedKey:P}=ks({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspaceId:w.workspaceChoice!=="__custom__"?w.workspaceChoice:null,currentWorkspacePath:w.resolvedWorkspacePath});w.openLaunchConfirm({title:`Launch ${I.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${y.toUpperCase()}`,workspaceOptions:F,selectedWorkspaceKey:P,details:[{label:"Mode",value:y.toUpperCase()},{label:"Provider",value:I.displayName}],showArgsInput:!0,showModelInput:y==="acp",initialArgs:"",initialModel:"",providerType:I.type},async()=>{const E=F.find(G=>G.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(E),T(y,I.type,{workspaceId:(E==null?void 0:E.workspaceId)??null,workspacePath:(E==null?void 0:E.workspacePath)??null,args:w.launchConfirmArgs,model:w.launchConfirmModel,resumeSessionId:w.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[I.icon?`${I.icon} `:"",I.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath||"Use selected workspace"})]},I.type))})]}),c.message&&s.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${c.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[c.message,w.canCreateMissingWorkspace&&s.jsx("div",{className:"mt-2",children:s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>f(w.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),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:g,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",l]}),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:p,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"})]})]})]})]}),w.browseDialogOpen&&s.jsx(ea,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:w.browseCurrentPath,directories:w.browseDirectories,busy:w.browseBusy,error:w.browseError,confirmLabel:"Use this folder",onClose:()=>w.setBrowseDialogOpen(!1),onNavigate:I=>{w.loadBrowsePath(I)},onConfirm:I=>{w.chooseCustomWorkspacePath(I),w.setBrowseDialogOpen(!1)}}),w.launchConfirm&&s.jsx(li,{title:w.launchConfirm.title,description:w.launchConfirm.description,details:w.launchConfirm.details,workspaceOptions:w.launchConfirm.workspaceOptions,selectedWorkspaceKey:w.launchConfirmWorkspaceKey,onWorkspaceChange:w.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:w.launchConfirm.providerType?Pn(!!w.launchConfirmResumeId):w.launchConfirm.confirmLabel,busyLabel:w.launchConfirm.providerType?void 0:w.launchConfirm.busyLabel,busy:w.launchConfirmBusy,showArgsInput:w.launchConfirm.showArgsInput,argsValue:w.launchConfirmArgs,onArgsChange:w.setLaunchConfirmArgs,showModelInput:w.launchConfirm.showModelInput,modelValue:w.launchConfirmModel,onModelChange:w.setLaunchConfirmModel,historyProviderNode:w.launchConfirm.providerType&&(w.launchConfirmSessionsLoading||w.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"}),w.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:Jo()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:w.launchConfirmTextFilter,onChange:I=>w.setLaunchConfirmTextFilter(I.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:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:w.launchConfirmWorkspaceFilter,onChange:I=>w.setLaunchConfirmWorkspaceFilter(I.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:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:w.launchConfirmModelFilter,onChange:I=>w.setLaunchConfirmModelFilter(I.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:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),s.jsxs("select",{value:w.launchConfirmSortMode,onChange:I=>w.setLaunchConfirmSortMode(I.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.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:w.launchConfirmResumableOnly,onChange:I=>w.setLaunchConfirmResumableOnly(I.target.checked),disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:w.launchConfirmResumeId,onChange:I=>w.setLaunchConfirmResumeId(I.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Ax()}),w.filteredLaunchConfirmSavedSessions.map(I=>s.jsxs("option",{value:I.providerSessionId,disabled:!I.canResume,children:[I.title||I.providerSessionId," ",I.canResume?"":"(workspace missing)"]},I.providerSessionId))]}),!w.launchConfirmSessionsLoading&&w.launchConfirmSavedSessions.length>0&&w.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),w.launchConfirmResumeId&&(()=>{const I=w.filteredLaunchConfirmSavedSessions.find(F=>F.providerSessionId===w.launchConfirmResumeId);if(!I)return null;const y=tu(I);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:y.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:y.providerSessionId}),s.jsx("div",{className:"mt-1",children:y.metaLine}),y.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:y.updatedLabel}),y.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:y.preview})]})})()]}),onConfirm:w.handleConfirmLaunch,onCancel:w.closeLaunchConfirm}),u&&s.jsx(eu,{section:m,onSectionChange:x})]})}function yn(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function ay(e,t=[]){const r=new Map(e.map(a=>[a.conversation.tabKey,a])),n=t.map(a=>r.get(a)).filter(a=>!!a);return n.length===e.length?n:yn(e)}function oy(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 iy(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:Cs(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 l;const a=_r(n)?"cli":Fs(n)?"acp":"ide",o=Cs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((l=n.activeChat)==null?void 0:l.title)||(_r(n)?n.cliName||n.type:Fs(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Fs(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 ly(e,t){const r=new Map;for(const n of t){const a=_s(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((h,x)=>x.timestamp-h.timestamp)[0]||null,l=(o==null?void 0:o.conversation)||null,c=io(n),d=a.filter(h=>h.unread||h.requiresAction).length,m=oy(n),u=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:At(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:d,total:a.length,latestConversation:l,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:c,preview:l?px(l):"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,l=a.latestTimestamp||a.fallbackActivityAt||0;return l!==o?l-o:n.label.localeCompare(a.label)})}function cy(e){return e==="chat"}function nn(e,t){var r;if(!(typeof window>"u"))try{if(!(!!((r=import.meta.env)!=null&&r.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,t)}catch{}}function dy({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:l,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:x,onRequestedMobileSectionConsumed:S,setSelectedTabKey:b,setScreen:p,setSelectedMachineId:g,setSection:v,setMachineBackTarget:f,resetMachineAction:C}){const T=i.useRef(null),k=i.useCallback(A=>{if(!(A!=null&&A.sessionId))return;const _=Tn(A,l),N=Math.max(Date.now(),js(A),_.lastUpdated||0);nn("mark_read:start",{tabKey:A.tabKey,sessionId:A.sessionId,displayPrimary:ut(A),inboxBucket:_.inboxBucket,unread:_.unread,lastSeenAt:_.lastSeenAt,lastUpdated:_.lastUpdated,activityAt:js(A),readAt:N}),c(_s(A)||A.routeId,"mark_session_seen",{sessionId:A.sessionId,providerSessionId:A.providerSessionId,seenAt:N,completionMarker:_.completionMarker}).then(w=>{nn("mark_read:result",{tabKey:A.tabKey,sessionId:A.sessionId,result:w})}).catch(w=>{nn("mark_read:error",{tabKey:A.tabKey,sessionId:A.sessionId,error:w instanceof Error?w.message:String(w)})})},[l,c]);return i.useEffect(()=>{var _;if(!n){cy(o)&&p("inbox"),b(((_=e[0])==null?void 0:_.tabKey)||null),T.current=null;return}if(o!=="chat"){T.current=null;return}const A=`${n.tabKey}:${n.sessionId||""}`;T.current!==A&&(T.current=A,k(n))},[e,k,o,n,p,b]),i.useEffect(()=>{if(!d)return;const A=e.find(_=>_.tabKey===d);A&&(b(A.tabKey),p("chat"),m==null||m())},[e,m,d,p,b]),i.useEffect(()=>{if(!u)return;const A=t.find(_=>_.id===u);A&&(g(A.id),C(),v("machines"),f("inbox"),p("machine"),h==null||h())},[t,h,u,C,f,p,v,g]),i.useEffect(()=>{x&&(v(x),p("inbox"),S==null||S())},[S,x,p,v]),i.useEffect(()=>{const A=r.filter(_=>_.inboxBucket==="task_complete"||_.unread);A.length!==0&&nn("inbox_state",{screen:o,selectedTabKey:a,items:A.map(_=>{const N=Tn(_.conversation,l);return{liveState:N,tabKey:_.conversation.tabKey,sessionId:_.conversation.sessionId,displayPrimary:ut(_.conversation),serverBucket:N.inboxBucket,computedBucket:_.inboxBucket,serverUnread:N.unread,computedUnread:_.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:js(_.conversation)}})})},[r,l,o,a]),{markConversationRead:k}}function uy(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function jl(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function my(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function py({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,o]=i.useState("idle"),[l,c]=i.useState(""),[d,m]=i.useState(null),u=i.useCallback(()=>{o("idle"),c(""),m(null)},[]),h=i.useCallback(async(f,C,T)=>{var k;try{o("loading"),c(`Launching ${C}…`);const A={ideType:C,enableCdp:!0};(k=T==null?void 0:T.workspacePath)!=null&&k.trim()&&(A.workspace=T.workspacePath.trim()),await e(f,"launch_ide",A),o("done"),c(`${C} launch requested`)}catch(A){o("error"),c(A instanceof Error?A.message:"Launch IDE failed"),console.error("Launch IDE failed",A)}},[e]),x=i.useCallback(async(f,C,T)=>{if(C.trim())try{o("loading"),c(T!=null&&T.createIfMissing?"Creating folder…":"Saving workspace…");const k=await e(f,"workspace_add",{path:C.trim(),createIfMissing:(T==null?void 0:T.createIfMissing)===!0});if(k!=null&&k.success){o("done"),c(T!=null&&T.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}o("error"),c((k==null?void 0:k.error)||"Could not save workspace")}catch(k){o("error"),c(k instanceof Error?k.message:"Could not save workspace")}},[e]),S=i.useCallback(async f=>{var C,T,k,A,_,N;try{o("loading"),c("Starting daemon upgrade…");const w=await e(f,"daemon_upgrade",{});if((C=w==null?void 0:w.result)!=null&&C.alreadyLatest){o("done"),c(`Already on v${((T=w==null?void 0:w.result)==null?void 0:T.version)||"latest"}.`);return}if((k=w==null?void 0:w.result)!=null&&k.upgraded||(A=w==null?void 0:w.result)!=null&&A.success){o("done"),c(`Upgrade to v${((_=w==null?void 0:w.result)==null?void 0:_.version)||"latest"} started. Daemon is restarting…`);return}o("error"),c(((N=w==null?void 0:w.result)==null?void 0:N.error)||"Upgrade failed")}catch(w){o("error"),c(w instanceof Error?w.message:"Upgrade failed")}},[e]),b=i.useCallback(async(f,C,T,k)=>{var N,w,D;const A=Date.now(),_={machineId:f,kind:C,providerType:T,workspaceId:(k==null?void 0:k.workspaceId)||null,workspacePath:(k==null?void 0:k.workspacePath)||null,resumeSessionId:(k==null?void 0:k.resumeSessionId)||null,startedAt:A};try{o("loading"),c(`Launching ${T}…`),m(_);const M={cliType:T};(N=k==null?void 0:k.workspacePath)!=null&&N.trim()?M.dir=k.workspacePath.trim():k!=null&&k.workspaceId&&(M.workspaceId=k.workspaceId),k!=null&&k.resumeSessionId&&(M.resumeSessionId=k.resumeSessionId),(w=k==null?void 0:k.args)!=null&&w.trim()&&(M.cliArgs=k.args.trim().split(/\s+/).filter(Boolean)),(D=k==null?void 0:k.model)!=null&&D.trim()&&(M.initialModel=k.model.trim());const j=await e(f,"launch_cli",M),W=(j==null?void 0:j.result)||j,H=(W==null?void 0:W.sessionId)||(W==null?void 0:W.id);if(j!=null&&j.success&&H){m(null),o("done"),c(`${T} launched`),t(Zt(H));return}if(j!=null&&j.success){o("loading"),c(`${T} launch requested — waiting for session…`);return}m(null),o("error"),c((j==null?void 0:j.error)||(W==null?void 0:W.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(M){if(my(M)){o("loading"),c(`${T} launch requested — waiting for session…`);return}m(null),o("error"),c(M instanceof Error?M.message:`Could not launch ${C.toUpperCase()} workspace`)}},[t,e]),p=i.useCallback(async(f,C)=>{try{const T=await e(f,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),k=(T==null?void 0:T.result)??T;return Array.isArray(k==null?void 0:k.sessions)?k.sessions:[]}catch(T){return console.error("Failed to list saved sessions on mobile:",T),[]}},[e]),g=i.useCallback(async(f,C)=>Zn(e,f,C),[e]);i.useEffect(()=>{if(!d)return;const f=jl(d.workspacePath),C=r.find(k=>{var M,j,W,H;if(!k||k.type==="adhdev-daemon"||uy(k.daemonId||k.id)!==d.machineId||(k.transport==="acp"?"acp":k.transport==="pty"?"cli":null)!==d.kind||String(k.agentType||k.type||"")!==d.providerType)return!1;const w=String(k.providerSessionId||"");if(d.resumeSessionId&&w)return w===d.resumeSessionId;if(f){const $=jl(k.workspace||k.runtimeWorkspaceLabel);return $?$===f:!1}return Number(k.lastUpdated||k._lastUpdate||k.timestamp||((H=(W=(j=(M=k.activeChat)==null?void 0:M.messages)==null?void 0:j.at)==null?void 0:W.call(j,-1))==null?void 0:H.timestamp)||0)>=d.startedAt-5e3});if(!C)return;const T=Xd({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:n});T&&(m(null),o("done"),c(`${d.providerType} launched`),t(Zt(T)))},[n,r,t,d]),i.useEffect(()=>{if(!d)return;const f=window.setTimeout(()=>{m(C=>!C||C.startedAt!==d.startedAt?C:(o("error"),c("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(f)},[d]);const v=i.useCallback(async(f,C)=>{if(C.kind==="ide"&&C.providerType){await h(f,C.providerType,{workspacePath:C.workspace||null});return}(C.kind==="cli"||C.kind==="acp")&&C.providerType&&await b(f,C.kind,C.providerType,{workspacePath:C.workspace||null,resumeSessionId:C.providerSessionId||null})},[h,b]);return{machineAction:{state:a,message:l},resetMachineAction:u,handleLaunchDetectedIde:h,handleAddWorkspace:x,handleMachineUpgrade:S,handleLaunchWorkspaceProvider:b,handleListSavedSessions:p,handleBrowseDirectory:g,handleOpenRecent:v}}function hy({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:l,setSelectedMachineId:c,setSection:d,setMachineBackTarget:m}){const u=i.useCallback(v=>{o(v.tabKey),l("chat"),n(v)},[n,l,o]),h=i.useCallback(v=>{const f=e.find(C=>C.routeId===v.routeId&&C.streamSource==="native");f&&(o(f.tabKey),l("chat"),n(f))},[e,n,l,o]),x=i.useCallback(()=>{n(t),l("inbox")},[n,t,l]),S=i.useCallback((v,f="inbox")=>{c(v),a(),d("machines"),m(f),l("machine")},[a,m,l,d,c]),b=i.useCallback(v=>{const f=_s(v);f&&S(f,"chat")},[S]),p=i.useCallback(()=>{a(),l(r)},[r,a,l]),g=i.useCallback(v=>{d(v),l("inbox")},[l,d]);return{openConversation:u,openNativeConversation:h,backFromConversation:x,openMachine:S,openConversationMachine:b,backFromMachine:p,changeMachineSection:g}}function Ts(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function fy(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function xy({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:l,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:x,onRequestedMobileSectionConsumed:S,onOpenHistory:b,onOpenRemote:p,onStopCli:g,wsStatus:v,isConnected:f,onShowAllHiddenConversations:C,onHideConversation:T,onOpenMeshGraph:k,onOpenNewSession:A,liveSessionInboxState:_,setCliViewModeOverrides:N}){const[w,D]=i.useState(()=>{var q;return((q=e[0])==null?void 0:q.tabKey)||null}),[M,j]=i.useState(()=>e[0]?"chat":"inbox"),[W,H]=i.useState("chats"),[$,I]=i.useState(null),[y,F]=i.useState("inbox"),P=i.useRef([]),E=As(),G="0.9.81",J=i.useMemo(()=>e.find(q=>q.tabKey===w)||e[0]||null,[e,w]),ye=i.useMemo(()=>J?r.find(q=>q.id===J.routeId):void 0,[r,J]),he=i.useMemo(()=>!J||st(J)||!at(J)?null:Zs(J),[J]),ne=i.useMemo(()=>r.filter(q=>q.type==="adhdev-daemon").sort(Fo),[r]),ue=i.useMemo(()=>ne.find(q=>q.id===$)||null,[ne,$]),Se=qn({sendDaemonCommand:a,activeConv:J||void 0,setActionLogs:o,isStandalone:l}),ve=py({sendDaemonCommand:a,navigate:E,ides:r,conversations:e}),X=i.useMemo(()=>e.map(q=>{const ce=M==="chat"&&(J==null?void 0:J.tabKey)===q.tabKey,Ne=zn(q,_,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ce}),je=js(q),O=ld(q);return{conversation:q,timestamp:je,preview:O,unread:Ne.unread,requiresAction:Ne.requiresAction,isWorking:Ne.isWorking,inboxBucket:Ne.inboxBucket}}),[e,_,M,J]),{markConversationRead:xe}=dy({conversations:e,machineEntries:ne,items:X,selectedConversation:J,selectedTabKey:w,screen:M,liveSessionInboxState:_,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:x,onRequestedMobileSectionConsumed:S,setSelectedTabKey:D,setScreen:j,setSelectedMachineId:I,setSection:H,setMachineBackTarget:F,resetMachineAction:ve.resetMachineAction}),fe=hy({conversations:e,selectedConversation:J,machineBackTarget:y,markConversationRead:xe,resetMachineAction:ve.resetMachineAction,setSelectedTabKey:D,setScreen:j,setSelectedMachineId:I,setSection:H,setMachineBackTarget:F}),we=i.useMemo(()=>yn(X.filter(q=>q.requiresAction)),[X]),be=i.useMemo(()=>yn(X.filter(q=>q.unread&&!q.requiresAction)),[X]),Ce=i.useMemo(()=>ay(X.filter(q=>!q.unread&&!q.requiresAction&&q.isWorking),P.current),[X]);i.useEffect(()=>{P.current=Ce.map(q=>q.conversation.tabKey)},[Ce]);const ee=i.useMemo(()=>yn(X.filter(q=>!q.unread&&!q.requiresAction&&!q.isWorking)),[X]),me=i.useMemo(()=>ue?X.filter(q=>_s(q.conversation)===ue.id):[],[X,ue]),ie=i.useMemo(()=>iy(ue,r),[r,ue]),pe=(ue==null?void 0:ue.version)||null,le=!!ue&&!!pe&&!0&&pe!==G,B=i.useMemo(()=>(ue==null?void 0:ue.availableProviders)||[],[ue]),z=i.useMemo(()=>B.filter(q=>Ts(q,"cli")).map(q=>({type:q.type,displayName:q.displayName||q.type,icon:q.icon})),[B]),de=i.useMemo(()=>B.filter(q=>Ts(q,"acp")).map(q=>({type:q.type,displayName:q.displayName||q.type,icon:q.icon})),[B]),re=i.useMemo(()=>ly(ne,X),[X,ne]),R=i.useCallback(async q=>{ue&&await ve.handleOpenRecent(ue.id,q)},[ve,ue]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&J?s.jsx(Yg,{selectedConversation:J,isAcp:st(J),isStandalone:l,selectedIdeEntry:ye,actionLogs:n,userName:c,isSendingChat:Se.isSendingChat,sendFeedbackMessage:Se.sendFeedbackMessage,isFocusingAgent:Se.isFocusingAgent,handleModalButton:Se.handleModalButton,handleRelaunch:Se.handleRelaunch,onBack:fe.backFromConversation,onOpenNativeConversation:fe.openNativeConversation,onOpenMachine:fe.openConversationMachine,onOpenHistory:b,onOpenRemote:p,onOpenMeshGraph:k,onStopCli:g,cliViewMode:he,onSetCliViewMode:async q=>{await Ed({conversation:J,mode:q,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:N})},handleSendChat:Se.handleSendChat,handleFocusAgent:Se.handleFocusAgent}):M==="machine"&&ue?s.jsx(ny,{selectedMachineEntry:ue,selectedMachineConversations:me,selectedMachineRecentLaunches:ie,cliProviders:z,acpProviders:de,selectedMachineNeedsUpgrade:le,appVersion:G,machineAction:ve.machineAction,isStandalone:l,section:W,showBottomNav:y==="inbox",onBack:fe.backFromMachine,onSectionChange:fe.changeMachineSection,onOpenConversation:fe.openConversation,onOpenRecent:R,onOpenMachineDetails:()=>E(`/machines/${ue.id}`),onMachineUpgrade:()=>ve.handleMachineUpgrade(ue.id),onLaunchDetectedIde:(q,ce)=>ve.handleLaunchDetectedIde(ue.id,q,ce),onAddWorkspace:(q,ce)=>ve.handleAddWorkspace(ue.id,q,ce),onBrowseDirectory:q=>ve.handleBrowseDirectory(ue.id,q),onLaunchWorkspaceProvider:(q,ce,Ne)=>ve.handleLaunchWorkspaceProvider(ue.id,q,ce,Ne),onListSavedSessions:q=>ve.handleListSavedSessions(ue.id,q)}):s.jsx(Qg,{section:W,attentionItems:we,unreadItems:be,workingItems:Ce,completedItems:ee,hiddenConversations:t,machineCards:re,getAvatarText:fy,actionLogs:n,sendDaemonCommand:a,onOpenConversation:fe.openConversation,onShowAllHidden:C,onHideConversation:T,onOpenMeshGraph:k,onOpenNewSession:A,onOpenMachine:fe.openMachine,onOpenSettings:()=>E("/settings"),onSectionChange:H,wsStatus:v,isConnected:f,isStandalone:l})})}function Ma(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function by({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const l=i.useRef(0),[c,d]=i.useState(!1),[m,u]=i.useState(null),h=i.useCallback(()=>{l.current=0,d(!1),u(null)},[]);i.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const x=i.useCallback(g=>{g.dataTransfer.types.includes("text/tab-key")&&(l.current+=1,d(!0))},[]),S=i.useCallback(g=>{if(!g.dataTransfer.types.includes("text/tab-key"))return;if(g.preventDefault(),!Ma(t,r)){u("merge");return}const v=g.currentTarget.getBoundingClientRect(),f=g.clientX-v.left,C=v.width/3;f<C?u("split-left"):f>C*2?u("split-right"):u("merge")},[t,r]),b=i.useCallback(()=>{l.current-=1,!(l.current>0)&&(l.current=0,d(!1),u(null))},[]),p=i.useCallback(g=>{l.current=0,d(!1);const v=g.dataTransfer.getData("text/tab-key"),f=v?e.some(T=>T.tabKey===v):!1,C=m;if(u(null),o(),!!v){if(g.preventDefault(),C==="split-left"&&Ma(t,r)){r==null||r(v,"split-left");return}if(C==="split-right"&&Ma(t,r)){r==null||r(v,"split-right");return}if(f){a(v);return}n==null||n(v)}},[e,m,t,r,n,a,o]);return{dragOver:c,dropAction:m,resetDragState:h,handleDragEnter:x,handleDragOver:S,handleDragLeave:b,handleDrop:p}}function gy(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 yy({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,l]=i.useState(t??null),[c,d]=i.useState(r??[]),[m,u]=i.useState(null),h=i.useRef(null),x=i.useRef(null),S=i.useRef(n),b=i.useRef(a);i.useEffect(()=>{S.current=n},[n]),i.useEffect(()=>{b.current=a},[a]),i.useEffect(()=>{t&&t!==o&&l(t)},[t,o]),i.useEffect(()=>{d(_=>{const N=gy(_,e);return N.length===_.length&&N.every((w,D)=>w===_[D])?_:N})},[e]);const p=i.useMemo(()=>{const _=m??c;if(_.length===0)return e;const N=new Map(_.map((w,D)=>[w,D]));return[...e].sort((w,D)=>{const M=N.get(w.tabKey)??999,j=N.get(D.tabKey)??999;return M-j})},[e,m,c]);i.useEffect(()=>{var N,w;if(p.length===0){o!==null&&(l(null),(N=S.current)==null||N.call(S,null));return}if(o&&p.some(D=>D.tabKey===o))return;const _=p[0].tabKey;_!==o&&(l(_),(w=S.current)==null||w.call(S,_))},[p,o]);const g=i.useMemo(()=>p.find(_=>_.tabKey===o),[p,o]),v=i.useCallback(_=>{var N;l(_),(N=S.current)==null||N.call(S,_)},[]),f=i.useCallback((_,N,w)=>{d(D=>{var H;const M=D.filter($=>$!==_),j=M.indexOf(N);if(j<0)return D;const W=w==="left"?j:j+1;return M.splice(W,0,_),(H=b.current)==null||H.call(b,M),M}),u(null)},[]),C=i.useCallback((_,N,w)=>{const M=(c.length>0?c:e.map(H=>H.tabKey)).filter(H=>H!==_),j=M.indexOf(N);if(j<0)return;const W=w==="left"?j:j+1;M.splice(W,0,_),h.current=M,u(M)},[c,e]),T=i.useCallback(()=>{var N;const _=h.current;_&&(d(_),(N=b.current)==null||N.call(b,_))},[]),k=i.useCallback(()=>{h.current=null,u(null)},[]),A=i.useCallback(_=>{d(N=>{var D;const w=N.filter(M=>M!==_);return w.push(_),(D=b.current)==null||D.call(b,w),w})},[]);return{activeTabId:o,activeConv:g,sortedConversations:p,previewOrderRef:h,draggingTabRef:x,selectTab:v,handleTabReorder:f,updatePreviewOrder:C,commitPreviewOrder:T,clearPreviewOrder:k,moveTabToEnd:A,setDraggingTabKey:_=>{x.current=_}}}function vy({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 ci({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 l=!r&&!n,c=n&&!!o,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",m=n?md:r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:d}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children: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:zt,"aria-label":zt,children:[s.jsx(kc,{size:14}),s.jsx("span",{children:zt})]})}),l&&s.jsx(Zd,{}),l&&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 ru="adhdev-tab-shortcuts";function nu(){try{return JSON.parse(localStorage.getItem(ru)||"{}")}catch{return{}}}function au({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,l]=i.useState(()=>nu()),[c,d]=i.useState(null),m=i.useCallback(h=>{const x=[];return h.metaKey&&x.push(a?"⌘":"Meta"),h.ctrlKey&&x.push("Ctrl"),h.altKey&&x.push(a?"⌥":"Alt"),h.shiftKey&&x.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(x.push(h.key.length===1?h.key.toUpperCase():h.key),x.join("+"))},[a]),u=i.useCallback(h=>{l(h);try{localStorage.setItem(ru,JSON.stringify(h))}catch{}},[]);return i.useEffect(()=>{if(!e||!c)return;const h=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){d(null);return}const S=m(x);if(!S)return;const b={...o};for(const[p,g]of Object.entries(b))g===S&&delete b[p];b[c]=S,u(b),d(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,c,o,u,m]),i.useEffect(()=>{if(!e)return;const h=x=>{if(!(!x.ctrlKey&&!x.metaKey&&!x.altKey)){for(const[S,b]of Object.entries(o))if(t.includes(S)&&m(x)===b){x.preventDefault(),r(),n(S);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,o,t,r,n,m]),{isMac:a,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const Aa=e=>{e.preventDefault()},wy=i.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:l,draggingTabRef:c,onFocus:d,onSelectTab:m,onConversationActivated:u,onPreviewReorder:h,onReorderTab:x,onCommitPreviewOrder:S,onClearPreviewOrder:b,onDragStateReset:p,onDragTabKeyChange:g,onReceiveTab:v,onOpenContextMenu:f,longPressTimer:C,isGroupActive:T}){const k=Qs(t),A=k.isGenerating?"agent-tab-generating":k.isWaiting?"agent-tab-waiting":"",_=k.isReconnecting,N=i.useCallback(y=>{c.current=t.tabKey,g(t.tabKey),y.dataTransfer.setData("text/tab-key",t.tabKey),y.dataTransfer.effectAllowed="move"},[t.tabKey,c,g]),w=i.useCallback(()=>{c.current=null,g(null),S(),b(),p()},[c,g,S,b,p]),D=i.useCallback(y=>{const F=c.current;if(!(!F||F===t.tabKey)&&y.dataTransfer.types.includes("text/tab-key")){y.preventDefault(),y.stopPropagation();const P=y.currentTarget.getBoundingClientRect(),E=y.clientX<P.left+P.width/2?"left":"right";h(F,t.tabKey,E)}},[t.tabKey,c,h]),M=i.useCallback(y=>{y.preventDefault(),y.stopPropagation();const F=y.dataTransfer.getData("text/tab-key");if(F&&F!==t.tabKey){const P=y.currentTarget.getBoundingClientRect(),E=y.clientX<P.left+P.width/2?"left":"right";l.includes(F)?x(F,t.tabKey,E):v&&v(F)}b()},[t.tabKey,l,x,v,b]),j=i.useCallback(y=>{y.stopPropagation(),d(),m(t.tabKey),u(t)},[t,u,d,m]),W=i.useCallback(y=>{y.preventDefault(),f(y.clientX,y.clientY,t.tabKey)},[t.tabKey,f]),H=i.useCallback(y=>{const F=y.touches[0];C.current=setTimeout(()=>{f(F.clientX,F.clientY,t.tabKey)},600)},[t.tabKey,C,f]),$=i.useCallback(()=>{C.current&&clearTimeout(C.current)},[C]),I=["adhdev-dockview-tab",A,r&&"is-active",T&&"is-group-active",_&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:I,draggable:!0,onDragStart:N,onDragEnd:w,onDragOver:D,onDrop:M,onClick:j,onContextMenu:W,onTouchStart:H,onTouchEnd:$,onTouchMove:$,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:k.isGenerating?s.jsx("div",{className:"tab-spinner"}):k.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):_?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):k.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:ut(t),children:ut(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[_?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:bs(t)}):k.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[bs(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:bs(t)}),s.jsx(qs,{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 jy({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:l,onConversationActivated:c,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:h,onDragStateReset:x,onDragTabKeyChange:S,onReceiveTab:b,onHideTab:p,isGroupActive:g,allowTabShortcuts:v=!0}){const[f,C]=i.useState(null),T=i.useRef(null),k=i.useRef(null),A=i.useMemo(()=>e.map(W=>W.tabKey),[e]);Pr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(f==null?void 0:f.tabKey)||null});const{isMac:_,tabShortcuts:N,shortcutListening:w,setShortcutListening:D,saveShortcuts:M}=au({enabled:v,sortedTabKeys:e.map(W=>W.tabKey),onFocus:o,onSelectTab:l});i.useEffect(()=>{if(!f)return;const W=H=>{const $=document.querySelector("[data-pane-context-menu]");$&&$.contains(H.target)||C(null)};return window.addEventListener("mousedown",W,!0),()=>window.removeEventListener("mousedown",W,!0)},[f]),i.useEffect(()=>{const W=k.current;if(!W)return;const H=$=>{Math.abs($.deltaY)<=Math.abs($.deltaX)||($.preventDefault(),W.scrollLeft+=$.deltaY)};return W.addEventListener("wheel",H,{passive:!1}),()=>W.removeEventListener("wheel",H)},[]);const j=i.useCallback((W,H,$)=>{C({x:W,y:H,tabKey:$})},[]);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(W=>s.jsx(wy,{conv:W,isActive:t===W.tabKey,isDraggedTab:a.current===W.tabKey,isTaskCompleteUnread:n.has(W.tabKey),shortcut:v?N[W.tabKey]:void 0,conversationKeys:A,draggingTabRef:a,onFocus:o,onSelectTab:l,onConversationActivated:c,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:h,onDragStateReset:x,onDragTabKeyChange:S,onReceiveTab:b,onOpenContextMenu:j,longPressTimer:T,isGroupActive:g},W.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),f&&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:f.x,top:f.y},children:[v&&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:Aa,onClick:W=>{W.stopPropagation(),D(f.tabKey),C(null)},children:["⌨ ",N[f.tabKey]?`Change shortcut (${N[f.tabKey]})`:"Set shortcut"]}),N[f.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:Aa,onClick:()=>{const W={...N};delete W[f.tabKey],M(W),C(null)},children:"✕ Remove shortcut"})]}),p&&s.jsxs(s.Fragment,{children:[v&&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:Aa,onClick:()=>{p(f.tabKey),C(null)},children:"🚫 Hide from Dashboard"})]})]}),v&&w&&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:W=>W.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. ",_?"⌘+1":"Ctrl+1",", ",_?"⌥+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 ky({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:l,hasRegisteredMachines:c,userName:d,groupIndex:m,onFocus:u,isSplitMode:h,numGroups:x,onMoveTab:S,onReceiveTab:b,style:p,onActiveTabChange:g,initialActiveTabId:v,initialTabOrder:f,onTabOrderChange:C,onHideTab:T,isFocused:k,allowTabShortcuts:A=!0,onOpenNewSession:_,liveSessionInboxState:N}){const{sendCommand:w}=jt(),D=i.useRef(null),{activeTabId:M,activeConv:j,sortedConversations:W,draggingTabRef:H,selectTab:$,handleTabReorder:I,updatePreviewOrder:y,commitPreviewOrder:F,clearPreviewOrder:P,moveTabToEnd:E,setDraggingTabKey:G}=yy({conversations:e,initialActiveTabId:v,initialTabOrder:f,onActiveTabChange:g,onTabOrderChange:C}),J=qn({sendDaemonCommand:a,activeConv:j,setActionLogs:o,isStandalone:l}),{dragOver:ye,dropAction:he,resetDragState:ne,handleDragEnter:ue,handleDragOver:Se,handleDragLeave:ve,handleDrop:X}=by({conversations:e,numGroups:x,onMoveTab:S,onReceiveTab:b,onOwnTabDrop:E,onClearPreviewOrder:P}),xe=j&&!st(j)&&Zs(j)==="terminal",fe=i.useMemo(()=>j?t.find(ee=>ee.id===j.routeId):void 0,[t,j]),we=i.useMemo(()=>j?n.filter(ee=>ee.routeId===j.tabKey):[],[n,j]),be=i.useMemo(()=>new Set(W.filter(ee=>eh(ee,N,{isOpenConversation:ee.tabKey===M})).map(ee=>ee.tabKey)),[M,N,W]);Pr("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:M,dragOver:ye});const Ce=i.useCallback(ee=>{ee.streamSource==="agent-stream"&&ee.agentType&&w(ee.routeId,qc(),{agentType:ee.agentType,...ee.sessionId&&{targetSessionId:ee.sessionId}}).catch(()=>{})},[w]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...p,outline:ye?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(jy,{conversations:W,activeTabId:M,groupIndex:m,numGroups:x,unreadTabKeys:be,draggingTabRef:H,onFocus:u,onSelectTab:$,onConversationActivated:Ce,onPreviewReorder:y,onReorderTab:I,onCommitPreviewOrder:F,onClearPreviewOrder:P,onDragStateReset:ne,onDragTabKeyChange:G,onMoveTab:S,onReceiveTab:b,onHideTab:T,isGroupActive:k??!1,allowTabShortcuts:A}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ue,onDragOver:Se,onDragLeave:ve,onDrop:X,children:[ye&&s.jsx(vy,{dropAction:he,canSplit:!!(x<4&&S)}),j?s.jsx(ii,{activeConv:j,clearToken:r[j.tabKey]||0,isCliTerminal:!!xe,ideEntry:fe,terminalRef:D,handleModalButton:J.handleModalButton,handleRelaunch:J.handleRelaunch,handleSendChat:J.handleSendChat,isSendingChat:J.isSendingChat,sendFeedbackMessage:J.sendFeedbackMessage,handleFocusAgent:J.handleFocusAgent,isFocusingAgent:J.isFocusingAgent,actionLogs:we,userName:d,isInputActive:!h||!!k}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(ci,{conversationsCount:e.length,isSplitMode:h,isStandalone:l,hasRegisteredMachines:c,onOpenNewSession:_})})]})]})}function Sy({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:l,actionLogs:c,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:h,userName:x,focusedGroup:S,focusGroup:b,moveTabToGroup:p,splitTabRelative:g,closeGroup:v,handleResizeStart:f,groupActiveTabIds:C,setGroupActiveTab:T,groupTabOrders:k,setGroupTabOrder:A,toggleHiddenTab:_,onOpenNewSession:N,allowTabShortcuts:w=!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((M,j)=>{const W=t&&n.length===r?`${n[j]}%`:void 0;return s.jsxs(Nt.Fragment,{children:[t&&j>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:H=>f(j-1,H),onDoubleClick:()=>v(j),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(ky,{style:t?{flexBasis:W??`${100/r}%`,flexGrow:W?0:1,flexShrink:W?0:1}:void 0,conversations:M,clearedTabs:o,ides:l,actionLogs:c,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:h,userName:x,groupIndex:j,isFocused:t&&S===j,onFocus:()=>b(j),isSplitMode:t,numGroups:r,onMoveTab:(H,$)=>{$==="left"&&j>0?p(H,j-1):$==="right"&&j<r-1?p(H,j+1):$==="split-left"&&r<4?g(H,j,"left"):$==="split-right"&&r<4&&g(H,j,"right")},onReceiveTab:H=>p(H,j),onActiveTabChange:H=>T(j,H),initialActiveTabId:C[j],initialTabOrder:k[j],onTabOrderChange:H=>A(j,H),onHideTab:_,onOpenNewSession:N,allowTabShortcuts:w,liveSessionInboxState:D})]},j)})})}function ou({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=i.useState(null),[l,c]=i.useState(null);i.useEffect(()=>e?mt.onScreenshot("ide-page",(u,h)=>{if(u!==e)return;const x=new FileReader;x.onload=()=>o(x.result),x.readAsDataURL(h)}):void 0,[e]),i.useEffect(()=>{r!=="connected"&&o(null)},[r]),i.useEffect(()=>{var u;return e?((u=mt.onStatus)==null?void 0:u.call(mt,(h,x)=>{h===e&&x!=null&&x.screenshotUsage&&c(x.screenshotUsage)}))||(()=>{}):void 0},[e]),i.useEffect(()=>{o(null)},[e,t]),i.useEffect(()=>{const m=e?mt.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 d=i.useCallback(async(m,u)=>{const h=e?mt.get(e):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(m,u,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:l,handleRemoteAction:d}}const iu="adhdev-dashboard-action-shortcuts",Ny=1200,Cy=[["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 Iy(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function lt(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function lu(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:lt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:lt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:lt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:lt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:lt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:lt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:lt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:lt("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:lt("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:lt("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:lt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:lt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:lt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:lt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:lt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:lt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:lt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:lt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:lt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:lt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:lt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:lt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:lt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:lt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:lt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:lt("toggleCliView",e)}]}function wo(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function On(e){const t=Object.fromEntries(lu(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(iu)||"{}"),n={...t,...r};for(const[a,o]of Cy)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function cu(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Ty({enabled:e=!0,onTrigger:t}){const r=Iy(),[n,a]=i.useState(()=>On(r)),[o,l]=i.useState(null),[c,d]=i.useState([]),m=i.useRef({parts:[],timer:null}),u=i.useCallback(p=>{const g=[];return p.metaKey&&g.push(r?"⌘":"Meta"),p.ctrlKey&&g.push("Ctrl"),p.altKey&&g.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&g.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(g.push(cu(p.key)),g.join("+"))},[r]),h=i.useCallback(p=>{a(p);try{localStorage.setItem(iu,JSON.stringify(p))}catch{}},[]);i.useEffect(()=>{const p=On(r),g=Object.entries(n),v=Object.entries(p);g.length===v.length&&g.every(([f,C])=>p[f]===C)||h(p)},[n,r,h]);const x=i.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),S=i.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},Ny))},[]);i.useEffect(()=>{if(!o)return;const p=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){l(null),d([]);return}const v=u(g);if(!v)return;const C=!(g.metaKey||g.ctrlKey||g.altKey)&&/^[A-Z0-9]$/.test(v);if(c.length===0&&C){d([v]);return}const k=[...c,v].slice(0,2).join(" "),A={...n};for(const[_,N]of Object.entries(A))N===k&&delete A[_];A[o]=k,h(A),l(null),d([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,u,h,o,c]),i.useEffect(()=>{if(!e||o)return;const p=g=>{if(g.defaultPrevented)return;const v=u(g);if(!v)return;const f=g.metaKey||g.ctrlKey||g.altKey;if(wo(g.target))return;const C=m.current.parts,T=f?[v]:[...C.slice(-1),v].slice(-2),k=T.join(" "),A=T[T.length-1],_=Object.entries(n).filter(([,j])=>!!j),N=_.find(([,j])=>j===k);if(N){g.preventDefault(),x(),t(N[0]);return}if(_.some(([,j])=>j.startsWith(`${k} `))){g.preventDefault(),m.current.parts=T,S();return}const D=_.find(([,j])=>j===A);if(D){g.preventDefault(),x(),t(D[0]);return}if(_.some(([,j])=>j.startsWith(`${A} `))){g.preventDefault(),m.current.parts=[A],S();return}x()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,S,e,u,t,x,o]),i.useEffect(()=>()=>x(),[x]);const b=i.useMemo(()=>lu(r),[r]);return{isMac:r,actionDefinitions:b,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:l,setShortcutListeningDraft:d,saveShortcuts:h}}function My({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 du(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function kl({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!du(n):!0}function Ay({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:du(r)}const uu=1e3,_y=4;function Sl(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Nl(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function Ly({detachDelayMs:e=uu,stillnessThresholdPx:t=_y,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,l=null,c=null,d=null,m=null,u=!1;const h=()=>{m!=null&&(a(m),m=null)},x=()=>{h(),c=null},S=()=>{h(),o=null,l=null,c=null,d=null,u=!1},b=()=>{!o||!c||!d||u||m!=null||(m=n(()=>{m=null,!(!o||!c||!d||u)&&Sl(d,l)&&(Nl(c,d,t)||(u=!0,r({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},p=v=>{if(!(!o||u)){if(!Sl(v,l)){d={clientX:v.clientX,clientY:v.clientY},x();return}(!c||Nl(c,v,t))&&(h(),c={clientX:v.clientX,clientY:v.clientY}),d={clientX:v.clientX,clientY:v.clientY},b()}},g=v=>{!o||u||(v&&(d={clientX:v.clientX,clientY:v.clientY}),x())};return{startDrag:v=>{h(),o=v.panelId,l=v.selfPanelBounds??null,c=null,d={clientX:v.clientX,clientY:v.clientY},u=!1},markSelfPanel:p,markNonSelfPanel:g,markNoDropTarget:g,markDockTarget:g,endDrag:S,isDragging:()=>o!=null,hasDetached:()=>u,dispose:S}}function Ry(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function an(e){return e.isActive}function Cl(e){return e.isVisible}const mu=i.createContext(null);function ta(){const e=i.useContext(mu);if(!e)throw new Error("DashboardDockviewContext missing");return e}function vn(e){return ut(e)||e.tabKey}function Py(e){return`remote:${e}`}function Bt(e){return e.startsWith("remote:")}function Il(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Dy(e){e.preventDefault()}function _a(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 La(e,t){e.classList.remove(eo.className,to.className),e.classList.add(t==="light"?eo.className:to.className)}function Tl(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 Ey(e){const[,t]=i.useState(0);i.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 $y(e,t,r){var l;const n=[t];let a;for(const c of n){let d;for(const m of c){const u=e.addPanel({id:m.tabKey,component:"conversation",title:vn(m),params:{kind:"conversation",tabKey:m.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});d||(d=u.id)}a=d??a}return r??((l=t[0])==null?void 0:l.tabKey)??null}function Ml(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])Bt(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!==vn(a)&&o.api.setTitle(vn(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:vn(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 Al(e,t,r){var d,m;const n=r?Py(r):null;for(const u of[...e.panels])Bt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=Wt(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),l=ud(a);if(o){o.title!==l&&o.api.setTitle(l);return}const c=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((m=e.panels.find(u=>!Bt(u.id)))==null?void 0:m.id);e.addPanel({id:n,component:"remote",title:l,params:{kind:"remote",routeId:r},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function By({params:e,api:t}){var S;const r=ta(),n=i.useRef(null),[a,o]=i.useState(()=>an(t)),[l,c]=i.useState(()=>Cl(t)),d=r.conversationsByTabKey.get(e.tabKey),m=qn({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});i.useEffect(()=>{o(an(t)),c(Cl(t));const b=[t.onDidActiveChange(p=>o(p.isActive)),t.onDidActiveGroupChange(p=>{if(!an(t)&&!p.isActive){o(!1);return}o(an(t))}),t.onDidVisibilityChange(p=>c(p.isVisible))];return()=>{for(const p of b)p.dispose()}},[t]);const u=i.useMemo(()=>d?r.ides.find(b=>b.id===d.routeId):void 0,[r.ides,d]),h=i.useMemo(()=>d?r.actionLogs.filter(b=>b.routeId===d.tabKey):[],[r.actionLogs,d]);if(!d)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(ci,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const x=!st(d)&&Zs(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(ii,{activeConv:d,clearToken:r.clearedTabs[d.tabKey]||0,isCliTerminal:x,ideEntry:u,terminalRef:n,handleModalButton:m.handleModalButton,handleRelaunch:m.handleRelaunch,handleSendChat:m.handleSendChat,isSendingChat:m.isSendingChat,handleFocusAgent:m.handleFocusAgent,isFocusingAgent:m.isFocusingAgent,actionLogs:h,userName:r.userName,scrollToBottomRequestNonce:((S=r.scrollToBottomRequest)==null?void 0:S.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:l})})}function Oy({params:e}){var d;const t=ta(),r=i.useMemo(()=>Wt([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=i.useMemo(()=>t.ides.find(m=>m.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((d=r==null?void 0:r.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:l,handleRemoteAction:c}=ou({doId:a,targetSessionId:r?Gc(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(_c,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:o,screenshotUsage:l,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 Fy(){const e=ta();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(ci,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function Wy(e){var S,b;Ey(e);const t=ta(),r=i.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=Wt([...t.conversationsByTabKey.values()],e.params.routeId),g=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,v=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${g?" is-active":""}${v?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(p==null?void 0:p.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:p!=null&&p.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:p.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const n=t.conversationsByTabKey.get(e.params.tabKey);if(!n)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 a=((b=e.api.group.activePanel)==null?void 0:b.id)===e.api.id,o=e.api.isGroupActive,l=zn(n,t.liveSessionInboxState,{isOpenConversation:a}),c=l.isReconnecting,d=l.isConnecting,m=l.isGenerating,u=l.isWaiting,h=l.unread,x=t.tabShortcuts[n.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${o?" is-group-active":""}${c?" is-reconnecting":""}`,title:ut(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:p=>{var g;p.preventDefault(),r(p),t.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((g=p.target)==null?void 0:g.ownerDocument)??document})},children:[h&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:m?s.jsx("div",{className:"tab-spinner"}):u?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):c?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):d?s.jsx("div",{className:"tab-connecting-spinner"}):n.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:ut(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:c?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:bs(n)}):d?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:bs(n)}):s.jsx("span",{children:bs(n)})})]}),x&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:x,children:x})]})}function Ky({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:l,hasRegisteredMachines:c,initialDataLoaded:d,userName:m,toggleHiddenTab:u,actionShortcuts:h,registerActionHandlers:x,onActiveTabChange:S,onOpenNewSession:b,onRequestScrollToBottom:p,requestedActiveTabKey:g,requestedRemoteIdeId:v,onRequestedActiveTabConsumed:f,scrollToBottomRequest:C,liveSessionInboxState:T,layoutProfile:k}){var tt,Ge,ot;const{theme:A}=er(),{sendCommand:_}=jt(),N=i.useRef(null),w=i.useRef(null),D=i.useRef(null),M=i.useRef(!1),j=i.useRef(!1),W=i.useRef(!1),H=i.useRef(null),$=i.useRef([]),[I,y]=i.useState(null),[F,P]=i.useState(0),E=i.useRef(typeof window>"u"?{}:ig(k)),G=i.useMemo(()=>new Map(e.map(U=>[U.tabKey,U])),[e]),J=i.useMemo(()=>{const U=N.current;return U?U.groups.some(V=>{try{const Z=V.model.location.type;return Z!=="floating"&&Z!=="popout"?!1:V.panels.some(ae=>G.has(ae.id))}catch{return!1}}):!1},[G,F,e]),ye=i.useCallback(()=>{var U;(U=N.current)==null||U.focus()},[]),he=i.useCallback((U,V)=>{p==null||p(U,V)},[p]),ne=i.useCallback(U=>{const V=document,Z=U.document;for(const oe of V.querySelectorAll('link[rel="stylesheet"]')){const ke=Z.createElement("link");ke.rel="stylesheet",ke.href=oe.href,oe.crossOrigin&&(ke.crossOrigin=oe.crossOrigin),Z.head.appendChild(ke)}for(const oe of V.querySelectorAll("style")){const ke=Z.createElement("style");ke.textContent=oe.textContent,Z.head.appendChild(ke)}const ae=[];for(const oe of V.styleSheets)try{for(const ke of oe.cssRules)ke instanceof CSSStyleRule&&(ke.selectorText===":root"||ke.selectorText==="html")&&ae.push(ke.cssText)}catch{}if(ae.length>0){const oe=Z.createElement("style");oe.textContent=ae.join(`
|
|
54
|
+
`),Z.head.appendChild(oe)}const K=V.documentElement.getAttribute("data-theme");K&&Z.documentElement.setAttribute("data-theme",K),Z.documentElement.style.colorScheme=K==="light"?"light":"dark",Z.body.className=V.body.className;const Y=V.documentElement.getAttribute("style");Y&&Z.documentElement.setAttribute("style",Y);const se=Z.getElementById("dv-popout-window");se instanceof HTMLElement&&(se.classList.add("adhdev-dockview"),La(se,A))},[A]),ue=i.useCallback(()=>{var V;const U=N.current;if(U)for(const Z of U.groups)try{const ae=(V=Z.element)==null?void 0:V.ownerDocument;if(!ae||ae===document)continue;const K=ae.getElementById("dv-popout-window");K instanceof HTMLElement&&(K.classList.add("adhdev-dockview"),La(K,A));const Y=document.documentElement.getAttribute("data-theme");Y&&ae.documentElement.setAttribute("data-theme",Y),ae.documentElement.style.colorScheme=Y==="light"?"light":"dark",ae.body.className=document.body.className;const se=document.documentElement.getAttribute("style");se?ae.documentElement.setAttribute("style",se):ae.documentElement.removeAttribute("style")}catch{}},[A]),Se=i.useCallback(U=>{const V=N.current;if(!V)return;const Z=V.getPanel(U);Z&&V.addPopoutGroup(Z,{popoutUrl:"/popout.html",onDidOpen:({window:ae})=>{ne(ae),me();const K=G.get(U);ae.document.title=K?`${ut(K)} — ADHDev`:"ADHDev — Popout"}})},[G,ne]),ve=i.useCallback(U=>{const V=N.current,Z=V==null?void 0:V.getPanel(U);if(!V||!Z)return;const ae=V.groups.filter(K=>{var Y;try{return((Y=K.element)==null?void 0:Y.ownerDocument)===document}catch{return!0}});ae.length>0?Z.api.moveTo({group:ae[0],position:"center"}):Z.api.moveTo({position:"center"}),Z.api.setActive()},[]),X=i.useCallback(U=>{var ae;const V=N.current;if(!V)return!1;const Z=V.getPanel(U);if(!Z)return!1;try{return((ae=Z.group.element)==null?void 0:ae.ownerDocument)!==document}catch{return!1}},[]),xe=i.useCallback(U=>{X(U)&&ve(U),u(U)},[X,ve,u]),fe=i.useCallback(U=>{const V=N.current,Z=V==null?void 0:V.getPanel(U);!V||!Z||V.addFloatingGroup(Z,{width:600,height:500})},[]),we=i.useCallback(U=>{var Z;const V=(Z=N.current)==null?void 0:Z.getPanel(U);if(!V)return!1;try{return V.group.model.location.type==="floating"}catch{return!1}},[]),be=i.useCallback(()=>{var V,Z;const U=(Z=(V=N.current)==null?void 0:V.activePanel)==null?void 0:Z.id;return!U||Bt(U)?null:G.has(U)?U:null},[G]),Ce=i.useCallback(U=>{const V=N.current,Z=V==null?void 0:V.getPanel(U);if(!V||!Z)return;const ae=V.groups.filter(K=>{try{return K.model.location.type==="grid"}catch{return!0}});ae.length>0?Z.api.moveTo({group:ae[0],position:"center"}):Z.api.moveTo({position:"center"}),Z.api.setActive()},[]),ee=i.useCallback(()=>{var Y;const U=N.current;if(!U)return;const Z=U.groups.filter(se=>{var oe;try{return((oe=se.element)==null?void 0:oe.ownerDocument)===document&&se.model.location.type==="grid"}catch{return!1}})[0]||null,ae=[...U.panels];for(const se of ae){const oe=(Y=se.group.element)==null?void 0:Y.ownerDocument,ke=se.group.model.location.type;oe===document&&ke==="grid"||(Z&&Z.id!==se.group.id?se.api.moveTo({group:Z,position:"center"}):se.api.moveTo({position:"center"}))}const K=U.activePanel;K&&(K.group.model.openPanel(K),K.api.setActive()),_a(document)},[]),me=i.useCallback(()=>{var V,Z;const U=N.current;if(U)for(const ae of U.groups){const K=(V=ae.element)==null?void 0:V.ownerDocument;if(!K||K===document)continue;const Y=K.getElementById("dv-popout-window");if(!(Y instanceof HTMLElement))continue;let se=null,oe=K.title||"ADHDev",ke="Popout workspace";const Pe=ae.activePanel;if(Pe)if(se=Pe.id,Bt(Pe.id)){const Me=((Z=Pe.params)==null?void 0:Z.routeId)||Pe.id.slice(7),Qe=Wt([...G.values()],Me);oe=ud(Qe),ke=Qe!=null&&Qe.machineName?`Remote view · ${Qe.machineName}`:"Remote view"}else{const Me=G.get(Pe.id);oe=Me?ut(Me):Pe.title||Pe.id,ke=Me?bs(Me):"Dockview panel"}K.title=`${oe} — ADHDev`;const Ee=Array.from(K.querySelectorAll("#adhdev-popout-header"));for(const Me of Ee)Me.remove();const Ae=K.createElement("div");Ae.id="adhdev-popout-header",K.body.appendChild(Ae),Ae.setAttribute("style",["position:absolute","top:0","left:0","right:0","height:52px","display:flex","align-items:center","justify-content:space-between","gap:12px","padding:0 14px","box-sizing:border-box","background:var(--surface-secondary)","border-bottom:1px solid var(--border-subtle)","z-index:5","backdrop-filter:blur(14px)"].join(";")),Ae.innerHTML=`
|
|
55
55
|
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
56
56
|
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
57
57
|
<div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Il(oe)}</div>
|
|
@@ -61,38 +61,38 @@ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Mach
|
|
|
61
61
|
<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>
|
|
62
62
|
<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>
|
|
63
63
|
</div>
|
|
64
|
-
`,Y.style.top="52px",Y.style.height="calc(100% - 52px)";const $e=Ae.querySelector("[data-adhdev-popout-focus]");$e&&($e.onclick=()=>{window.focus()});const Fe=Ae.querySelector("[data-adhdev-popout-dock]");Fe&&(Fe.disabled=!se,Fe.style.opacity=se?"1":"0.5",Fe.style.cursor=se?"pointer":"default",Fe.onclick=()=>{var Me;se&&ve(se),(Me=K.defaultView)==null||Me.focus()})}},[G,ve]),ie=i.useCallback(U=>{var ae;const V=N.current,Z=V==null?void 0:V.getPanel(U);if(!(!V||!Z)){Z.group.model.openPanel(Z),Z.api.setActive(),he(U,"dockview-shortcut");try{const K=Z.group.model.location;K.type==="popout"?K.getWindow().focus():_a((ae=Z.group.element)==null?void 0:ae.ownerDocument)}catch{}}},[he]),pe=i.useCallback(U=>{const V=N.current,Z=V==null?void 0:V.activePanel,ae=(V==null?void 0:V.activeGroup)||(Z==null?void 0:Z.group);if(!V||!Z||!ae)return;const K=ae.panels||[];if(K.length<=1)return;const Y=K.findIndex(ke=>ke.id===Z.id);if(Y<0)return;const se=(Y+U+K.length)%K.length,oe=K[se];oe&&(oe.group.model.openPanel(oe),oe.api.setActive(),Bt(oe.id)||he(oe.id,"dockview-shortcut"))},[he]),le=i.useCallback(U=>{var $e;const V=N.current,Z=(V==null?void 0:V.activeGroup)||(($e=V==null?void 0:V.activePanel)==null?void 0:$e.group);if(!V||!Z)return;const ae=V.groups||[],K=ae.find(Fe=>Fe.id===Z.id);if(!K)return;const Y=K.element.getBoundingClientRect(),se=Y.left+Y.width/2,oe=Y.top+Y.height/2,ke=(Fe,Me,Qe,et)=>Math.max(0,Math.min(Me,et)-Math.max(Fe,Qe)),Pe=Fe=>{const Me=Fe.element.getBoundingClientRect(),Qe=Me.left+Me.width/2,et=Me.top+Me.height/2;let bt=0,gt=0,dt=0,ht=!1;if(U==="left"?(ht=Qe<se,bt=Math.max(0,Y.left-Me.right),gt=Math.abs(et-oe),dt=ke(Y.top,Y.bottom,Me.top,Me.bottom)):U==="right"?(ht=Qe>se,bt=Math.max(0,Me.left-Y.right),gt=Math.abs(et-oe),dt=ke(Y.top,Y.bottom,Me.top,Me.bottom)):U==="above"?(ht=et<oe,bt=Math.max(0,Y.top-Me.bottom),gt=Math.abs(Qe-se),dt=ke(Y.left,Y.right,Me.left,Me.right)):(ht=et>oe,bt=Math.max(0,Me.top-Y.bottom),gt=Math.abs(Qe-se),dt=ke(Y.left,Y.right,Me.left,Me.right)),!ht)return Number.POSITIVE_INFINITY;const Ue=dt>0?0:120;return bt*3+gt+Ue};let Ee=null,Ae=Number.POSITIVE_INFINITY;for(const Fe of ae){if(Fe.id===K.id)continue;const Me=Pe(Fe);Number.isFinite(Me)&&(Me>=Ae||(Ae=Me,Ee=Fe))}return Ee||void 0},[]),B=i.useCallback(U=>{var ae;const V=le(U);if(!V)return;const Z=V.activePanel||V.panels[0];Z&&(V.model.openPanel(Z),Z.api.setActive(),Bt(Z.id)||he(Z.id,"dockview-focus"),_a((ae=V.element)==null?void 0:ae.ownerDocument))},[le,he]),z=i.useCallback((U,V)=>{const Z=N.current,ae=Z==null?void 0:Z.activePanel,K=(Z==null?void 0:Z.activeGroup)||(ae==null?void 0:ae.group);if(!Z||!ae||!K)return;let Y=le(U);!Y&&(V!=null&&V.createGroupIfMissing)&&(Y=Z.addGroup({referenceGroup:K,direction:U})),Y&&(ae.api.moveTo({group:Y,position:"center"}),ae.group.model.openPanel(ae),ae.api.setActive(),Bt(ae.id)||he(ae.id,V!=null&&V.createGroupIfMissing?"dockview-split":"dockview-move"))},[le,he]),{isMac:de,tabShortcuts:re,shortcutListening:R,setShortcutListening:q,saveShortcuts:ce}=nu({sortedTabKeys:e.map(U=>U.tabKey),onFocus:ye,onSelectTab:ie}),Ne=i.useCallback(()=>{var Z;const U=N.current;if(!U)return;const V=U.activePanel;if(V){if(Bt(V.id)){const ae=((Z=V.params)==null?void 0:Z.routeId)||V.id.slice(7),K=Wt(e,ae);K!=null&&K.tabKey&&q(K.tabKey);return}G.has(V.id)&&q(V.id)}},[G,ie,q,e]),je=i.useCallback(U=>{const V=[];return U.metaKey&&V.push(de?"⌘":"Meta"),U.ctrlKey&&V.push("Ctrl"),U.altKey&&V.push(de?"⌥":"Alt"),U.shiftKey&&U.key.length!==1&&V.push(de?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(U.key)?null:(V.push(lu(U.key)),V.join("+"))},[de]),O=i.useCallback(U=>{var V,Z;switch(U){case"splitActiveTabRight":z("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":z("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const ae=be();ae&&fe(ae);return}case"popoutActiveTab":{const ae=be();ae&&Se(ae);return}case"dockActiveTab":{const ae=be();if(!ae)return;X(ae)?ve(ae):we(ae)&&Ce(ae);return}case"focusLeftPane":B("left");return;case"focusRightPane":B("right");return;case"focusUpPane":B("above");return;case"focusDownPane":B("below");return;case"moveActiveTabToLeftPane":z("left");return;case"moveActiveTabToRightPane":z("right");return;case"moveActiveTabToUpPane":z("above");return;case"moveActiveTabToDownPane":z("below");return;case"selectPreviousGroupTab":pe(-1);return;case"selectNextGroupTab":pe(1);return;case"setActiveTabShortcut":Ne();return;case"hideCurrentTab":{const ae=(Z=(V=N.current)==null?void 0:V.activePanel)==null?void 0:Z.id;ae&&!Bt(ae)&&xe(ae);return}default:return}},[pe,Ce,B,fe,be,xe,we,X,ve,z,Se,Ne]);i.useEffect(()=>{if(!C)return;const U=C.sourceDocument,V=U.defaultView??window,Z=ae=>{const K=U.querySelector("[data-dockview-tab-context-menu]");K&&K.contains(ae.target)||y(null)};return V.addEventListener("mousedown",Z,!0),V!==window&&window.addEventListener("mousedown",()=>y(null),!0),()=>{V.removeEventListener("mousedown",Z,!0),V!==window&&window.removeEventListener("mousedown",()=>y(null),!0)}},[C]);const Ie=i.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:G,hasDetachedConversationPanels:J,ides:r,isStandalone:l,hasRegisteredMachines:c,onOpenNewSession:b,liveSessionInboxState:I,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:xe,userName:m,scrollToBottomRequest:T,tabShortcuts:re,openTabContextMenu:({x:U,y:V,tabKey:Z,sourceDocument:ae})=>y({x:U,y:V,tabKey:Z,sourceDocument:ae??document}),popoutTab:Se,moveTabBackToMain:ve,isTabInPopout:X,floatTab:fe,isTabFloating:we}),[n,t,G,J,r,l,c,b,I,a,o,xe,m,T,re,Se,ve,X,fe,we]),Le=C?Ty({isTabInPopout:X(C.tabKey),isTabFloating:we(C.tabKey),tabShortcut:re[C.tabKey],actionShortcuts:h}):[],He=i.useCallback(U=>{var ae;const V=N.current;if((((ae=V==null?void 0:V.activePanel)==null?void 0:ae.id)??null)===U.id){U.group.model.openPanel(U);return}U.group.model.openPanel(U),U.api.setActive()},[]),ze=i.useCallback((U,V="requested-tab")=>{if(!U)return!1;const Z=N.current;if(!Z)return!1;const ae=Z.getPanel(U);return ae?(He(ae),he(U,V),f==null||f(),!0):!1},[He,f,he]),Xe=i.useCallback(()=>{if(W.current)return!1;const U=ze(H.current,"stored-layout-restore");return U&&(W.current=!0),U},[ze]),Je=i.useCallback(()=>{var V;const U=N.current;U&&ag(k,{activeTabId:((V=U.activePanel)==null?void 0:V.id)??null,layout:U.toJSON()})},[k]),rt=i.useCallback(()=>{ig(k,E.current)},[k]),pt=i.useCallback(U=>{var ae,K,Y,se;const V=N.current;if(!V)return{kind:"grid"};const Z=V.toJSON();for(const oe of Z.floatingGroups||[])if((K=(ae=oe.data)==null?void 0:ae.views)!=null&&K.includes(U)&&oe.position)return{kind:"floating",position:oe.position};for(const oe of Z.popoutGroups||[])if((se=(Y=oe.data)==null?void 0:Y.views)!=null&&se.includes(U))return{kind:"popout",position:oe.position,popoutUrl:oe.url};return{kind:"grid"}},[]),xt=i.useCallback(U=>{const V=N.current;if(!V)return;const Z=V.getPanel(U),ae=E.current[U];if(!Z||!ae||ae.kind==="grid")return;if(Z.group.model.location.type===ae.kind){delete E.current[U],rt();return}if(ae.kind==="floating"){V.addFloatingGroup(Z,{x:ae.position.left??24,y:ae.position.top??24,width:ae.position.width,height:ae.position.height}),delete E.current[U],rt();return}delete E.current[U],rt()},[rt]);i.useEffect(()=>(x==null||x({setShortcutForActiveTab:Ne,restoreHiddenTabToSavedLocation:xt,activateConversationTab:ie,resetAllPanelsToMain:ee,activatePreviousTabInGroup:()=>pe(-1),activateNextTabInGroup:()=>pe(1),floatActiveTab:()=>{const U=be();U&&fe(U)},popoutActiveTab:()=>{const U=be();U&&Se(U)},dockActiveTab:()=>{const U=be();U&&(X(U)?ve(U):we(U)&&Ce(U))},splitActiveTabRight:()=>z("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>z("below",{createGroupIfMissing:!0}),focusLeftPane:()=>B("left"),focusRightPane:()=>B("right"),focusUpPane:()=>B("above"),focusDownPane:()=>B("below"),moveActiveTabToLeftPane:()=>z("left"),moveActiveTabToRightPane:()=>z("right"),moveActiveTabToUpPane:()=>z("above"),moveActiveTabToDownPane:()=>z("below")}),()=>x==null?void 0:x(null)),[pe,Ce,fe,B,be,we,X,z,ve,Se,x,ee,xt,ie,Ne]),i.useEffect(()=>()=>{var U;(U=D.current)==null||U.call(D),D.current=null},[]);const vt=i.useCallback(U=>{var Z,ae;N.current=U.api,(Z=D.current)==null||Z.call(D),D.current=null;const V=ng(k);if(H.current=(V==null?void 0:V.activeTabId)??null,V!=null&&V.layout&&U.api.fromJSON(V.layout,{reuseExistingPanels:!1}),j.current=kl({hasStoredLayout:!!(V!=null&&V.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),j.current||(Ml(U.api,e),Al(U.api,e,v)),U.api.totalPanels===0&&e.length>0){const K=Ey(U.api,e,g);if(K){const Y=U.api.getPanel(K);Y&&He(Y)}}else!j.current&&!ze(g)&&Xe();if(M.current=!0,U.api.onDidActivePanelChange(K=>{var se;if(H.current=(K==null?void 0:K.id)??null,W.current=!0,me(),K&&Bt(K.id)){const oe=((se=K.params)==null?void 0:se.routeId)||K.id.slice(7),ke=Wt(e,oe);S((ke==null?void 0:ke.tabKey)??null),Je();return}if(S((K==null?void 0:K.id)??null),Je(),!K)return;const Y=G.get(K.id);(Y==null?void 0:Y.streamSource)==="agent-stream"&&Y.agentType&&_(Y.routeId,Gc(),{agentType:Y.agentType,...Y.sessionId&&{targetSessionId:Y.sessionId}}).catch(()=>{})}),U.api.onDidLayoutChange(()=>{Je(),me(),P(K=>K+1)}),Ly()){const K=Ae=>({clientX:Ae.clientX,clientY:Ae.clientY}),Y=Ae=>{const $e=Ae==null?void 0:Ae.getBoundingClientRect();return $e?{left:$e.left,right:$e.right,top:$e.top,bottom:$e.bottom}:null},se=Ae=>{var Fe;const $e=(Fe=w.current)==null?void 0:Fe.getBoundingClientRect();return $e?Ae.clientX<$e.left||Ae.clientX>$e.right||Ae.clientY<$e.top||Ae.clientY>$e.bottom:!1},oe=_y({detachDelayMs:du,onDetach:({panelId:Ae,clientX:$e,clientY:Fe})=>{var dt,ht;const Me=U.api.getPanel(Ae);if(!Me)return;try{if(Me.group.model.location.type!=="grid")return}catch{return}const Qe=(dt=w.current)==null?void 0:dt.getBoundingClientRect(),et=(ht=Me.group.element)==null?void 0:ht.getBoundingClientRect(),bt=Math.round(Math.min(Math.max((et==null?void 0:et.width)??600,360),720)),gt=Math.round(Math.min(Math.max((et==null?void 0:et.height)??500,260),640));U.api.addFloatingGroup(Me,{x:Qe?Math.max(0,$e-Qe.left-32):void 0,y:Qe?Math.max(0,Fe-Qe.top-18):void 0,width:bt,height:gt}),Me.api.setActive(),Je(),me(),P(Ue=>Ue+1)}}),ke=[U.api.onWillDragPanel(Ae=>{if(!(Ae.nativeEvent.defaultPrevented||Ae.nativeEvent.shiftKey)){try{if(Ae.panel.group.model.location.type!=="grid")return}catch{return}oe.startDrag({panelId:Ae.panel.id,selfPanelBounds:Y(Ae.panel.group.element),...K(Ae.nativeEvent)})}}),U.api.onWillShowOverlay(Ae=>{if(oe.hasDetached()){Ae.preventDefault();return}oe.markDockTarget(K(Ae.nativeEvent))}),U.api.onWillDrop(Ae=>{if(oe.hasDetached()){Ae.preventDefault(),oe.endDrag();return}oe.markDockTarget(K(Ae.nativeEvent))}),U.api.onDidDrop(()=>oe.endDrag()),U.api.onUnhandledDragOverEvent(Ae=>{oe.isDragging()&&oe.markSelfPanel(K(Ae.nativeEvent))})],Pe=Ae=>{if(!oe.isDragging())return;const $e=K(Ae);se($e)&&oe.markNonSelfPanel($e)},Ee=()=>oe.endDrag();window.addEventListener("dragover",Pe,!0),window.addEventListener("drop",Ee,!0),window.addEventListener("dragend",Ee,!0),D.current=()=>{oe.dispose();for(const Ae of ke)Ae.dispose();window.removeEventListener("dragover",Pe,!0),window.removeEventListener("drop",Ee,!0),window.removeEventListener("dragend",Ee,!0)}}U.api.onDidAddGroup(K=>{requestAnimationFrame(()=>{var Y,se;try{const oe=(Y=K.element)==null?void 0:Y.ownerDocument;if(!oe||oe===document)return;(se=oe.getElementById("dv-popout-window"))==null||se.classList.add("adhdev-dockview");const ke=document.documentElement.getAttribute("data-theme");ke&&oe.documentElement.setAttribute("data-theme",ke),oe.body.className=document.body.className;const Pe=document.documentElement.getAttribute("style");Pe&&oe.documentElement.setAttribute("style",Pe)}catch{}me(),P(oe=>oe+1)})}),S(((ae=U.api.activePanel)==null?void 0:ae.id)??null)},[He,ze,G,r,d,k,S,Je,g,v,_,me,e]);i.useLayoutEffect(()=>{const U=N.current;if(!U||!M.current||j.current&&kl({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;j.current&&(j.current=!1);const V=$.current,Z=new Set(V),ae=e.map(Ee=>Ee.tabKey),K=new Set(ae),Y=My({previousVisibleConversationCount:V.length,visibleConversationCount:e.length,ides:r});let se=!1;for(const Ee of V)K.has(Ee)||Y||(E.current[Ee]=pt(Ee),se=!0);se&&rt(),Y||(Ml(U,e),Al(U,e,v));const oe=ae.filter(Ee=>!Z.has(Ee));let ke=!1;for(const Ee of oe){const Ae=U.getPanel(Ee),$e=E.current[Ee];if(!Ae||!$e||$e.kind==="grid")continue;if(Ae.group.model.location.type===$e.kind){delete E.current[Ee],ke=!0;continue}if($e.kind==="floating"){U.addFloatingGroup(Ae,{x:$e.position.left??24,y:$e.position.top??24,width:$e.position.width,height:$e.position.height}),delete E.current[Ee],ke=!0;continue}}if(ke&&rt(),$.current=ae,g&&ze(g))return;!U.activePanel&&U.panels[0]&&He(U.panels[0]),!!(U.activePanel&&U.getPanel(U.activePanel.id))||Xe()},[He,ze,Xe,r,d,rt,pt,g,v,e]),i.useEffect(()=>{M.current&&ze(g)},[ze,g]),i.useEffect(()=>{const U=Z=>{const ae=Z.target;if(!ae)return;const K=ae.querySelector("[data-tab-key]")||ae.closest("[data-tab-key]");if(K){const Y=K.getAttribute("data-tab-key");if(Y&&Z.dataTransfer){const se=ae.closest(".dv-tab")||K.closest(".dv-tab")||K;Z.dataTransfer.effectAllowed="move",Z.dataTransfer.setData("text/tab-key",Y),se instanceof HTMLElement&&Z.dataTransfer.setDragImage(se,Math.max(12,Math.round(se.clientWidth/2)),Math.max(10,Math.round(se.clientHeight/2)))}}};window.addEventListener("dragstart",U);const V=Tl(N.current);for(const Z of V)Z.addEventListener("dragstart",U);return()=>{window.removeEventListener("dragstart",U);for(const Z of V)Z.removeEventListener("dragstart",U)}},[F]),i.useEffect(()=>{var V;const U=(V=w.current)==null?void 0:V.querySelector(".adhdev-dockview");U instanceof HTMLElement&&La(U,A),ue(),me()},[me,ue,A]),i.useEffect(()=>{me()},[me]),i.useEffect(()=>{const U=V=>{if(V.defaultPrevented||R)return;const Z=je(V);if(!Z)return;const ae=V.metaKey||V.ctrlKey||V.altKey;wo(V.target)&&!ae||On(de).setActiveTabShortcut!==Z||(V.preventDefault(),V.stopPropagation(),Ne())};return window.addEventListener("keydown",U,!0),()=>window.removeEventListener("keydown",U,!0)},[je,de,R,Ne]),i.useEffect(()=>{const U=w.current;if(!U)return;const V=Z=>{var oe,ke;if(!Z.isTrusted)return;const ae=(ke=(oe=Z.target)==null?void 0:oe.closest)==null?void 0:ke.call(oe,".dv-scrollable");if(!ae)return;Z.preventDefault(),Z.stopPropagation();const K=Math.abs(Z.deltaX),Y=Math.abs(Z.deltaY),se=K>Y?Z.deltaX:Z.deltaY;ae.dispatchEvent(new WheelEvent("wheel",{deltaY:se,deltaMode:Z.deltaMode,bubbles:!1,cancelable:!0}))};return U.addEventListener("wheel",V,{passive:!1,capture:!0}),()=>U.removeEventListener("wheel",V,{capture:!0})},[]),i.useEffect(()=>{const U=Tl(N.current);if(U.length===0)return;const V=U.map(Z=>{let ae=[],K=null;const Y=()=>{K!=null&&Z.clearTimeout(K),K=null,ae=[]},se=()=>{K!=null&&Z.clearTimeout(K),K=Z.setTimeout(()=>{K=null,ae=[]},1200)},oe=Pe=>{if(!Pe.ctrlKey&&!Pe.metaKey&&!Pe.altKey)return;const Ee=je(Pe);if(!Ee)return;const Ae=ru();for(const[$e,Fe]of Object.entries(Ae))if(e.some(Me=>Me.tabKey===$e)&&Fe===Ee){Pe.preventDefault(),ie($e);return}},ke=Pe=>{if(Pe.defaultPrevented||R)return;const Ee=je(Pe);if(!Ee)return;const Ae=Pe.metaKey||Pe.ctrlKey||Pe.altKey;if(wo(Pe.target))return;const $e=On(de),Fe=Object.entries($e).filter(([Ue,Kt])=>!!Kt&&(Ue==="splitActiveTabRight"||Ue==="splitActiveTabDown"||Ue==="floatActiveTab"||Ue==="popoutActiveTab"||Ue==="dockActiveTab"||Ue==="focusLeftPane"||Ue==="focusRightPane"||Ue==="focusUpPane"||Ue==="focusDownPane"||Ue==="moveActiveTabToLeftPane"||Ue==="moveActiveTabToRightPane"||Ue==="moveActiveTabToUpPane"||Ue==="moveActiveTabToDownPane"||Ue==="selectPreviousGroupTab"||Ue==="selectNextGroupTab"||Ue==="setActiveTabShortcut"||Ue==="hideCurrentTab")),Me=Ae?[Ee]:[...ae.slice(-1),Ee].slice(-2),Qe=Me.join(" "),et=Me[Me.length-1],bt=Fe.find(([,Ue])=>Ue===Qe);if(bt){Pe.preventDefault(),Y(),O(bt[0]);return}if(Fe.some(([,Ue])=>Ue.startsWith(`${Qe} `))){Pe.preventDefault(),ae=Me,se();return}const dt=Fe.find(([,Ue])=>Ue===et);if(dt){Pe.preventDefault(),Y(),O(dt[0]);return}if(Fe.some(([,Ue])=>Ue.startsWith(`${et} `))){Pe.preventDefault(),ae=[et],se();return}Y()};return Z.addEventListener("keydown",oe),Z.addEventListener("keydown",ke),()=>{Y(),Z.removeEventListener("keydown",oe),Z.removeEventListener("keydown",ke)}});return()=>{for(const Z of V)Z()}},[je,de,F,ie,R,O,e]);const Te=A==="light"?eo:to,Ve=((ot=(Ge=(tt=N.current)==null?void 0:tt.activePanel)==null?void 0:Ge.group.element)==null?void 0:ot.ownerDocument)??document;return s.jsxs(uu.Provider,{value:Ie,children:[s.jsx("div",{ref:w,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(pm,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:$y,remote:By},defaultTabComponent:Fy,watermarkComponent:Oy,onReady:vt,singleTabMode:"default",tabAnimation:"smooth",theme:Te,popoutUrl:"/popout.html"})}),C&&Tr.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:C.x,top:C.y},children:Le.map(U=>{if(U.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},U.id);let V=s.jsx(xp,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{};switch(U.id){case"dockInWindow":case"dockBackToGrid":V=s.jsx(gp,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{Ce(C.tabKey),y(null)};break;case"moveBackToMain":V=s.jsx(fp,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{ve(C.tabKey),y(null)};break;case"floatAsPanel":V=s.jsx(bp,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{fe(C.tabKey),y(null)};break;case"openInNewWindow":V=s.jsx(hp,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{Se(C.tabKey),y(null)};break;case"setShortcut":Z=ae=>{ae.stopPropagation(),q(C.tabKey),y(null)};break;case"removeShortcut":V=s.jsx(wt,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{const ae={...re};delete ae[C.tabKey],ce(ae),y(null)};break;case"hideTab":V=s.jsx(Lo,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{xe(C.tabKey),y(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 ${U.tone==="muted"?"text-text-muted":""}`,onMouseDown:Py,onClick:Z,children:[V,s.jsx("span",{className:"flex-1 min-w-0",children:U.label}),U.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:U.shortcut}):null]},U.id)})}),C.sourceDocument.body),R&&Tr.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:()=>q(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:U=>U.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. ",de?"⌘+1":"Ctrl+1",", ",de?"⌥+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"})]})}),Ve.body)]})}const mu="adhdev-recent-launch-args-v1",Ky=8;function pu(e){return String(e||"").trim().replace(/\s+/g," ")}function di(e,t){return`${e.trim()}::${t.trim()}`}function ui(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(mu)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function hu(e){if(!(typeof window>"u"))try{window.localStorage.setItem(mu,JSON.stringify(e))}catch{}}function jo(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=ui().byKey[di(r,n)])==null?void 0:o.items)||[]}function fu(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=pu(r);if(!n||!a||!o)return;const l=ui(),c=di(n,a),d=((u=l.byKey[c])==null?void 0:u.items)||[],m=[o,...d.filter(h=>h!==o)].slice(0,Ky);l.byKey[c]={items:m},hu(l)}function Hy(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=pu(r);if(!n||!a||!o)return;const l=ui(),c=di(n,a),m=(((u=l.byKey[c])==null?void 0:u.items)||[]).filter(h=>h!==o);m.length>0?l.byKey[c]={items:m}:delete l.byKey[c],hu(l)}function xu(e){return!e.hasLoadedInitialResults&&!e.isLoading}function wn({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 Uy({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 bu({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:l,onOpenHistory:c,onClearSelection:d}){const m=o?eu(o):null,u=Uy({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(wn,{title:"Saved history",description:Jo(),action:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:l,children:t?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:c,children:_x()})]}),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:d,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:u}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function gu({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 zy({workspaceMode:e,activeKind:t,cliEnabled:r,ideEnabled:n,acpEnabled:a,busy:o,onSelect:l}){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:"IDE",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:()=>l(c.id),disabled:!c.enabled||o,children:c.label},c.id))})]})}function Ra(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>Ts(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>Ts(a,"acp"))?"acp":null}function on(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Vy({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:l,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var Ue,Kt;const u=Er(),h=i.useMemo(()=>[...e].sort(Fo),[e]),[x,S]=i.useState(((Ue=h[0])==null?void 0:Ue.id)||""),b=i.useMemo(()=>h.find(te=>te.id===x)||h[0],[x,h]),p=i.useMemo(()=>((b==null?void 0:b.workspaces)||[]).map(te=>({id:te.id,path:te.path,label:te.label})),[b]),g=(b==null?void 0:b.defaultWorkspaceId)||null,[v,f]=i.useState("workspace"),[T,I]=i.useState(""),[k,A]=i.useState(""),[_,N]=i.useState([]),[w,D]=i.useState(""),[M,j]=i.useState(!1),[W,H]=i.useState(null),[$,C]=i.useState(""),[y,F]=i.useState(Ra(h[0])),[P,E]=i.useState(""),[G,J]=i.useState(""),[ye,he]=i.useState([]),[ne,ue]=i.useState(""),[Se,ve]=i.useState([]),[X,xe]=i.useState(!1),[fe,we]=i.useState(!1),[be,Ce]=i.useState(""),[ee,me]=i.useState(!1),[ie,pe]=i.useState(()=>Ct()),[le,B]=i.useState(null),[z,de]=i.useState(!1),[re,R]=i.useState(""),[q,ce]=i.useState(null),[Ne,je]=i.useState(!1),[O,Ie]=i.useState(""),[Le,He]=i.useState([]),[ze,Xe]=i.useState(!1),[Je,rt]=i.useState(""),[pt,xt]=i.useState(!1),vt=i.useRef(null),Te=i.useRef(0);i.useEffect(()=>{var te;!x&&((te=h[0])!=null&&te.id)&&S(h[0].id)},[x,h]),i.useEffect(()=>{!b||!(!b.workspaces||!b.availableProviders||!b.detectedIdes||!b.recentLaunches)||u(b.id,{minFreshMs:3e4}).catch(()=>{})},[u,b]);const Ve=i.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(te=>Ts(te,"cli")),[b]),tt=i.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(te=>Ts(te,"acp")),[b]),Ge=i.useMemo(()=>((b==null?void 0:b.detectedIdes)||[]).map(te=>({id:te.type,label:te.name||te.type,meta:te.running?"Detected locally":"Available to open"})),[b]),ot=i.useMemo(()=>y==="cli"?Ve.map(te=>({id:te.type,label:te.displayName||te.type,meta:"CLI provider"})):y==="acp"?tt.map(te=>({id:te.type,label:te.displayName||te.type,meta:"ACP provider"})):Ge,[tt,y,Ve,Ge]),U=i.useMemo(()=>_.find(te=>te.id===w)||null,[_,w]),V=i.useMemo(()=>Ve.find(te=>te.type===P)||null,[Ve,P]),Z=i.useMemo(()=>Gd(V==null?void 0:V.meshCoordinator,{meshId:(U==null?void 0:U.id)||"",workspace:(U==null?void 0:U.workspace)||""}),[V,U]),ae=q||Z,K=i.useCallback(async te=>{j(!0),C("");try{const De=await c(te);N(De),D(L=>{var Q;return De.some(ge=>ge.id===L)?L:((Q=De[0])==null?void 0:Q.id)||""}),H(te)}catch(De){N([]),D(""),H(te),C(De instanceof Error?De.message:"Could not load meshes")}finally{j(!1)}},[c]);i.useEffect(()=>{var De;if(!b)return;if(vt.current!==b.id){vt.current=b.id,f("workspace"),I(g||((De=p[0])==null?void 0:De.id)||"__home__"),A(""),N([]),D(""),H(null),C(""),F(Ra(b)),E(""),J(""),ue(""),ve([]),we(!1),Ce(""),pe(Ct()),R(""),ce(null);return}I(L=>{var Q;return L==="__custom__"||L==="__home__"||p.some(ge=>ge.id===L)?L:g||((Q=p[0])==null?void 0:Q.id)||"__home__"}),F(L=>L==="ide"&&Ge.length>0||L==="cli"&&Ve.length>0||L==="acp"&&tt.length>0?L:Ra(b))},[tt.length,Ve.length,g,Ge.length,b,p]),i.useEffect(()=>{!b||v!=="mesh"||W===b.id||M||K(b.id)},[K,W,M,b,v]),i.useEffect(()=>{v==="mesh"&&y!=="cli"&&Ve.length>0&&F("cli")},[y,Ve.length,v]),i.useEffect(()=>{var te;y&&(ot.some(De=>De.id===P)||E(((te=ot[0])==null?void 0:te.id)||""))},[y,ot,P]),i.useEffect(()=>{ce(null)},[b==null?void 0:b.id,w,P,v]);const Y=i.useCallback(async(te,De)=>{const L=Te.current+1;return Te.current=L,xe(!0),Ce(""),m(te,De).then(Q=>{Te.current===L&&ve(Q)}).catch(Q=>{Te.current===L&&(ve([]),Ce(Q instanceof Error?Q.message:"Could not load saved sessions"))}).finally(()=>{Te.current===L&&(xe(!1),we(!0))})},[m]),se=i.useCallback((te,De)=>{he(jo(te,De))},[]);i.useEffect(()=>{Te.current+=1,ue(""),pe(Ct()),!b||!P||y==="ide"?he([]):se(b.id,P),we(!1),ve([]),Ce(""),xe(!1)},[y,se,Y,b,P]),i.useEffect(()=>{if(!ne)return;const te=Se.find(De=>De.providerSessionId===ne);te!=null&&te.canResume||ue("")},[Se,ne]);const oe=T==="__custom__"?k.trim():T==="__home__"?"":((Kt=p.find(te=>te.id===T))==null?void 0:Kt.path)||"",ke=i.useMemo(()=>b?t.filter(te=>te.id!==b.id&&te.daemonId===b.id).map(te=>te.workspace):[],[t,b]),Pe=i.useMemo(()=>((b==null?void 0:b.recentLaunches)||[]).map(te=>te.workspace),[b]),Ee=i.useCallback(te=>{const De=String(te.workspace||"").trim();if(!De)return;const L=p.find(Q=>on(Q.path)===on(De));if(L){I(L.id),A("");return}I("__custom__"),A(De)},[p]),Ae=i.useCallback(te=>{const De=String(te.workspace||"").trim();if(!De)return{workspaceId:null,workspacePath:null};const L=p.find(Q=>on(Q.path)===on(De));return L?{workspaceId:L.id,workspacePath:null}:{workspaceId:null,workspacePath:De}},[p]),$e=i.useMemo(()=>Se.find(te=>te.providerSessionId===ne)||null,[Se,ne]),Fe=i.useMemo(()=>{var De;if(y!=="cli"||!b||!P)return null;const te=((De=Ve.find(L=>L.type===P))==null?void 0:De.displayName)||P;return{routeId:b.id,daemonId:b.id,providerSessionId:ne||void 0,transport:"pty",mode:"chat",agentName:te,agentType:P,status:"idle",title:te,messages:[],ideType:P,workspaceName:oe,workspacePath:oe,displayPrimary:te,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${b.id}:${P}`,machineName:At(b,{fallbackId:b.id})}},[y,Ve,oe,b,ne,P]),Me=i.useCallback(()=>{var De;if(!b)return;I("__custom__"),je(!0),rt("");const te=Qn(b.platform,Jn(k.trim(),oe,ke,Pe,b.defaultWorkspacePath,(De=p.find(L=>L.id===g))==null?void 0:De.path,p.map(L=>L.path)));Xe(!0),n(b.id,te).then(L=>{Ie(L.path),A(L.path),He(L.directories)}).catch(L=>{rt(L instanceof Error?L.message:"Could not load folder")}).finally(()=>Xe(!1))},[k,g,Pe,ke,n,oe,b,p]),Qe=i.useCallback(te=>{b&&(Xe(!0),rt(""),n(b.id,te).then(De=>{Ie(De.path),A(De.path),He(De.directories)}).catch(De=>{rt(De instanceof Error?De.message:"Could not load folder")}).finally(()=>Xe(!1)))},[n,b]),et=i.useCallback(async()=>{if(!b||!oe)return;xt(!0),R("");const te=await a(b.id,oe);if(xt(!1),!te.ok){R(te.error||"Could not save workspace");return}R("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,oe,b]),bt=i.useCallback(async()=>{if(!b)return;if(v==="mesh"){if(!w||!P)return;de(!0),R(""),ce(null);const L=await d(b.id,w,P);if(de(!1),!L.ok){if(L.code==="mesh_coordinator_manual_mcp_setup_required"&&L.manualSetup){ce(L.manualSetup),R("Manual MCP setup required before this provider can act as mesh coordinator.");return}R(L.error||"Could not start mesh coordinator");return}r();return}if(!y||!P)return;de(!0),R("");const te=G.trim()?G.trim().split(/\s+/).filter(Boolean):[],De=y==="ide"?await o(b.id,P,{workspacePath:oe||null}):await l(b.id,y,P,{workspaceId:T!=="__home__"&&T!=="__custom__"?T:null,workspacePath:T==="__custom__"&&oe||null,resumeSessionId:y==="cli"&&ne?ne:null,cliArgs:te});if(de(!1),!De.ok){R(De.error||"Could not start session");return}y!=="ide"&&G.trim()&&(fu(b.id,P,G),se(b.id,P)),r()},[y,G,se,r,o,d,l,oe,b,w,ne,P,T,v]),gt=v==="mesh"?"Start mesh coordinator":y?pd(y,y==="cli"&&!!ne):"Start",dt=v==="mesh"?"Starting coordinator…":y?hd(y,y==="cli"&&!!ne):"Starting…",ht=h.length>5;return b?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(wt,{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:[s.jsx(wn,{title:"Machine",children:ht?s.jsx("select",{"aria-label":"Machine",value:b.id,onChange:te=>S(te.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:z,children:h.map(te=>s.jsx("option",{value:te.id,children:At(te,{fallbackId:te.id})},te.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:h.map(te=>{const De=At(te,{fallbackId:te.id}),L=b.id===te.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${De}`,"aria-pressed":L,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${L?"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:()=>S(te.id),disabled:z,title:De,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${te.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:De})]},te.id)})})}),s.jsxs(wn,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:v==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Me,disabled:z,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(te=>s.jsxs("button",{type:"button",role:"radio","aria-checked":v===te.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${v===te.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:()=>{f(te.id),R(""),te.id==="mesh"&&b&&W!==b.id&&!M&&K(b.id)},disabled:z,children:[s.jsx("div",{className:"text-sm font-semibold",children:te.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:te.desc})]},te.id))}),v==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:T,onChange:te=>{const De=te.target.value;I(De),De==="__custom__"?Me():R("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:z,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),p.map(te=>s.jsxs("option",{value:te.id,children:[te.id===g?"⭐ ":"",Vn(te.path,te.label)||te.path]},te.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:T==="__home__"?"Launch without a workspace.":oe||"Select a workspace folder."}),T==="__custom__"&&oe&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Me,disabled:z,children:[s.jsx(Ns,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:et,disabled:z||pt,children:pt?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[M&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!M&&$&&s.jsx("div",{className:"rounded-lg border border-status-error/25 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:$}),!M&&!$&&_.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."}),_.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:_.map(te=>s.jsxs("button",{type:"button",role:"radio","aria-checked":w===te.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${w===te.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>D(te.id),disabled:z,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:te.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[te.repoIdentity||"Repo mesh",typeof te.nodesCount=="number"?` · ${te.nodesCount} node${te.nodesCount===1?"":"s"}`:""]}),te.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",te.workspace]})]},te.id))}),U&&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(zy,{workspaceMode:v,activeKind:y,cliEnabled:Ve.length>0,ideEnabled:Ge.length>0,acpEnabled:tt.length>0,busy:z,onSelect:F}),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:y==="ide"?"Choose IDE":y==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[ot.map(te=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${P===te.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>E(te.id),disabled:z,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:te.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:te.meta})]},te.id)),ot.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."})]})]}),v==="mesh"&&ae&&s.jsx(gu,{setup:ae,providerName:(V==null?void 0:V.displayName)||(V==null?void 0:V.name)||P}),v!=="mesh"&&y!=="ide"&&s.jsxs(wn,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:G,onChange:te=>J(te.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:z}),ye.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:ye.map(te=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>J(te),disabled:z,title:te,children:te},te))})]}),v!=="mesh"&&y==="cli"&&s.jsx(bu,{busy:z,savedSessionsLoading:X,savedSessionsError:be,selectedSession:$e,onRefresh:()=>{!b||!P||Y(b.id,P)},onOpenHistory:()=>{!b||!P||(me(!0),xu({hasLoadedInitialResults:fe,isLoading:X})&&Y(b.id,P))},onClearSelection:()=>ue("")}),re&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${re.includes("saved")||re.includes("requested")||re.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:re})]}),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:z,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:bt,disabled:z||(v==="mesh"?!w||!P||y!=="cli"||M:!y||!P||T==="__custom__"&&!oe),children:[s.jsx(Po,{size:14}),z?dt:gt]})]})]})}),Ne&&s.jsx(ea,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:O,directories:Le,busy:ze,error:Je,onClose:()=>je(!1),onNavigate:Qe,onConfirm:te=>{A(te),Ie(te),I("__custom__"),je(!1)}}),ee&&Fe&&s.jsx(ei,{activeConv:Fe,ides:[],isCreatingChat:!1,isRefreshingHistory:X,savedSessions:Se,isSavedSessionsLoading:X,isResumingSavedSessionId:le,savedHistoryFilters:ie,missingWorkspaceResumePath:oe||null,onSavedHistoryFiltersChange:pe,onClose:()=>me(!1),onNewChat:()=>{ue(""),me(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!b||!P||Y(b.id,P)},onResumeSavedSession:te=>{if(!b||!P||le||!te.canResume)return;const De=Ae(te);ue(te.providerSessionId),Ee(te),B(te.providerSessionId),me(!1),de(!0),R(""),l(b.id,"cli",P,{workspaceId:De.workspaceId,workspacePath:De.workspacePath,resumeSessionId:te.providerSessionId}).then(L=>{if(!L.ok){R(L.error||"Could not resume session");return}r()}).finally(()=>{de(!1),B(L=>L===te.providerSessionId?null:L)})}})]}):null}const Gy=5*60*1e3;function yu(e){var t,r;return((t=e.git)==null?void 0:t.isGitRepo)===!0?!1:!!(e.gitProbePending||((r=e.connection)==null?void 0:r.state)==="connecting")}function qy(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function vu(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function wu(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function Fn(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function Yy(e){return Fn(e)?"degraded":wu(e)?"dirty":"online"}function Xy(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function _l(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 Pa(e){return e.length===0?"unknown":e.reduce((t,r)=>_l(r)>_l(t)?r:t)}function Jy(e){var o,l,c,d,m;const t=new Map,r=new Map;for(const u of e){const h=(l=(o=u.git)==null?void 0:o.branch)==null?void 0:l.trim();h&&(r.set(h,(r.get(h)??0)+1),(c=u.git)!=null&&c.upstream&&t.set(h,(t.get(h)??0)+1))}const n=[...t.entries()].sort((u,h)=>{if(h[1]!==u[1])return h[1]-u[1];const x=["main","master","develop","dev"],S=x.indexOf(u[0]),b=x.indexOf(h[0]);return S!==-1||b!==-1?S===-1?1:b===-1?-1:S-b:u[0].localeCompare(h[0])});return(d=n[0])!=null&&d[0]?n[0][0]:((m=[...r.entries()].sort((u,h)=>h[1]-u[1])[0])==null?void 0:m[0])??null}function Qy(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 Ll(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 Zy(e){return e.reduce((t,r)=>Ll(r.status)>Ll(t.status)?r:t)}function e0(e,t){if(!t||yu(e))return null;const r=e.git,n=(r==null?void 0:r.branch)??null,a=(r==null?void 0:r.upstream)??null,o=(r==null?void 0:r.upstreamStatus)??null,l=(r==null?void 0:r.ahead)??0,c=(r==null?void 0:r.behind)??0,d=vu(r)||wu(r),m=!!(r!=null&&r.hasConflicts)||Fn(r),u={branch:n,defaultBranch:t,upstream:a,upstreamStatus:o,ahead:l,behind:c,dirty:d,hasConflicts:m};return(r==null?void 0:r.isGitRepo)!==!0?{...u,status:"blocked_review",needsConvergence:!0,reason:"git_status_unavailable",nextStep:`Resolve git status for '${e.machineLabel||e.nodeId}' before declaring the mesh converged.`}:n?m||d?{...u,status:"not_mergeable",needsConvergence:!0,reason:r!=null&&r.hasConflicts?"conflicts_present":Fn(r)?"submodule_out_of_sync":"dirty_workspace",nextStep:`Commit, checkpoint, or resolve '${n}' before any convergence step into ${t}.`}:a&&o&&o!=="fresh"?{...u,status:"blocked_review",needsConvergence:!0,reason:"upstream_unverified",nextStep:`Refresh '${n}' against ${a} before claiming the mesh is converged.`}:n===t?l>0||c>0?{...u,status:"blocked_review",needsConvergence:!0,reason:"default_branch_not_even_with_upstream",nextStep:`Bring ${t} even with ${a??"its upstream"} before declaring convergence complete.`}:{...u,status:"merged_to_main",needsConvergence:!1,reason:"clean_default_branch",nextStep:null}:e.isLocalWorktree?{...u,status:"cleanup_candidate",needsConvergence:!0,reason:"clean_non_default_worktree_branch",nextStep:`Run refine / cleanup for '${n}' or explicitly classify the worktree before ending the task.`}:!a||l>0||c>0?{...u,status:"blocked_review",needsConvergence:!0,reason:a?"feature_branch_not_even_with_upstream":"feature_branch_missing_upstream",nextStep:`Push or reconcile '${n}', then merge it into ${t} or mark it blocked with a reason.`}:{...u,status:"pushed_feature_branch_needs_merge",needsConvergence:!0,reason:"clean_non_default_branch",nextStep:`Review and merge '${n}' into ${t}; do not treat it as fully complete while it remains off ${t}.`}:{...u,status:"blocked_review",needsConvergence:!0,reason:"branch_unknown",nextStep:`Inspect '${e.machineLabel||e.nodeId}' and confirm which branch should converge into ${t}.`}}function t0(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function s0(e){var d,m,u;const{nodeStatus:t,expectedSubmodulePaths:r,refreshedAtMs:n}=e,a=[],o=t.machineLabel||t.nodeId,l=t.git;if(!l){if(yu(t))return a.push(`${o} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:a};const h=t.health==="online"||t.machineStatus==="online"||((d=t.connection)==null?void 0:d.state)==="connected"||((m=t.connection)==null?void 0:m.state)==="self";return a.push(h?`${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((l.submodules??[]).map(h=>h.path));if(r.size>0){const h=[...r].filter(x=>!c.has(x));h.length>0&&a.push(`${o} is missing submodule visibility for ${h.join(", ")} even though another peer reported it.`)}return((u=t.connection)==null?void 0:u.state)!=="self"&&n!==null&&typeof l.lastCheckedAt=="number"&&n-l.lastCheckedAt>Gy&&a.push(`${o} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),a.some(h=>h.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:a}:a.some(h=>h.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:a}:{snapshotCompleteness:"complete",snapshotWarnings:a}}function ju(e){var D;const r=(typeof e.defaultBranch=="string"&&e.defaultBranch.trim().length>0?e.defaultBranch.trim():null)??Jy(e.nodes),n=qy(e.refreshedAt),a=new Set(e.nodes.flatMap(M=>{var j;return(((j=M.git)==null?void 0:j.submodules)??[]).map(W=>W.path)})),o=[],l=[],c=[],d=new Map;for(const M of e.nodes){const j=M.git,W=(j==null?void 0:j.branch)??null,H=Yy(j),$=vu(j)||H==="dirty",C=Qy(M,r),y=e0(M,r),F=s0({nodeStatus:M,expectedSubmodulePaths:a,refreshedAtMs:n}),P={id:M.nodeId,type:C.length>0?"orphanNode":"worktreeNode",label:M.machineLabel||M.nodeId.slice(0,8),workspace:M.workspace,branch:W,upstream:(j==null?void 0:j.upstream)??null,upstreamStatus:(j==null?void 0:j.upstreamStatus)??null,machineLabel:M.machineLabel||null,health:Pa([M.health,H]),ahead:(j==null?void 0:j.ahead)??0,behind:(j==null?void 0:j.behind)??0,dirty:$,dirtyFiles:Xy(j),hasConflicts:(j==null?void 0:j.hasConflicts)??!1,activeSessionCount:((D=M.activeSessions)==null?void 0:D.length)??0,activeSessions:M.activeSessions??[],providers:M.providers??[],isOrphan:C.length>0,orphanReasons:C,error:M.error,nextStepHint:F.snapshotWarnings[0]??C[0]??(y==null?void 0:y.nextStep)??void 0,parentNodeId:null,submodulePath:null,submoduleCommit:(j==null?void 0:j.headCommit)??null,outOfSync:Fn(j),snapshotCompleteness:F.snapshotCompleteness,snapshotWarnings:F.snapshotWarnings,branchConvergence:y,source:M};if(o.push(P),W){const E=d.get(W)??[];E.push(P.id),d.set(W,E)}for(const E of(j==null?void 0:j.submodules)??[]){const G=`${P.id}::submodule::${E.path}`,J=E.path.split("/").filter(Boolean).pop()||E.path;o.push({id:G,type:"submoduleNode",label:J,workspace:E.repoPath,branch:null,upstream:null,upstreamStatus:null,machineLabel:P.machineLabel,health:t0(E),ahead:0,behind:0,dirty:E.dirty,dirtyFiles:E.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],error:E.error,nextStepHint:E.error||(E.outOfSync?`${E.path} is out of sync with the parent checkout`:E.dirty?`${E.path} has local changes`:`${E.path} is in sync with the parent checkout`),parentNodeId:P.id,submodulePath:E.path,submoduleCommit:E.commit,outOfSync:E.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:P.id,parentWorkspace:M.workspace,submodule:E}}),l.push({id:`${P.id}--${G}`,source:P.id,target:G,type:"submoduleLink",label:E.outOfSync?"submodule out of sync":"submodule"})}}const m=r?`__branch_${r}`:null;if(m&&r){const j=(d.get(r)??[]).map(y=>o.find(F=>F.id===y)).filter(Boolean),W=j.map(y=>y.branchConvergence).filter(Boolean),H=W.length>0?Zy(W):null,$=W.filter(y=>y.needsConvergence).length,C={id:m,type:"defaultBranchNode",label:r,workspace:e.repoIdentity,branch:r,upstream:null,upstreamStatus:null,machineLabel:"default branch",health:Pa(j.map(y=>y.health)),ahead:0,behind:0,dirty:j.some(y=>y.dirty),dirtyFiles:j.reduce((y,F)=>y+F.dirtyFiles,0),hasConflicts:j.some(y=>y.hasConflicts),activeSessionCount:j.reduce((y,F)=>y+F.activeSessionCount,0),activeSessions:j.flatMap(y=>y.activeSessions),providers:[...new Set(j.flatMap(y=>y.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:$>0?`${$} workspace(s) on ${r} still need follow-up`:j.length>0?`${j.length} workspace(s) currently on ${r}`:"No workspaces currently checked out to the default branch",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:H,source:{nodeId:m,machineLabel:r,workspace:e.repoIdentity,health:Pa(j.map(y=>y.health)),providers:[],activeSessions:[]}};o.push(C);for(const y of o)if(!(y.id===m||y.type==="submoduleNode")){if(y.branch===r){l.push({id:`${m}--${y.id}`,source:m,target:y.id,type:"parentBranch",label:"checked out"});continue}if(y.branch){l.push({id:`${m}--${y.id}`,source:m,target:y.id,type:y.isOrphan?"orphanLink":"parentBranch",label:y.branch});continue}y.isOrphan&&l.push({id:`${m}--${y.id}`,source:m,target:y.id,type:"orphanLink",label:"detached"})}}for(const[M,j]of d){if(j.length<2)continue;const W=j.map(H=>o.find($=>$.id===H)).filter(Boolean);W.sort((H,$)=>H.label.localeCompare($.label));for(let H=1;H<W.length;H+=1)l.push({id:`wt_${W[H-1].id}--${W[H].id}`,source:W[H-1].id,target:W[H].id,type:"worktreeLink",label:H===1?`${M} peers`:void 0})}const u=o.filter(M=>M.type!=="defaultBranchNode"),h=u.filter(M=>M.isOrphan).length,x=u.filter(M=>M.hasConflicts).length,S=u.filter(M=>M.health==="offline").length,b=u.filter(M=>M.type==="submoduleNode"&&M.outOfSync).length,p=u.filter(M=>{var j;return M.type!=="submoduleNode"&&((j=M.branchConvergence)==null?void 0:j.needsConvergence)}).length,g=u.filter(M=>{var j;return((j=M.branchConvergence)==null?void 0:j.status)==="blocked_review"}).length,v=u.filter(M=>{var j;return((j=M.branchConvergence)==null?void 0:j.status)==="pushed_feature_branch_needs_merge"}).length,f=u.filter(M=>{var j;return((j=M.branchConvergence)==null?void 0:j.status)==="cleanup_candidate"}).length,T=u.filter(M=>{var j;return((j=M.branchConvergence)==null?void 0:j.status)==="not_mergeable"}).length,I=u.filter(M=>M.snapshotWarnings.length>0).length,k=u.filter(M=>M.snapshotCompleteness==="pending_git").length,A=u.filter(M=>M.snapshotCompleteness==="missing_git").length,_=u.filter(M=>M.snapshotCompleteness==="missing_submodule_report").length,N=u.filter(M=>M.snapshotCompleteness==="stale").length,w=[k>0?`${k} node(s) are still waiting for a live peer git snapshot`:null,A>0?`${A} node(s) have no visible peer git snapshot`:null,_>0?`${_} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,N>0?`${N} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return p>0&&c.push(`${p} workspace(s) still need follow-up before the mesh is converged`),h>0&&c.push(`${h} workspace(s) need attention before safe coordination`),g>0&&c.push(`${g} workspace(s) are blocked on branch convergence or upstream sync`),v>0&&c.push(`${v} clean feature branch workspace(s) still need merge follow-up`),f>0&&c.push(`${f} worktree workspace(s) are ready for refine / cleanup`),T>0&&c.push(`${T} workspace(s) have local changes or conflicts blocking convergence`),x>0&&c.push(`${x} workspace(s) report merge conflicts`),S>0&&c.push(`${S} node(s) are currently offline`),b>0&&c.push(`${b} submodule(s) are out of sync with their parent checkout`),c.push(...w),r||c.push("Could not infer a default branch from live mesh status"),{meshId:e.meshId,meshName:e.meshName,repoIdentity:e.repoIdentity,refreshedAt:e.refreshedAt,nodes:o,edges:l,stats:{totalNodes:u.length,onlineNodes:u.filter(M=>M.health==="online").length,dirtyNodes:u.filter(M=>M.dirty).length,orphanNodes:h,errorNodes:u.filter(M=>!!M.error||M.outOfSync).length,offlineNodes:S,followUpNodes:p,blockedReviewNodes:g,mergeReadyNodes:v,cleanupCandidateNodes:f,notMergeableNodes:T,incompleteSnapshotNodes:I,missingGitSnapshotNodes:A,missingSubmoduleSnapshotNodes:_,staleGitSnapshotNodes:N,totalActiveSessions:u.reduce((M,j)=>M+j.activeSessionCount,0)},warnings:c,snapshotWarnings:w}}function ku(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 Su(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=ku(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(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 Nu(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function r0(e){var t;return!Nu(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 ln(e){return[...new Set(e.filter(t=>!!t))]}function Cu(e){return e.nodes.filter(t=>t.type!=="submoduleNode")}function n0(e){const t=e.nodes.find(l=>l.type==="defaultBranchNode")??null,r=(t==null?void 0:t.branch)??null,n=e.nodes.filter(l=>l.type!=="defaultBranchNode"&&l.type!=="submoduleNode"&&!l.isOrphan&&!!r&&l.branch===r),a=e.nodes.filter(l=>l.type!=="submoduleNode"&&!l.isOrphan),o=Cu(e);return t||n.length>0?ln([t==null?void 0:t.id,...n.map(l=>l.id)]):a.length>0?ln(a.map(l=>l.id)):o.length>0?ln(o.map(l=>l.id)):ln(e.nodes.map(l=>l.id))}function a0(e){const t=Cu(e),r=new Set(t.map(o=>o.branch).filter(o=>!!o)).size,n=e.nodes.filter(o=>o.type==="submoduleNode").length,a=t.filter(o=>o.isOrphan).length;return t.length>=6||r>=3||n>=3||a>0}function Iu(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 o0(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${Iu(e)}::${n}x${a}`}const i0={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"},l0={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"},c0={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"},d0={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 tr(e){return e==="light"?{theme:e,isDark:!1,flowColorMode:"light",textPrimary:"text-slate-900",textSecondary:"text-slate-700",textMuted:"text-slate-500",graphShellClass:"relative 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",graphMiniMapClass:"!bottom-4 !right-4 !bg-white/95 !border !border-slate-200 !rounded-xl !shadow-md",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 overflow-y-auto 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=>l0[t],actionButton:t=>d0[t]}:{theme:e,isDark:!0,flowColorMode:"dark",textPrimary:"text-slate-100",textSecondary:"text-slate-300",textMuted:"text-slate-400",graphShellClass:"relative 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",graphMiniMapClass:"!bottom-4 !right-4 !bg-slate-950/85 !border !border-white/10 !rounded-xl",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 overflow-y-auto 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=>i0[t],actionButton:t=>c0[t]}}const Rl=390,Pl=192,Dl=120,u0=36,El=148,m0=24,Tu=i.createContext(tr("dark"));function p0(e,t,r){const n=t?"border-cyan-400/70 shadow-[0_0_0_1px_rgba(34,211,238,0.35),0_24px_60px_rgba(8,145,178,0.18)]":r?"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)]",a=Su(e);if((a==null?void 0:a.tone)==="danger")return`${n} ${r?"bg-rose-500/12":"bg-rose-50/95"}`;if((a==null?void 0:a.tone)==="warn")return`${n} ${r?"bg-amber-500/10":"bg-amber-50/95"}`;if((a==null?void 0:a.tone)==="info")return`${n} ${r?"bg-violet-500/10":"bg-violet-50/95"}`;switch(e.health){case"online":return`${n} ${r?"bg-emerald-500/8":"bg-emerald-50/95"}`;case"dirty":return`${n} ${r?"bg-amber-500/8":"bg-amber-50/95"}`;case"degraded":return`${n} ${r?"bg-rose-500/10":"bg-rose-50/95"}`;case"wrong_branch":return`${n} ${r?"bg-violet-500/10":"bg-violet-50/95"}`;case"offline":return`${n} ${r?"bg-slate-500/12":"bg-slate-100/95"}`;default:return`${n} ${r?"bg-slate-950/78":"bg-white/96"}`}}function qt(e,t){switch(e){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 h0(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 Mu(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 f0(e){return e.replace(/_/g," ")}function x0(e){return!e.upstream||e.upstreamStatus==="fresh"}function b0(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),!x0(e))t.push("upstream unverified");else{const n=ku(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 g0({data:e,selected:t}){const r=i.useContext(Tu),n=e.graphNode,a=n.type==="defaultBranchNode",o=n.type==="submoduleNode",l=r0(n),c=a?"default branch anchor":o?n.submodulePath||"submodule checkout":n.machineLabel||n.workspace,d=n.submoduleCommit?n.submoduleCommit.slice(0,7):null,m=Su(n),u=b0(n),h=Nu(n);return s.jsxs("div",{className:`${o?"w-[204px]":"w-[220px]"} rounded-2xl border px-3.5 py-3 backdrop-blur-sm transition-all ${p0(n,t,r.isDark)}`,children:[s.jsx(ki,{type:"target",position:Si.Top,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:n.label}),s.jsx("div",{className:`truncate text-[11px] ${r.textMuted}`,children:c})]}),s.jsx("span",{className:"mt-0.5 h-2.5 w-2.5 shrink-0 rounded-full",style:{backgroundColor:Mu(n.health)},"aria-hidden":!0})]}),m&&s.jsx("div",{className:`mt-3 inline-flex max-w-full items-center rounded-full border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] ${h0(m.tone,r.isDark)}`,children:s.jsx("span",{className:"truncate",children:m.label})}),s.jsxs("div",{className:"mt-3 flex flex-wrap gap-1.5 text-[10px]",children:[s.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${qt("health",r.isDark)}`,children:f0(n.health)}),o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("submodule",r.isDark)}`,children:"submodule"}),n.branch&&!o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("meta",r.isDark)}`,children:n.branch}),d&&o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("meta",r.isDark)}`,children:d}),n.dirty&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("dirty",r.isDark)}`,children:o?"local changes":`${n.dirtyFiles} dirty`}),n.outOfSync&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("conflict",r.isDark)}`,children:"out of sync"}),n.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("conflict",r.isDark)}`,children:"conflicts"}),!o&&n.upstream&&n.upstreamStatus!=="fresh"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("orphan",r.isDark)}`,children:"upstream unverified"}),n.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("orphan",r.isDark)}`,children:"needs follow-up"})]}),s.jsx("div",{className:`mt-3 text-[11px] leading-5 ${r.textSecondary}`,children:u}),l&&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"}`,children:h}),s.jsx(ki,{type:"source",position:Si.Bottom,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const y0={meshNode:g0};function Da(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)}function v0(e,t=tr("dark")){const r=[...e.nodes].sort(Da),n=r.find(p=>p.type==="defaultBranchNode")??null,a=new Map;for(const p of r){if(p.type!=="submoduleNode"||!p.parentNodeId)continue;const g=a.get(p.parentNodeId)??[];g.push(p),a.set(p.parentNodeId,g)}const o=r.filter(p=>p.id!==(n==null?void 0:n.id)&&p.type!=="submoduleNode"),l=new Map,c=[];for(const p of o){if(p.isOrphan||!p.branch){c.push(p);continue}const g=p.branch,v=l.get(g)??[];v.push(p),l.set(g,v)}const d=[...l.entries()].sort(([p],[g])=>n!=null&&n.branch&&p===n.branch&&g!==n.branch?-1:n!=null&&n.branch&&g===n.branch&&p!==n.branch?1:p.localeCompare(g));c.length>0&&d.push(["__orphans__",[...c].sort(Da)]),d.length===0&&d.push(["__nodes__",[]]);const m=[],u=d.length,h=Math.max(1,u-1)*Rl,x=n?0:80,S=n?Pl:0;n&&m.push({id:n.id,type:"meshNode",position:{x:h/2,y:x},data:{graphNode:n},selected:!1,draggable:!1,selectable:!0}),d.forEach(([p,g],v)=>{const f=v*Rl,T=g.length>0?g:o.length>0?o:[];let I=S;T.forEach(k=>{m.push({id:k.id,type:"meshNode",position:{x:f,y:I},data:{graphNode:k},selected:!1,draggable:!1,selectable:!0});const A=[...a.get(k.id)??[]].sort(Da);if(A.length>0){A.forEach((_,N)=>{m.push({id:_.id,type:"meshNode",position:{x:f+u0,y:I+El+N*Dl},data:{graphNode:_},selected:!1,draggable:!1,selectable:!0})}),I+=El+A.length*Dl+m0;return}I+=Pl}),p==="__nodes__"&&o.length===0&&n&&m.push({id:`${n.id}__placeholder`,type:"meshNode",position:{x:f,y:S},data:{graphNode:{id:`${n.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:e.repoIdentity,branch:n.branch,upstream:null,upstreamStatus:null,machineLabel:null,health:"unknown",ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],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:`${n.id}__placeholder`,machineLabel:"",workspace:e.repoIdentity,health:"unknown",providers:[],activeSessions:[]}}},selected:!1,draggable:!1,selectable:!1})});const b=e.edges.map(p=>({id:p.id,source:p.source,target:p.target,label:p.label,type:p.type==="worktreeLink"||p.type==="submoduleLink"?"smoothstep":"bezier",animated:p.type==="orphanLink",markerEnd:{type:ym.ArrowClosed,width:p.type==="submoduleLink"?16:18,height:p.type==="submoduleLink"?16:18,color:$l(p)},style:{stroke:$l(p),strokeWidth:p.type==="orphanLink"?2.25:p.type==="submoduleLink"?1.7:p.type==="worktreeLink"?1.8:2,strokeDasharray:p.type==="orphanLink"?"5 4":p.type==="submoduleLink"?"4 3":void 0},labelStyle:{fill:t.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:t.edgeLabelBackgroundColor,fillOpacity:1,stroke:t.edgeLabelBorderColor},labelBgPadding:[5,3],labelBgBorderRadius:6}));return{nodes:m,edges:b}}function $l(e){switch(e.type){case"parentBranch":return"#38bdf8";case"worktreeLink":return"#a78bfa";case"sessionLink":return"#34d399";case"orphanLink":return"#f97316";case"submoduleLink":return"#c084fc";default:return"#64748b"}}function w0({data:e,viewportKey:t}){const r=vm(),n=wm(),a=i.useRef(null),o=i.useMemo(()=>Iu(e),[e]),l=i.useMemo(()=>n0(e),[e]);return i.useEffect(()=>{if(!r||e.nodes.length===0||a.current===t)return;let c=!1;const d=requestAnimationFrame(()=>{if(c)return;const m=l.length>0&&l.length<e.nodes.length;n.fitView({nodes:m?l.map(u=>({id:u})):void 0,padding:m?.2:.16,maxZoom:m?1.04:.96,duration:260}),a.current=t});return()=>{c=!0,cancelAnimationFrame(d)}},[e.nodes.length,l,o,r,n,t]),null}function j0({data:e,selectedNodeId:t=null,onNodeClick:r}){const{theme:n}=er(),a=i.useMemo(()=>tr(n),[n]),o=i.useMemo(()=>v0(e,a),[e,a]),l=i.useMemo(()=>a0(e),[e]),c=i.useRef(null),[d,m]=i.useState({width:0,height:0}),u=i.useMemo(()=>o0(e,d.width,d.height),[e,d.height,d.width]),h=i.useMemo(()=>o.nodes.map(x=>({...x,selected:x.id===t})),[o.nodes,t]);return i.useEffect(()=>{const x=c.current;if(!x)return;const S=()=>{const p=Math.max(0,Math.round(x.clientWidth)),g=Math.max(0,Math.round(x.clientHeight));m(v=>v.width===p&&v.height===g?v:{width:p,height:g})};S();const b=typeof ResizeObserver=="function"?new ResizeObserver(()=>S()):null;return b==null||b.observe(x),window.addEventListener("resize",S),()=>{b==null||b.disconnect(),window.removeEventListener("resize",S)}},[]),s.jsx(Tu.Provider,{value:a,children:s.jsxs("div",{ref:c,className:a.graphShellClass,children:[s.jsxs("div",{className:`absolute inset-x-3 top-3 z-10 flex flex-wrap items-center justify-between gap-2 text-[11px] ${a.textSecondary}`,children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsxs("span",{className:a.graphStatChipClass,children:[e.stats.totalNodes," node",e.stats.totalNodes===1?"":"s"]}),s.jsxs("span",{className:a.graphStatChipClass,children:[e.stats.totalActiveSessions," active session",e.stats.totalActiveSessions===1?"":"s"]}),e.stats.orphanNodes>0&&s.jsxs("span",{className:a.isDark?"rounded-full border border-orange-400/25 bg-orange-500/12 px-3 py-1 text-orange-100":"rounded-full border border-orange-300 bg-orange-50 px-3 py-1 text-orange-700",children:[e.stats.orphanNodes," need attention"]})]}),s.jsx("div",{className:a.graphHintChipClass,children:"Focused on the main path first · drag or scroll to pan"})]}),s.jsx("div",{className:"h-[420px] w-full min-w-0 min-h-[420px] sm:h-[520px] xl:h-[640px]",children:s.jsxs(hm,{nodes:h,edges:o.edges,nodeTypes:y0,minZoom:.25,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!1,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(x,S)=>r==null?void 0:r(S.data.graphNode),className:"h-full w-full",colorMode:a.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(w0,{data:e,viewportKey:u}),l&&s.jsx(fm,{className:a.graphMiniMapClass,nodeColor:x=>Mu(x.data.graphNode.health)}),s.jsx(xm,{className:a.graphControlsClass,showInteractive:!1}),s.jsx(bm,{variant:gm.Dots,gap:18,size:1.2,color:a.graphBackgroundDotColor})]})})]})})}const Bl=new Set(["pending","assigned"]),k0={pending:0,assigned:0},S0={recentFailures:0},Or=i.createContext(tr("dark"));function Ke({label:e,tone:t="default"}){const r=i.useContext(Or);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 hr({title:e,subtitle:t,children:r,className:n=""}){const a=i.useContext(Or);return s.jsxs("section",{className:`${a.cardClass} ${n}`,children:[s.jsxs("div",{className:a.cardHeaderClass,children:[s.jsx("div",{className:a.cardTitleClass,children:e}),t&&s.jsx("div",{className:a.cardSubtitleClass,children:t})]}),s.jsx("div",{className:"px-4 py-3",children:r})]})}function qe({label:e,value:t}){const r=i.useContext(Or);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 Ht({label:e,onClick:t,tone:r="default"}){const n=i.useContext(Or);return s.jsx("button",{type:"button",onClick:t,className:`rounded-full border px-2.5 py-1 text-[11px] transition ${n.actionButton(r)}`,children:e})}function ps(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function Rs(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleString()}function Ea(e){switch(e){case"completed":return"good";case"failed":case"cancelled":return"danger";case"assigned":return"info";case"pending":return"warn";default:return"default"}}function Ol(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 cn(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 Fl(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 Au(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 $a(e){return e===!0?"yes":e===!1?"no":"unknown"}function Wl(e,t){if(!t)return null;const r=new URLSearchParams;return e&&r.set("daemonId",e),r.set("targetSessionId",t),`/dashboard?${r.toString()}`}function Kl(e){if(e.gitProbePending)return"Git probe pending";const t=e.git;if(!t)return"No git probe";const r=(t.staged??0)+(t.modified??0)+(t.untracked??0)+(t.deleted??0)+(t.renamed??0),n=[];t.branch&&n.push(t.branch),t.upstream&&t.upstreamStatus!=="fresh"&&n.push("upstream unverified"),t.upstreamStatus==="fresh"&&((t.ahead??0)>0||(t.behind??0)>0)&&n.push(`↑${t.ahead??0}/↓${t.behind??0}`),r>0&&n.push(`${r} dirty`);const a=(t.submodules??[]).filter(l=>l.dirty),o=(t.submodules??[]).filter(l=>l.outOfSync||l.error);return a.length>0&&n.push(`${a.length} submodule dirty`),o.length>0&&n.push(`${o.length} submodule drift`),t.hasConflicts&&n.push("conflicts"),n.join(" · ")||"Clean"}function N0(e){switch(e){case"merged_to_main":return"merged to default branch";case"pushed_feature_branch_needs_merge":return"feature branch still needs merge";case"cleanup_candidate":return"worktree still needs refine / cleanup";case"blocked_review":return"review blocked before convergence";case"not_mergeable":return"not mergeable yet";default:return null}}function C0(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 Ba(e){const t=e.assignedNodeId||e.targetNodeId||"unbound",r=e.assignedSessionId||e.targetSessionId||"no session";return`${t} · ${r}`}function dn(e){return e.assignedNodeId||e.targetNodeId||null}function Oa(e){var t;return e.assignedSessionId||e.targetSessionId||((t=e.autoLaunch)==null?void 0:t.sessionId)||null}function Cr(e){return e?e.slice(0,7):null}function I0(e,t){var o,l,c;const r=Cr((o=e==null?void 0:e.git)==null?void 0:o.headCommit),n=((c=(l=e==null?void 0:e.git)==null?void 0:l.headMessage)==null?void 0:c.trim())||"";if(r||n)return[r,n].filter(Boolean).join(" · ");const a=t[0];return a?[Cr(a.commit),a.message].filter(Boolean).join(" · "):null}function T0(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 M0(e){var r,n,a,o,l,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)||((l=e.selectedNodeStatus)==null?void 0:l.workspace)||null;if(t&&e.selectedSessionEntry){const d=((c=e.selectedNodeStatus)==null?void 0:c.daemonId)||e.coordinatorDaemonId;return d?{daemonId:d,workspace:t}:null}if(t&&e.selectedNodeStatus){const d=e.selectedNodeStatus.daemonId||e.coordinatorDaemonId;return d?{daemonId:d,workspace:t}:null}return null}function A0(e){return(e.providers??[]).length>0?e.providers.join(", "):((e.providerPriority??[]).length>0,"not reported yet")}function Hl(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":Au(e.connection)}function Ul(e,t){return ps(e)??e??(t?"pending live refresh":"not reported")}function _u({graph:e,status:t,emptyMessage:r="No live mesh graph is available for this coordinator yet.",daemonId:n=null,sendDaemonCommand:a=null}){var Se,ve,X,xe,fe,we,be,Ce,ee,me,ie,pe,le,B,z,de,re;const{theme:o}=er(),l=i.useMemo(()=>tr(o),[o]),c=As(),[d,m]=i.useState(null),[u,h]=i.useState(null),[x,S]=i.useState("active"),[b,p]=i.useState({}),g=i.useMemo(()=>new Map(t.nodes.map(R=>[R.nodeId,R])),[t.nodes]),v=i.useMemo(()=>new Map(e.nodes.map(R=>[R.id,R])),[e.nodes]),f=((Se=t.queue)==null?void 0:Se.tasks)??[],T=((ve=t.queue)==null?void 0:ve.summary)??null,I=(T==null?void 0:T.activeCounts)??k0,k=((X=t.ledger)==null?void 0:X.summary)??S0,A=i.useMemo(()=>C0(t),[t]),_=i.useMemo(()=>{const R=new Map;for(const q of A){const ce=q.session.state||q.session.lifecycle||"unknown";R.set(ce,(R.get(ce)??0)+1)}return[...R.entries()].sort((q,ce)=>ce[1]-q[1])},[A]),N=i.useMemo(()=>x==="all"?f:x==="active"?f.filter(R=>Bl.has(R.status)):f.filter(R=>!Bl.has(R.status)),[x,f]);i.useEffect(()=>{d&&(v.has(d)||(m(null),h(R=>!R||"nodeId"in R&&R.nodeId===d?null:R)))},[v,d]);const w=d?v.get(d)??null:null,D=d?g.get(d)??null:null,M=(u==null?void 0:u.kind)==="queue"?f.find(R=>R.id===u.taskId)??null:null,j=(u==null?void 0:u.kind)==="session"?A.find(R=>R.nodeId===u.nodeId&&R.session.sessionId===u.sessionId)??null:null,W=i.useMemo(()=>A.filter(R=>R.nodeId===d),[d,A]),H=i.useMemo(()=>f.filter(R=>dn(R)===d),[f,d]),$=M0({coordinatorDaemonId:n,selectedNodeStatus:D,selectedSessionEntry:j}),C=($==null?void 0:$.workspace)??null,y=C?b[C]??null:null,F=D!=null&&D.gitProbePending&&!((xe=y==null?void 0:y.entries)!=null&&xe.length)?"Pending live git probe":I0(D,(y==null?void 0:y.entries)??[]),P=i.useCallback(R=>{R&&c(Zt(R),{state:{openRemoteForTabKey:R}})},[c]),E=i.useCallback((R,q)=>{m(R),h({kind:"session",nodeId:R,sessionId:q})},[]),G=i.useCallback(R=>{m(R),h({kind:"node",nodeId:R})},[]);i.useEffect(()=>{if(!$||!a)return;const{daemonId:R,workspace:q}=$,ce=b[q];if(ce!=null&&ce.loading||ce&&(ce.entries.length>0||ce.error))return;let Ne=!1;return p(je=>{var O;return{...je,[q]:{loading:!0,error:null,entries:((O=je[q])==null?void 0:O.entries)??[]}}}),a(R,"git_log",{workspace:q,limit:5}).then(je=>{Ne||p(O=>({...O,[q]:{loading:!1,error:null,entries:T0(je)}}))}).catch(je=>{Ne||p(O=>({...O,[q]:{loading:!1,error:je instanceof Error?je.message:"git_log failed",entries:[]}}))}),()=>{Ne=!0}},[b,$,a]);const J=[...e.warnings??[],...t.nodes.filter(R=>R.machineStatus&&R.machineStatus!=="online").map(R=>`${R.machineLabel}: ${R.machineStatus}`)],ye=e.stats.incompleteSnapshotNodes>0,he=e.stats.followUpNodes>0?`${e.stats.followUpNodes} need follow-up`:ye?"mesh visibility incomplete":"mesh converged",ne=e.stats.followUpNodes>0?"danger":ye?"warn":"good",ue=!!(M||j||w);return s.jsx(Or.Provider,{value:l,children:s.jsxs("div",{className:"flex min-h-0 flex-col gap-4 xl:flex-row",children:[s.jsx("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col gap-4",children:s.jsxs("div",{className:`${l.cardClass} min-h-0 flex-1 rounded-[28px] p-3 sm:p-4`,style:{minHeight:420},children:[s.jsxs("div",{className:`mb-3 flex flex-wrap items-start justify-between gap-3 rounded-2xl px-3.5 py-3 ${l.isDark?"border border-white/10 bg-slate-950/45":"border border-slate-200 bg-white/95 shadow-sm"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-wrap gap-2 text-xs ${l.textSecondary}`,children:[s.jsx(Ke,{label:he,tone:ne}),e.stats.blockedReviewNodes>0&&s.jsx(Ke,{label:`${e.stats.blockedReviewNodes} blocked review`,tone:"danger"}),e.stats.notMergeableNodes>0&&s.jsx(Ke,{label:`${e.stats.notMergeableNodes} not mergeable`,tone:"danger"}),e.stats.mergeReadyNodes>0&&s.jsx(Ke,{label:`${e.stats.mergeReadyNodes} need merge`,tone:"warn"}),e.stats.cleanupCandidateNodes>0&&s.jsx(Ke,{label:`${e.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info"}),e.stats.offlineNodes>0&&s.jsx(Ke,{label:`${e.stats.offlineNodes} offline`,tone:"danger"}),e.stats.incompleteSnapshotNodes>0&&s.jsx(Ke,{label:`${e.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn"}),e.stats.missingGitSnapshotNodes>0&&s.jsx(Ke,{label:`${e.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn"}),e.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(Ke,{label:`${e.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn"}),e.stats.staleGitSnapshotNodes>0&&s.jsx(Ke,{label:`${e.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn"}),((T==null?void 0:T.active)??0)>0&&s.jsx(Ke,{label:`${(T==null?void 0:T.active)??0} active queue`,tone:"info"}),s.jsx(Ke,{label:`${e.stats.totalNodes} nodes`,tone:"default"}),e.stats.totalActiveSessions>0&&s.jsx(Ke,{label:`${e.stats.totalActiveSessions} active sessions`,tone:"info"})]}),s.jsxs("details",{className:`max-w-full rounded-xl px-3 py-2 text-xs ${l.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 ${l.textSecondary} [&::-webkit-details-marker]:hidden`,children:"Legend & secondary details"}),s.jsxs("div",{className:"mt-3 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ke,{label:`${e.stats.dirtyNodes} dirty`,tone:e.stats.dirtyNodes>0?"warn":"good"}),s.jsx(Ke,{label:`${e.stats.orphanNodes} orphan`,tone:e.stats.orphanNodes>0?"warn":"good"}),s.jsx(Ke,{label:`${k.recentFailures} recent failures`,tone:k.recentFailures>0?"danger":"good"}),_.length===0?s.jsx(Ke,{label:"no session metadata"}):_.slice(0,2).map(([R,q])=>s.jsx(Ke,{label:`${q} ${R}`,tone:cn(R)},R))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ke,{label:"Anchor = default branch",tone:"info"}),s.jsx(Ke,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(Ke,{label:"Submodule link = child checkout",tone:"warn"})]}),J.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:J.map(R=>s.jsx("span",{className:l.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:R},R))}),s.jsx("div",{className:`text-xs ${l.textMuted}`,children:"Click a node only when you want drill-down details. The graph itself now carries the convergence state."})]})]})]}),e.nodes.length>0?s.jsx(j0,{data:e,selectedNodeId:d,onNodeClick:R=>{if((u==null?void 0:u.kind)==="node"&&d===R.id){m(null),h(null);return}m(R.id),h({kind:"node",nodeId:R.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:r})]})}),ue&&s.jsxs("div",{className:"flex w-full shrink-0 flex-col gap-4 xl:w-[420px]",children:[s.jsx(hr,{title:"Selected detail",subtitle:"Node, session, or queue item drill-down.",children:s.jsx("div",{className:"flex flex-col gap-3",children:(u==null?void 0:u.kind)==="queue"&&M?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(Ke,{label:M.status,tone:Ea(M.status)}),s.jsx(Ke,{label:M.id.slice(0,8),tone:"default"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[dn(M)&&s.jsx(Ht,{label:"View node",onClick:()=>G(dn(M)||"")}),(()=>{const R=Oa(M);if(!R)return null;const q=A.find(ce=>ce.session.sessionId===R)??null;return s.jsxs(s.Fragment,{children:[q&&s.jsx(Ht,{label:"View session",onClick:()=>E(q.nodeId,q.session.sessionId)}),s.jsx(Ht,{label:"Open chat",tone:"info",onClick:()=>P(R)})]})})()]}),s.jsx(qe,{label:"Message",value:M.message}),s.jsx(qe,{label:"Routing",value:Ba(M)}),s.jsx(qe,{label:"Created",value:ps(M.createdAt)??"unknown"}),s.jsx(qe,{label:"Updated",value:ps(M.updatedAt)??"unknown"}),s.jsx(qe,{label:"Requeues",value:M.requeueCount??0}),s.jsx(qe,{label:"Auto-launch",value:M.autoLaunch?`${M.autoLaunch.status}${M.autoLaunch.providerType?` · ${M.autoLaunch.providerType}`:""}`:"none"}),(()=>{var Ne,je,O;const R=M.assignedSessionId||M.targetSessionId||((Ne=M.autoLaunch)==null?void 0:Ne.sessionId)||null,q=M.assignedNodeId||M.targetNodeId||((je=M.autoLaunch)==null?void 0:je.nodeId)||null,ce=Wl(q?(O=g.get(q))==null?void 0:O.daemonId:null,R);return ce?s.jsx("a",{href:ce,className:l.isDark?"inline-flex w-fit items-center rounded-full border border-sky-400/30 bg-sky-500/10 px-3 py-1 text-xs font-medium text-sky-100 transition hover:bg-sky-500/20":"inline-flex w-fit items-center rounded-full border border-sky-300 bg-sky-50 px-3 py-1 text-xs font-medium text-sky-700 transition hover:bg-sky-100",children:"Open linked dashboard chat"}):null})(),M.cancelReason&&s.jsx(qe,{label:"Cancel reason",value:M.cancelReason}),M.requeueReason&&s.jsx(qe,{label:"Requeue reason",value:M.requeueReason})]}):(u==null?void 0:u.kind)==="session"&&j?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(Ke,{label:j.session.state||j.session.lifecycle||"unknown",tone:cn(j.session.state||j.session.lifecycle)}),j.session.providerType&&s.jsx(Ke,{label:j.session.providerType,tone:"info"}),j.session.isCached&&s.jsx(Ke,{label:"cached",tone:"default"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ht,{label:"View node",onClick:()=>G(j.nodeId)}),s.jsx(Ht,{label:"Open chat",tone:"info",onClick:()=>P(j.session.sessionId)})]}),s.jsx(qe,{label:"Session id",value:j.session.sessionId}),s.jsx(qe,{label:"Node",value:j.machineLabel}),s.jsx(qe,{label:"Workspace",value:j.workspace}),s.jsx(qe,{label:"Branch",value:j.branch??"unknown"}),s.jsx(qe,{label:"Node health",value:j.nodeHealth}),s.jsx(qe,{label:"Lifecycle",value:j.session.lifecycle??"unknown"}),j.session.surfaceKind&&s.jsx(qe,{label:"Surface",value:j.session.surfaceKind}),j.session.recoveryState&&s.jsx(qe,{label:"Recovery",value:j.session.recoveryState}),j.session.lastActivityAt&&s.jsx(qe,{label:"Last activity",value:ps(j.session.lastActivityAt)??j.session.lastActivityAt}),(()=>{var q;const R=Wl((q=g.get(j.nodeId))==null?void 0:q.daemonId,j.session.sessionId);return R?s.jsx("a",{href:R,className:l.isDark?"inline-flex w-fit items-center rounded-full border border-sky-400/30 bg-sky-500/10 px-3 py-1 text-xs font-medium text-sky-100 transition hover:bg-sky-500/20":"inline-flex w-fit items-center rounded-full border border-sky-300 bg-sky-50 px-3 py-1 text-xs font-medium text-sky-700 transition hover:bg-sky-100",children:"Open dashboard chat"}):null})(),s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/10 bg-slate-950/40 p-3":"rounded-xl border border-slate-200 bg-slate-50 p-3",children:[s.jsx("div",{className:`mb-2 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Git context"}),s.jsxs("div",{className:`flex flex-col gap-2 text-xs ${l.textSecondary}`,children:[s.jsx("div",{children:F||"HEAD subject not present in cached mesh_status."}),(y==null?void 0:y.loading)&&s.jsx("div",{className:"text-slate-500",children:"Loading recent commits…"}),(y==null?void 0:y.error)&&s.jsxs("div",{className:"text-amber-200",children:["Recent history unavailable: ",y.error]}),((y==null?void 0:y.entries)??[]).slice(0,5).map(R=>s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-2.5 py-2":"rounded-lg border border-slate-200 bg-white px-2.5 py-2",children:[s.jsxs("div",{className:`font-medium ${l.textPrimary}`,children:[Cr(R.commit)," · ",R.message]}),s.jsxs("div",{className:"mt-1 text-[11px] text-slate-500",children:[R.authorName||"unknown author",Rs(R.committedAt)?` · ${Rs(R.committedAt)}`:""]})]},R.commit))]})]})]}):w?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/10 bg-slate-950/40 p-3":"rounded-xl border border-slate-200 bg-slate-50 p-3",children:[s.jsxs("div",{className:"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 ${l.textPrimary}`,children:w.label}),s.jsx("div",{className:`mt-1 break-all text-xs ${l.textMuted}`,children:(D==null?void 0:D.workspace)??w.workspace})]}),s.jsx("button",{type:"button",onClick:()=>{m(null),h(null)},className:l.isDark?"rounded-full border border-white/10 bg-white/[0.03] px-2 py-1 text-xs text-slate-300 transition hover:bg-white/[0.06] hover:text-white":"rounded-full border border-slate-200 bg-white px-2 py-1 text-xs text-slate-600 transition hover:bg-slate-50 hover:text-slate-900",children:"Close"})]}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[w.branch&&s.jsx(Ke,{label:w.branch,tone:"default"}),((fe=w.branchConvergence)==null?void 0:fe.status)&&s.jsx(Ke,{label:w.branchConvergence.status,tone:w.branchConvergence.needsConvergence?"warn":"good"}),w.snapshotWarnings.length>0&&s.jsx(Ke,{label:`snapshot ${w.snapshotCompleteness}`,tone:"warn"})]}),s.jsxs("div",{className:"mt-3 flex flex-col gap-0.5",children:[s.jsx(qe,{label:"Graph branch",value:w.branch??"unknown"}),s.jsx(qe,{label:"Graph upstream",value:w.upstream??"none"}),s.jsx(qe,{label:"Convergence",value:N0((we=w.branchConvergence)==null?void 0:we.status)??"not classified"})]}),w.snapshotWarnings.length>0&&s.jsxs("div",{className:l.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:"Peer snapshot warning"}),s.jsx("div",{className:"mt-1",children:w.snapshotWarnings[0]})]}),((be=w.branchConvergence)==null?void 0:be.nextStep)&&s.jsxs("div",{className:l.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:"Convergence follow-up"}),s.jsx("div",{className:"mt-1",children:w.branchConvergence.nextStep})]})]}),D&&s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/10 bg-slate-950/40 p-3":"rounded-xl border border-slate-200 bg-slate-50 p-3",children:[s.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[s.jsx(Ke,{label:D.health,tone:Ol(D.health)}),D.machineStatus&&s.jsx(Ke,{label:D.machineStatus,tone:D.machineStatus==="online"?"good":"warn"}),s.jsx(Ke,{label:`launchReady ${$a(D.launchReady)}`,tone:D.launchReady?"good":"warn"}),s.jsx(Ke,{label:Hl(D),tone:Fl(D.connection)}),D.worktreeBranch&&s.jsx(Ke,{label:D.worktreeBranch,tone:"info"})]}),s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsx(qe,{label:"Repo root",value:D.repoRoot??D.workspace}),s.jsx(qe,{label:"Provider(s)",value:A0(D)}),s.jsx(qe,{label:"Provider priority",value:(D.providerPriority??[]).join(", ")||"not configured"}),s.jsx(qe,{label:"Drift",value:Kl(D)}),s.jsx(qe,{label:"HEAD",value:F??(D.gitProbePending?"Pending live git probe":"Not available")}),s.jsx(qe,{label:"Daemon",value:D.daemonId??"unknown"}),s.jsx(qe,{label:"Machine",value:D.machineId??D.machineLabel}),s.jsx(qe,{label:"Launch ready",value:$a(D.launchReady)}),s.jsx(qe,{label:"Mesh connection",value:Hl(D)}),s.jsx(qe,{label:"Transport",value:((Ce=D.connection)==null?void 0:Ce.transport)??"unknown"}),s.jsx(qe,{label:"Connection source",value:((ee=D.connection)==null?void 0:ee.source)??"unknown"}),s.jsx(qe,{label:"Last seen",value:Ul(D.lastSeenAt,!!D.gitProbePending)}),s.jsx(qe,{label:"Updated",value:Ul(D.updatedAt,!!D.gitProbePending)}),((me=D.connection)==null?void 0:me.lastConnectedAt)&&s.jsx(qe,{label:"Last connected",value:ps(D.connection.lastConnectedAt)??D.connection.lastConnectedAt}),((ie=D.connection)==null?void 0:ie.lastCommandAt)&&s.jsx(qe,{label:"Last mesh command",value:ps(D.connection.lastCommandAt)??D.connection.lastCommandAt}),((pe=D.connection)==null?void 0:pe.reason)&&s.jsx(qe,{label:"Connection reason",value:D.connection.reason}),s.jsx(qe,{label:"Sessions",value:D.activeSessions.length}),D.error&&s.jsx(qe,{label:"Error",value:D.error})]}),W.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Active sessions"}),s.jsx("div",{className:"flex flex-col gap-2",children:W.map(R=>{const q=R.session.state||R.session.lifecycle||"unknown";return s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",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:`truncate font-medium ${l.textPrimary}`,children:R.session.title||R.session.sessionId}),s.jsxs("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:[R.session.providerType||"unknown provider"," · ",q]})]}),s.jsx(Ke,{label:q,tone:cn(q)})]}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[s.jsx(Ht,{label:"View session",onClick:()=>E(R.nodeId,R.session.sessionId)}),s.jsx(Ht,{label:"Open chat",tone:"info",onClick:()=>P(R.session.sessionId)})]})]},`${R.nodeId}:${R.session.sessionId}`)})})]}),H.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Related queue items"}),s.jsx("div",{className:"flex flex-col gap-2",children:H.map(R=>{const q=Oa(R),ce=q?A.find(Ne=>Ne.session.sessionId===q)??null:null;return s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",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:`truncate font-medium ${l.textPrimary}`,children:R.message}),s.jsx("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:Ba(R)})]}),s.jsx(Ke,{label:R.status,tone:Ea(R.status)})]}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[s.jsx(Ht,{label:"View queue detail",onClick:()=>h({kind:"queue",taskId:R.id})}),ce&&s.jsx(Ht,{label:"View session",onClick:()=>E(ce.nodeId,ce.session.sessionId)}),q&&s.jsx(Ht,{label:"Open chat",tone:"info",onClick:()=>P(q)})]})]},R.id)})})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Recent commits"}),s.jsxs("div",{className:"flex flex-col gap-2",children:[(y==null?void 0:y.loading)&&s.jsx("div",{className:(l.isDark,"text-xs text-slate-500"),children:"Loading recent commits…"}),(y==null?void 0:y.error)&&s.jsxs("div",{className:"text-xs text-amber-200",children:["Recent history unavailable: ",y.error]}),!(y!=null&&y.loading)&&!(y!=null&&y.error)&&((y==null?void 0:y.entries)??[]).length===0&&s.jsx("div",{className:(l.isDark,"text-xs text-slate-500"),children:"Recent commit history not available from the current mesh snapshot yet."}),((y==null?void 0:y.entries)??[]).slice(0,5).map(R=>s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",children:[s.jsxs("div",{className:`font-medium ${l.textPrimary}`,children:[Cr(R.commit)," · ",R.message]}),s.jsxs("div",{className:"mt-1 text-[11px] text-slate-500",children:[R.authorName||"unknown author",Rs(R.committedAt)?` · ${Rs(R.committedAt)}`:""]})]},R.commit))]})]}),(((B=(le=D.git)==null?void 0:le.submodules)==null?void 0:B.length)??0)>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Submodules"}),s.jsx("div",{className:"flex flex-col gap-2",children:(((z=D.git)==null?void 0:z.submodules)??[]).map(R=>s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"font-medium",children:R.path}),R.dirty&&s.jsx(Ke,{label:"dirty",tone:"warn"}),(R.outOfSync||R.error)&&s.jsx(Ke,{label:"drift",tone:"danger"})]}),s.jsx("div",{className:"mt-1 break-all text-[11px] text-slate-400",children:R.repoPath}),s.jsx("div",{className:"mt-1 text-[11px] text-slate-500",children:"Select the submodule node in the graph for its own HEAD and recent history."}),R.error&&s.jsx("div",{className:"mt-1 text-[11px] text-rose-200",children:R.error})]},`${D.nodeId}:${R.path}`))})]})]}),!D&&s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/10 bg-slate-950/40 p-3":"rounded-xl border border-slate-200 bg-slate-50 p-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Git context"}),s.jsx("div",{className:"text-xs text-slate-300",children:F??"No daemon-owned node status is attached to this graph node."}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Recent commits"}),s.jsxs("div",{className:"flex flex-col gap-2",children:[(y==null?void 0:y.loading)&&s.jsx("div",{className:(l.isDark,"text-xs text-slate-500"),children:"Loading recent commits…"}),(y==null?void 0:y.error)&&s.jsxs("div",{className:"text-xs text-amber-200",children:["Recent history unavailable: ",y.error]}),!(y!=null&&y.loading)&&!(y!=null&&y.error)&&((y==null?void 0:y.entries)??[]).length===0&&s.jsx("div",{className:(l.isDark,"text-xs text-slate-500"),children:"Recent commit history not available for this detached graph node yet."}),((y==null?void 0:y.entries)??[]).slice(0,5).map(R=>s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",children:[s.jsxs("div",{className:`font-medium ${l.textPrimary}`,children:[Cr(R.commit)," · ",R.message]}),s.jsxs("div",{className:"mt-1 text-[11px] text-slate-500",children:[R.authorName||"unknown author",Rs(R.committedAt)?` · ${Rs(R.committedAt)}`:""]})]},R.commit))]})]})]})]}):s.jsx("div",{className:`text-xs ${l.textMuted}`,children:"Select a node, session, or queue item."})})}),s.jsxs(hr,{title:"Queue",subtitle:"Active work plus recent history from mesh_status.",children:[s.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:["active","history","all"].map(R=>s.jsx("button",{type:"button",onClick:()=>S(R),className:`rounded-full border px-3 py-1 text-xs transition ${x===R?l.isDark?"border-sky-400/30 bg-sky-500/10 text-sky-100":"border-sky-300 bg-sky-50 text-sky-700":l.isDark?"border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/[0.06]":"border-slate-200 bg-white text-slate-600 hover:bg-slate-50"}`,children:R},R))}),s.jsxs("div",{className:"mb-3 grid grid-cols-2 gap-2 text-xs sm:grid-cols-4 xl:grid-cols-2",children:[s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300":"rounded-xl border border-slate-200 bg-white px-3 py-2 text-slate-600",children:["Active ",s.jsx("span",{className:`ml-1 ${l.textPrimary}`,children:(T==null?void 0:T.active)??0})]}),s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300":"rounded-xl border border-slate-200 bg-white px-3 py-2 text-slate-600",children:["Pending ",s.jsx("span",{className:`ml-1 ${l.textPrimary}`,children:I.pending})]}),s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300":"rounded-xl border border-slate-200 bg-white px-3 py-2 text-slate-600",children:["Assigned ",s.jsx("span",{className:`ml-1 ${l.textPrimary}`,children:I.assigned})]}),s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300":"rounded-xl border border-slate-200 bg-white px-3 py-2 text-slate-600",children:["History ",s.jsx("span",{className:`ml-1 ${l.textPrimary}`,children:(T==null?void 0:T.historical)??0})]})]}),s.jsx("div",{className:"max-h-[24vh] overflow-y-auto pr-1",children:N.length===0?s.jsx("div",{className:`text-xs ${l.textMuted}`,children:"No queue items for this filter."}):s.jsx("div",{className:"flex flex-col gap-2",children:N.map(R=>{const q=Oa(R),ce=q?A.find(je=>je.session.sessionId===q)??null:null,Ne=dn(R);return s.jsxs("button",{type:"button",onClick:()=>h({kind:"queue",taskId:R.id}),className:`rounded-xl border px-3 py-2 text-left transition ${(u==null?void 0:u.kind)==="queue"&&u.taskId===R.id?l.isDark?"border-sky-400/30 bg-sky-500/10":"border-sky-300 bg-sky-50":l.isDark?"border-white/10 bg-white/[0.03] hover:bg-white/[0.06]":"border-slate-200 bg-white hover:bg-slate-50"}`,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:`truncate text-xs font-medium ${l.textPrimary}`,children:R.message}),s.jsx("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:Ba(R)})]}),s.jsx(Ke,{label:R.status,tone:Ea(R.status)})]}),(Ne||ce||q)&&s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[Ne&&s.jsx("button",{type:"button",onClick:je=>{je.stopPropagation(),G(Ne)},className:l.isDark?"text-[11px] text-slate-300 underline underline-offset-2 transition hover:text-white":"text-[11px] text-slate-600 underline underline-offset-2 transition hover:text-slate-900",children:"View node"}),ce&&s.jsx("button",{type:"button",onClick:je=>{je.stopPropagation(),E(ce.nodeId,ce.session.sessionId)},className:l.isDark?"text-[11px] text-slate-300 underline underline-offset-2 transition hover:text-white":"text-[11px] text-slate-600 underline underline-offset-2 transition hover:text-slate-900",children:"View session"}),q&&s.jsx("button",{type:"button",onClick:je=>{je.stopPropagation(),P(q)},className:l.isDark?"text-[11px] text-sky-200 underline underline-offset-2 transition hover:text-white":"text-[11px] text-sky-700 underline underline-offset-2 transition hover:text-sky-900",children:"Open chat"})]})]},R.id)})})})]}),s.jsx(hr,{title:"Sessions",subtitle:"Node-level active session roster.",children:s.jsx("div",{className:"max-h-[22vh] overflow-y-auto pr-1",children:A.length===0?s.jsx("div",{className:`text-xs ${l.textMuted}`,children:"No active session metadata in this mesh snapshot."}):s.jsx("div",{className:"flex flex-col gap-2",children:A.map(R=>{const q=R.session.state||R.session.lifecycle||"unknown";return s.jsx("button",{type:"button",onClick:()=>{m(R.nodeId),h({kind:"session",nodeId:R.nodeId,sessionId:R.session.sessionId})},className:`rounded-xl border px-3 py-2 text-left transition ${(u==null?void 0:u.kind)==="session"&&u.nodeId===R.nodeId&&u.sessionId===R.session.sessionId?l.isDark?"border-sky-400/30 bg-sky-500/10":"border-sky-300 bg-sky-50":l.isDark?"border-white/10 bg-white/[0.03] hover:bg-white/[0.06]":"border-slate-200 bg-white hover:bg-slate-50"}`,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:`truncate text-xs font-medium ${l.textPrimary}`,children:R.machineLabel}),s.jsxs("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:[R.session.title||R.session.providerType||"unknown provider"," · ",R.branch||"no branch"]})]}),s.jsxs("div",{className:"flex flex-col items-end gap-1",children:[s.jsx(Ke,{label:q,tone:cn(q)}),s.jsx("button",{type:"button",onClick:ce=>{ce.stopPropagation(),P(R.session.sessionId)},className:l.isDark?"text-[11px] text-sky-200 underline underline-offset-2 transition hover:text-white":"text-[11px] text-sky-700 underline underline-offset-2 transition hover:text-sky-900",children:"Open chat"})]})]})},`${R.nodeId}:${R.session.sessionId}`)})})})}),s.jsx(hr,{title:"Nodes",subtitle:"Health, branch, drift, and provider view per node.",children:s.jsx("div",{className:"max-h-[22vh] overflow-y-auto pr-1",children:s.jsx("div",{className:"flex flex-col gap-2",children:t.nodes.map(R=>s.jsx("button",{type:"button",onClick:()=>{m(R.nodeId),h({kind:"node",nodeId:R.nodeId})},className:`rounded-xl border px-3 py-2 text-left transition ${(u==null?void 0:u.kind)==="node"&&u.nodeId===R.nodeId?l.isDark?"border-sky-400/30 bg-sky-500/10":"border-sky-300 bg-sky-50":l.isDark?"border-white/10 bg-white/[0.03] hover:bg-white/[0.06]":"border-slate-200 bg-white hover:bg-slate-50"}`,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:`truncate text-xs font-medium ${l.textPrimary}`,children:R.machineLabel}),s.jsx("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:Kl(R)}),s.jsx("div",{className:(l.isDark,"mt-1 truncate text-[11px] text-slate-500"),children:(R.providers??[]).join(", ")||"no provider metadata"}),s.jsxs("div",{className:"mt-1 flex flex-wrap gap-1",children:[s.jsx(Ke,{label:`launchReady ${$a(R.launchReady)}`,tone:R.launchReady?"good":"warn"}),s.jsx(Ke,{label:Au(R.connection),tone:Fl(R.connection)})]})]}),s.jsxs("div",{className:"flex flex-col items-end gap-1",children:[s.jsx(Ke,{label:R.health,tone:Ol(R.health)}),R.machineStatus&&s.jsx(Ke,{label:R.machineStatus,tone:R.machineStatus==="online"?"good":"warn"}),R.activeSessions.length>0&&s.jsx(Ke,{label:`${R.activeSessions.length} sessions`,tone:"info"})]})]})},R.nodeId))})})}),s.jsx(hr,{title:"Recent mesh events",subtitle:"Read-only ledger tail from mesh_status.",children:s.jsx("div",{className:"max-h-[18vh] overflow-y-auto pr-1",children:(((de=t.ledger)==null?void 0:de.entries)??[]).length===0?s.jsx("div",{className:`text-xs ${l.textMuted}`,children:"No recent ledger entries."}):s.jsx("div",{className:"flex flex-col gap-2",children:(((re=t.ledger)==null?void 0:re.entries)??[]).map(R=>s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-xl border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("span",{className:`font-medium ${l.textPrimary}`,children:R.kind}),s.jsx("span",{className:(l.isDark,"text-[11px] text-slate-500"),children:ps(R.timestamp)??R.timestamp})]}),s.jsx("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:R.nodeId||R.sessionId||R.providerType||"mesh-wide event"})]},R.id))})})})]})]})})}function kt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Re(...e){for(const t of e){if(typeof t!="string")continue;const r=t.trim();if(r)return r}}function $t(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function Dt(...e){for(const t of e)if(typeof t=="boolean")return t}function Fa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function _0(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 L0(e,t){if(!Array.isArray(e))return;const r=e.map(n=>{const a=kt(n),o=Re(a.path),l=Re(a.commit),c=Re(a.repoPath,a.repo_root)??_0(t,o);return!o||!l||!c?null:{path:o,commit:l,repoPath:c,dirty:Dt(a.dirty)??!1,outOfSync:Dt(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:$t(a.lastCheckedAt,a.last_checked_at)??Date.now(),...Re(a.error)?{error:Re(a.error)}:{}}}).filter(n=>n!==null);return r.length>0?r:void 0}function ko(e,t,r){const n=Dt(e.isGitRepo);if(!Object.keys(e).length||n===void 0)return;const a=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(h=>typeof h=="string"):[],o=$t(e.conflicts)??a.length,l=Dt(e.hasConflicts)??o>0,c=Re(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,d=L0(e.submodules,c),m=Re(e.upstreamStatus,e.upstream_status),u=Re(e.error);return{workspace:Re(e.workspace,t.workspace)||"",repoRoot:c??null,isGitRepo:n,branch:Re(e.branch)??null,headCommit:Re(e.headCommit)??null,headMessage:Re(e.headMessage)??null,upstream:Re(e.upstream)??null,upstreamStatus:m??"unchecked",ahead:$t(e.ahead)??0,behind:$t(e.behind)??0,staged:$t(e.staged)??0,modified:$t(e.modified)??0,untracked:$t(e.untracked)??0,deleted:$t(e.deleted)??0,renamed:$t(e.renamed)??0,hasConflicts:l,conflictFiles:a,stashCount:$t(e.stashCount,e.stash_count)??0,lastCheckedAt:(r==null?void 0:r.lastCheckedAt)??$t(e.lastCheckedAt,e.last_checked_at)??Date.now(),...d?{submodules:d}:{},...u?{error:u}:{}}}function R0(e){const t=kt(e.lastGit??e.last_git),r=kt(t.result),n=kt(t.status),a=kt(r.status),o=kt(e.lastProbe??e.last_probe),l=kt(o.git),c=kt(l.result),d=kt(l.status),m=kt(c.status),u=Object.keys(n).length?n:Object.keys(a).length?a:Object.keys(d).length?d:Object.keys(m).length?m:{};return ko(u,e,{lastCheckedAt:Date.now()})}function P0(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 D0(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 zl(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=P0(e);return t.outOfSync?"degraded":t.dirty||D0(e)?"dirty":"online"}function E0(e){const t=Array.isArray(e.activeSessionDetails)?e.activeSessionDetails:Array.isArray(e.active_session_details)?e.active_session_details:null;if(t){const a=t.map(o=>{const l=kt(o),c=Re(l.sessionId,l.session_id,l.id);return c?{sessionId:c,...Re(l.providerType,l.provider)?{providerType:Re(l.providerType,l.provider)}:{},...Re(l.state,l.status)?{state:Re(l.state,l.status)}:{},...Re(l.lifecycle)?{lifecycle:Re(l.lifecycle)}:{},...Re(l.surfaceKind,l.surface_kind)?{surfaceKind:Re(l.surfaceKind,l.surface_kind)}:{},...Re(l.recoveryState,l.recovery_state)?{recoveryState:Re(l.recoveryState,l.recovery_state)}:{},...Re(l.workspace)?{workspace:Re(l.workspace)}:{},...Re(l.title)?{title:Re(l.title)}:{},...Re(l.lastActivityAt,l.last_activity_at)?{lastActivityAt:Re(l.lastActivityAt,l.last_activity_at)}:{},...Dt(l.isCached,l.is_cached)!==void 0?{isCached:Dt(l.isCached,l.is_cached)}:{}}:null}).filter(o=>o!==null);if(a.length>0)return a}const r=kt(e.activeSession??e.active_session),n=Re(r.id,r.sessionId,r.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id);if(n)return[{sessionId:n,...Re(r.providerType,r.provider)?{providerType:Re(r.providerType,r.provider)}:{},...Re(r.state,r.status)?{state:Re(r.state,r.status)}:{}}]}function Vl(e){const t=kt(e.connection);return Object.keys(t).length>0?t:void 0}function $0(e){const t=kt(e),r=Re(t.nodeId,t.id);if(!r)return null;const n=kt(t.cachedStatus),a=R0(t),o=a?void 0:ko(kt(t.git),t),l=a??o,c=l?void 0:ko(kt(n.git),t),d=l??c,m=Re(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),u=a?zl(d):Re(t.health)||(d?zl(d):void 0)||Re(n.health)||m||Re(t.status)||"unknown",x=(a?void 0:Re(t.error))??(l?void 0:Re(n.error)),S=E0(t),b=Fa(t.activeSessions),p=(S==null?void 0:S.map(v=>v.sessionId))??[],g=Fa(t.providerPriority);return{nodeId:r,machineLabel:Re(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,r)||r,workspace:Re(t.workspace,d==null?void 0:d.workspace)||"",...Re(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:Re(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)}:{},...Re(t.daemonId,t.daemon_id)?{daemonId:Re(t.daemonId,t.daemon_id)}:{},...Re(t.machineId,t.machine_id)?{machineId:Re(t.machineId,t.machine_id)}:{},...m?{machineStatus:m}:{},...Dt(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:Dt(t.isLocalWorktree,t.is_local_worktree)}:{},...Re(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:Re(t.worktreeBranch,t.worktree_branch)}:{},health:u,...d?{git:d}:{},...Dt(t.gitProbePending,t.git_probe_pending)!==void 0?{gitProbePending:Dt(t.gitProbePending,t.git_probe_pending)}:{},providers:Fa(t.providers),activeSessions:b.length>0?b:p,...S&&S.length>0?{activeSessionDetails:S}:{},...g.length>0?{providerPriority:g}:{},...Dt(t.launchReady)!==void 0?{launchReady:Dt(t.launchReady)}:{},...Re(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)?{lastSeenAt:Re(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)}:{},...Re(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)?{updatedAt:Re(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)}:{},...Vl(t)?{connection:Vl(t)}:{},...x?{error:x}:{}}}function B0(e){const t=Re(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(c=>$0(c)).filter(c=>c!==null):null;if(!t||!n)return null;const a=Re(e.meshName,e.mesh_name,e.name),o=Re(e.repoIdentity,e.repo_identity),l=Re(e.refreshedAt,e.refreshed_at,e.updatedAt,e.updated_at);return!a||!o||!l?null:{...e,meshId:t,meshName:a,repoIdentity:o,refreshedAt:l,nodes:n}}function Lu(e){const t=(e==null?void 0:e.result)??e,r=[e==null?void 0:e.status,t==null?void 0:t.status,t,e];for(const n of r){const a=B0(kt(n));if(a)return a}return null}function O0({activeConv:e,sendDaemonCommand:t,onClose:r}){var A;const n=typeof((A=e.settings)==null?void 0:A.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null,a=e.daemonId??null,o=Vd(),{theme:l}=er(),c=i.useMemo(()=>tr(l),[l]),[d,m]=i.useState(null),[u,h]=i.useState(null),[x,S]=i.useState(!1),[b,p]=i.useState(null),[g,v]=i.useState(null),f=i.useCallback(async()=>{if(!a||!n){p("This coordinator does not expose a live mesh id."),m(null),h(null);return}S(!0),p(null);try{const _=o!=null&&o.loadMeshStatus?await o.loadMeshStatus(a,n):await t(a,"mesh_status",{meshId:n}),N=Lu(_);if(!N){m(null),h(null),p("mesh_status returned an unexpected payload.");return}const w=ju(N);h(N),m(w),v(N.refreshedAt||new Date().toISOString())}catch(_){m(null),h(null),p(_ instanceof Error?_.message:"Failed to load live mesh status")}finally{S(!1)}},[a,n,o,t]);i.useEffect(()=>{f()},[f]),i.useEffect(()=>{const _=N=>{N.key==="Escape"&&r()};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[r]);const T=(d==null?void 0:d.meshName)||(u==null?void 0:u.meshName)||n||"Repo Mesh",I=g?new Date(g).toLocaleTimeString():null,k=i.useMemo(()=>x?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[x]);return s.jsx("div",{className:c.dialogOverlayClass,onClick:r,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:c.dialogShellClass,onClick:_=>_.stopPropagation(),children:[s.jsxs("div",{className:c.dialogHeaderClass,children:[s.jsx("div",{className:"min-w-0 flex-1",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-sky-400/20 bg-sky-500/12 text-sky-200 shadow-[0_12px_30px_rgba(14,165,233,0.18)]",children:s.jsx(as,{size:18})}),s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("h2",{className:c.dialogTitleClass,children:T}),s.jsx("span",{className:c.dialogKickerClass,children:"Mesh observability"})]}),s.jsxs("p",{className:c.dialogSubtitleClass,children:[ut(e),e.workspaceName?` · ${e.workspaceName}`:"",d!=null&&d.repoIdentity?` · ${d.repoIdentity}`:""]})]})]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end",children:[I&&s.jsxs("span",{className:c.dialogRefreshedChipClass,children:["Refreshed ",I]}),s.jsx("button",{type:"button",onClick:f,disabled:x,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:x?"Refreshing…":"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:c.dialogCloseButtonClass,"aria-label":"Close mesh graph",children:s.jsx(wt,{size:16})})]})]}),b&&s.jsx("div",{className:c.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:b}),s.jsx("div",{className:c.dialogBodyClass,children:d&&u?s.jsx(_u,{graph:d,status:u,emptyMessage:k,daemonId:a,sendDaemonCommand:t}):s.jsx("div",{className:c.dialogEmptyClass,children:k})})]})})}function F0(e,t){const{sendCommand:r}=jt(),[n,a]=i.useState(null),[o,l]=i.useState(!1);i.useEffect(()=>{if(!e||!t){a(null);return}l(!0),r(e,"git_remote_url",{workspace:t}).then(d=>{const m=(d==null?void 0:d.result)??d;a(typeof(m==null?void 0:m.remoteUrl)=="string"?m.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>l(!1))},[e,t,r]);const c=W0(n);return{remoteUrl:n,githubUrl:c,loading:o}}function W0(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 Ru=5e3;function K0(e){return`git:${e}`}function H0({workspace:e,includeDiffSummary:t=!1,intervalMs:r=Ru}){return{type:"subscribe",topic:"workspace.git",key:K0(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function mi(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Ms(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 U0(e){const t=mi(e);return(t==null?void 0:t.success)===!1?{status:null,error:Ms(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:Ms(t,"Git status response did not include status")}}function z0(e){const t=mi(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:Ms(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:Ms(t,"Git diff summary response did not include diffSummary")}}function Wa(e){return e===void 0||typeof e=="boolean"}function V0(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Wa(t.binary)&&Wa(t.truncated)&&Wa(t.staged)}function G0(e){const t=mi(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Ms(t,"Git file diff request failed")}:V0(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:Ms(t,"Git file diff response did not include a valid diff object")}}function q0({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=Ru}){const{sendCommand:o,sendData:l}=jt(),c=typeof t=="string"?t.trim():"",d=!!(r&&e&&c),[m,u]=i.useState(null),[h,x]=i.useState(null),[S,b]=i.useState(!1),[p,g]=i.useState(null),v=i.useCallback(async()=>{if(!(!d||!e||!c)){b(!0),g(null);try{const T=U0(await o(e,"git_status",{workspace:c}));if(T.error){u(null),x(null),g(T.error);return}if(u(T.status),!n){x(null);return}const I=z0(await o(e,"git_diff_summary",{workspace:c}));if(I.error){x(null),g(I.error);return}x(I.diffSummary)}catch(T){g(Ms(T,"Git status request failed"))}finally{b(!1)}}},[d,e,n,o,c]),f=i.useMemo(()=>c?H0({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return i.useEffect(()=>{if(!d||!e||!c||!f){u(null),x(null),b(!1),g(null);return}const T=l?Qt.subscribe({sendData:l},e,f,I=>{var k,A;I.workspace===c&&(u(I.status),x(I.diffSummary??null),g(((k=I.status)==null?void 0:k.error)||((A=I.diffSummary)==null?void 0:A.error)||null),b(!1))},{retryIntervalMs:1e3}):null;return v(),()=>{T==null||T()}},[d,e,v,f,l,c]),{status:m,diffSummary:h,loading:S,error:p,refresh:v}}const Y0={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},X0={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 Gl(e){return e.split("/").pop()??e}function J0(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function Q0({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 l=n===o.path,c=Y0[o.status]??"?",d=X0[o.status]??"text-zinc-400",m=J0(o.path),u=Gl(o.path),h=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 ${l?"bg-surface-elevated":""}`,onClick:()=>r==null?void 0:r(o),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${d}`,title:o.status,children:c}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[m&&s.jsxs("span",{className:"text-text-secondary",children:[m,"/"]}),s.jsx("span",{className:"text-text-primary",children:u}),o.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",Gl(o.oldPath)]}),h]}),!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 Z0(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 ev({diff:e,binary:t,truncated:r,loading:n,error:a,className:o=""}){const l=i.useRef(null);if(i.useEffect(()=>{l.current&&(l.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(`
|
|
65
|
-
`);return s.jsxs("div",{ref:l,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:c.map((d,m)=>
|
|
66
|
-
`)}function Pu({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=jt(),{status:a,diffSummary:o,loading:l,error:c,refresh:d}=q0({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,u]=i.useState(null),[h,x]=i.useState(null),[S,b]=i.useState(""),[p,g]=i.useState(!1),[v,f]=i.useState(!1),[T,I]=i.useState(null),[k,A]=i.useState(null),{githubUrl:_}=F0(e,t),N=i.useCallback(async H=>{if(!((m==null?void 0:m.path)===H.path&&!m.loading)){u({path:H.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const $=await n(e,"git_diff_file",{workspace:t,path:H.path,staged:H.staged}),C=G0($);if(C.error||!C.diff){u({path:H.path,diff:"",binary:!1,truncated:!1,loading:!1,error:C.error??"Failed to load diff"});return}u({path:H.path,diff:C.diff.diff,binary:C.diff.binary??!1,truncated:C.diff.truncated??!1,loading:!1,error:null})}catch($){const C=$ instanceof Error?$.message:"Failed to load diff";u({path:H.path,diff:"",binary:!1,truncated:!1,loading:!1,error:C})}}},[e,n,m,t]),w=i.useCallback(H=>{b(""),g(!1),I(null),A(null),x(H)},[]),D=i.useCallback(()=>{x(null),I(null),f(!1)},[]),M=i.useCallback(async()=>{var H,$,C;if(h){f(!0),I(null);try{let y;h==="checkpoint"?y=await n(e,"git_checkpoint",{workspace:t,message:S,includeUntracked:p}):h==="stash"?y=await n(e,"git_stash_push",{workspace:t,message:S,includeUntracked:p}):h==="stash_pop"?y=await n(e,"git_stash_pop",{workspace:t}):h==="checkout_files"&&m&&(y=await n(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const F=(y==null?void 0:y.result)??y;if((F==null?void 0:F.success)===!1||F!=null&&F.error){I((F==null?void 0:F.error)??"Action failed"),f(!1);return}h==="checkpoint"?A(`Checkpoint created: ${(($=(H=F==null?void 0:F.checkpoint)==null?void 0:H.commit)==null?void 0:$.slice(0,7))??"done"}`):h==="stash"?A(`Stashed as ${((C=F==null?void 0:F.stash)==null?void 0:C.stashRef)??"stash@{0}"}`):h==="stash_pop"?A("Stash restored"):(A("File reverted"),u(null)),x(null),await d()}catch(y){I(y instanceof Error?y.message:"Action failed")}finally{f(!1)}}},[h,n,e,t,S,p,m,d]),j=!!(a!=null&&a.hasConflicts),W=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:H=>{H.target===H.currentTarget&&r()},children:s.jsxs("div",{className:"relative flex h-[80vh] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[s.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??"Git Status"}),s.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),_&&s.jsx("a",{href:`${_}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-sky-400 underline",title:"Open on GitHub",children:"GitHub ↗"})]}),s.jsx("button",{onClick:d,disabled:l,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(wt,{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"}),W===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:[l&&!o&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),o&&s.jsx(Q0,{files:o.files,truncated:o.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:N}),!l&&!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(ev,{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:()=>A(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:()=>w("checkpoint"),disabled:j,title:j?"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:()=>w("stash"),disabled:j,title:j?"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:()=>w("stash_pop"),disabled:j||!(a!=null&&a.stashCount),title:j?"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:()=>w("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 H=tv((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(H),A("Copied to clipboard"),setTimeout(()=>A(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),h&&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:[h==="checkpoint"&&"Create checkpoint commit",h==="stash"&&"Stash changes",h==="stash_pop"&&"Restore latest stash?",h==="checkout_files"&&`Revert changes to ${(m==null?void 0:m.path)??"file"}?`]}),(h==="checkpoint"||h==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:S,onChange:H=>b(H.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:p,onChange:H=>g(H.target.checked)}),"Include untracked files"]})]}),T&&s.jsx("p",{className:"text-xs text-red-400",children:T}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:D,disabled:v,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:M,disabled:v||(h==="checkpoint"||h==="stash")&&!S.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:v?"Working…":"Confirm"})]})]})})]})})}function sv({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=i.useState(!1),[o,l]=i.useState(!1),[c,d]=i.useState(!1),[m,u]=i.useState(!1),[h,x]=i.useState(!1),[S,b]=i.useState("quickstart"),[p,g]=i.useState("workspace"),v=i.useMemo(()=>!t&&!e,[t,e]),f=i.useCallback(N=>{a(N),N&&l(!1)},[]),T=i.useCallback(N=>{l(N),N&&a(!1)},[]),I=i.useCallback(()=>{b(r===0?"quickstart":"shortcuts"),g("workspace"),d(!0),a(!1),l(!1)},[r]),k=i.useCallback(()=>{d(!1)},[]),A=i.useCallback(()=>{u(!0)},[]),_=i.useCallback(()=>{u(!1)},[]);return i.useEffect(()=>{if(!v){x(!1);return}x(!0);const N=window.setTimeout(()=>{x(!1)},1e4);return()=>window.clearTimeout(N)},[v]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:m,guideNudgeVisible:h,guideTab:S,shortcutSection:p,isDesktopDashboard:v,setGuideTab:b,setShortcutSection:g,handleInboxOpenChange:f,handleHiddenOpenChange:T,handleOpenShortcutHelp:I,closeShortcutHelp:k,openNewSession:A,closeNewSession:_}}function rv(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 nv(e){return e instanceof Error?e.message:String(e||"")}function av(e){const t=nv(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function ov({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:l,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:m,mobileChatConversations:u,hiddenConversations:h,ides:x,actionLogs:S,sendDaemonCommand:b,setActionLogs:p,setCliViewModeOverrides:g,isStandalone:v,initialDataLoaded:f,userName:T,requestedMobileTabKey:I,onRequestedMobileTabConsumed:k,requestedMachineId:A,onRequestedMachineConsumed:_,requestedMobileSection:N,onRequestedMobileSectionConsumed:w,containerRef:D,isSplitMode:M,numGroups:j,groupSizes:W,groupedConvs:H,clearedTabs:$,focusedGroup:C,focusGroup:y,moveTabToGroup:F,splitTabRelative:P,closeGroup:E,handleResizeStart:G,groupActiveTabIds:J,setGroupActiveTab:ye,groupTabOrders:he,setGroupTabOrder:ne,toggleHiddenTab:ue,visibleConversations:Se,requestedDesktopTabKey:ve,onRequestedDesktopTabConsumed:X,onDesktopActiveTabChange:xe,onRequestScrollToBottom:fe,onHideConversation:we,onShowHiddenConversation:be,onShowAllHiddenConversations:Ce,scrollToBottomRequest:ee,machineEntries:me,layoutProfile:ie,onBrowseMachineDirectory:pe,onSaveMachineWorkspace:le,onLaunchMachineIde:B,onLaunchMachineProvider:z,onListMachineMeshes:de,onLaunchMeshCoordinator:re,onListMachineSavedSessions:R,notifications:q,notificationUnreadCount:ce,liveSessionInboxState:Ne,onMarkNotificationRead:je,onMarkNotificationUnread:O,onDeleteNotification:Ie}){const Le=Nt.useRef(null),{inboxOpen:He,hiddenOpen:ze,shortcutHelpOpen:Xe,newSessionOpen:Je,guideNudgeVisible:rt,guideTab:pt,shortcutSection:xt,isDesktopDashboard:vt,setGuideTab:Te,setShortcutSection:Ve,handleInboxOpenChange:tt,handleHiddenOpenChange:Ge,handleOpenShortcutHelp:ot,closeShortcutHelp:U,openNewSession:V,closeNewSession:Z}=sv({isMobile:t,showMobileChatMode:e,visibleConversationCount:Se.length}),[ae,K]=Nt.useState(null),[Y,se]=Nt.useState(null),oe=Nt.useCallback((L,Q)=>{K({daemonId:L,workspace:Q})},[]),ke=Nt.useCallback(L=>{se(L)},[]),Pe=Nt.useCallback(L=>{var Q;Tr.flushSync(()=>{be(L)}),(Q=Le.current)==null||Q.restoreHiddenTabToSavedLocation(L.tabKey)},[be]),Ee=Nt.useCallback(L=>{var ge;const Q=u.find(Be=>uo(Be,L))||h.find(Be=>uo(Be,L));Q&&(h.some(Be=>Be.tabKey===Q.tabKey)&&Pe(Q),xe(Q.tabKey),(ge=Le.current)==null||ge.activateConversationTab(Q.tabKey),fe(Q.tabKey,"notification-open")),je(L.id),tt(!1)},[Pe,h,u,xe,je,fe]),Ae=Nt.useCallback(()=>{var Q;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Q=Le.current)==null||Q.resetAllPanelsToMain(),Ge(!1))},[Ge]),$e=Nt.useCallback(async L=>{var Oe;if(!r)return;const Q=(Oe=r.modalButtons)==null?void 0:Oe[L];if(!Q)return;const ge=Gs(r);if(!ge)return;const Be=Q.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),_e=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(Be);try{await b(ge,"resolve_action",{button:Q,action:_e?"approve":"reject",buttonIndex:L,...xs(r)})}catch(nt){av(nt)||console.error("[Shortcut approval] Failed:",nt)}},[r,b]),{isMac:Fe,actionDefinitions:Me,actionShortcuts:Qe,shortcutListening:et,shortcutListeningDraft:bt,setShortcutListening:gt,setShortcutListeningDraft:dt,saveShortcuts:ht}=Iy({enabled:vt&&!Xe,onTrigger:L=>{var Q,ge,Be,_e,Oe,nt,Mt,ft,ss,Fr,Wr,Kr,Hr,Ur,zr,Vr;if(L==="openShortcutHelp"){ot();return}if(L==="openNewSession"){V();return}if(L==="hideCurrentTab"){r&&we(r);return}if(L==="toggleHiddenTabs"){Ge(!ze);return}if(L==="openHistoryForActiveTab"){r&&!st(r)&&o(r);return}if(L==="openRemoteForActiveTab"){r&&!at(r)&&!st(r)&&l(r);return}if(L==="splitActiveTabRight"){(Q=Le.current)==null||Q.splitActiveTabRight();return}if(L==="splitActiveTabDown"){(ge=Le.current)==null||ge.splitActiveTabDown();return}if(L==="floatActiveTab"){(Be=Le.current)==null||Be.floatActiveTab();return}if(L==="popoutActiveTab"){(_e=Le.current)==null||_e.popoutActiveTab();return}if(L==="dockActiveTab"){(Oe=Le.current)==null||Oe.dockActiveTab();return}if(L==="focusLeftPane"){(nt=Le.current)==null||nt.focusLeftPane();return}if(L==="focusRightPane"){(Mt=Le.current)==null||Mt.focusRightPane();return}if(L==="focusUpPane"){(ft=Le.current)==null||ft.focusUpPane();return}if(L==="focusDownPane"){(ss=Le.current)==null||ss.focusDownPane();return}if(L==="moveActiveTabToLeftPane"){(Fr=Le.current)==null||Fr.moveActiveTabToLeftPane();return}if(L==="moveActiveTabToRightPane"){(Wr=Le.current)==null||Wr.moveActiveTabToRightPane();return}if(L==="moveActiveTabToUpPane"){(Kr=Le.current)==null||Kr.moveActiveTabToUpPane();return}if(L==="moveActiveTabToDownPane"){(Hr=Le.current)==null||Hr.moveActiveTabToDownPane();return}if(L==="triggerPrimaryApprovalAction"){$e(0);return}if(L==="triggerSecondaryApprovalAction"){$e(1);return}if(L==="triggerTertiaryApprovalAction"){$e(2);return}if(L==="setActiveTabShortcut"){(Ur=Le.current)==null||Ur.setShortcutForActiveTab();return}if(L==="selectPreviousGroupTab"){(zr=Le.current)==null||zr.activatePreviousTabInGroup();return}if(L==="selectNextGroupTab"){(Vr=Le.current)==null||Vr.activateNextTabInGroup();return}!r||!at(r)||st(r)||L==="toggleCliView"&&m(d==="chat"?"terminal":"chat")}}),Ue=Nt.useCallback(()=>{U(),gt(null),dt([])},[U,gt,dt]),Kt=Nt.useMemo(()=>xt==="all"?Me:Me.filter(L=>rv(L)===xt),[Me,xt]),te=Nt.useCallback(()=>{const L=Object.fromEntries(Me.map(Q=>[Q.id,""]));ht(L)},[Me,ht]),De=Nt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const L=Object.fromEntries(Me.map(Q=>[Q.id,Q.defaultShortcut]));ht(L)},[Me,ht]);return Nt.useEffect(()=>{const L=Q=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Q.metaKey&&Q.key.toLowerCase()==="w":Q.ctrlKey&&Q.key.toLowerCase()==="w")&&(Q.preventDefault(),r&&we&&we(r))};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[r,we]),Nt.useEffect(()=>{if(!Xe||et)return;const L=Q=>{Q.key==="Escape"&&(Q.preventDefault(),Ue())};return window.addEventListener("keydown",L,!0),()=>window.removeEventListener("keydown",L,!0)},[Ue,Xe,et]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(Nx,{activeConv:r,wsStatus:n,isConnected:a,conversations:Se,hiddenConversations:h,onOpenHistory:o,onHideConversation:we,onShowConversation:Pe,onShowAllHidden:Ce,onResetPanelsToMain:Ae,notifications:q,notificationUnreadCount:ce,onOpenNotification:Ee,onMarkNotificationRead:je,onMarkNotificationUnread:O,onDeleteNotification:Ie,inboxOpen:He,onInboxOpenChange:tt,hiddenOpen:ze,onHiddenOpenChange:Ge,onOpenNewSession:t?void 0:V,onOpenDashboardGuide:ot,guideNudgeVisible:rt,actionShortcuts:Qe,onOpenRemote:()=>{!r||at(r)||st(r)||l(r)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:m,onOpenGitDialog:oe,onOpenMeshGraph:ke}),e?s.jsx(fy,{conversations:u,hiddenConversations:h,ides:x,actionLogs:S,sendDaemonCommand:b,setActionLogs:p,setCliViewModeOverrides:g,isStandalone:v,userName:T,requestedActiveTabKey:I,onRequestedActiveTabConsumed:k,requestedMachineId:A,onRequestedMachineConsumed:_,requestedMobileSection:N,onRequestedMobileSectionConsumed:w,onOpenHistory:o,onOpenRemote:l,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:Ce,onHideConversation:we,onOpenMeshGraph:ke,onOpenNewSession:V,liveSessionInboxState:Ne}):t?s.jsx(ky,{containerRef:D,isSplitMode:M,numGroups:j,groupSizes:W,groupedConvs:H,clearedTabs:$,ides:x,actionLogs:S,sendDaemonCommand:b,setActionLogs:p,isStandalone:v,hasRegisteredMachines:me.length>0,userName:T,focusedGroup:C,focusGroup:y,moveTabToGroup:F,splitTabRelative:P,closeGroup:E,handleResizeStart:G,groupActiveTabIds:J,setGroupActiveTab:ye,groupTabOrders:he,setGroupTabOrder:ne,toggleHiddenTab:ue,onOpenNewSession:V,allowTabShortcuts:!1,liveSessionInboxState:Ne}):s.jsx(Wy,{visibleConversations:Se,clearedTabs:$,ides:x,actionLogs:S,sendDaemonCommand:b,setActionLogs:p,isStandalone:v,hasRegisteredMachines:me.length>0,initialDataLoaded:f,userName:T,toggleHiddenTab:ue,actionShortcuts:Qe,registerActionHandlers:L=>{Le.current=L},onActiveTabChange:xe,requestedActiveTabKey:ve,onRequestedActiveTabConsumed:X,onRequestScrollToBottom:fe,scrollToBottomRequest:ee,onOpenNewSession:V,liveSessionInboxState:Ne,layoutProfile:ie}),Je&&s.jsx(Vy,{machines:me,ides:x,onClose:Z,onBrowseDirectory:pe,onSaveWorkspace:le,onLaunchIde:B,onLaunchProvider:z,onListMeshes:de,onLaunchMeshCoordinator:re,onListSavedSessions:R}),Y&&s.jsx(O0,{activeConv:Y,sendDaemonCommand:b,onClose:()=>se(null)}),ae&&s.jsx(Pu,{daemonId:ae.daemonId,workspace:ae.workspace,onClose:()=>K(null)}),Xe&&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:Ue,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:L=>L.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:Ue,"aria-label":"Close dashboard guide",children:s.jsx(wt,{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(L=>s.jsx("button",{type:"button",className:`btn btn-sm ${pt===L.id?"btn-primary":"btn-secondary"}`,onClick:()=>Te(L.id),children:L.label},L.id))}),pt==="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 ",Fe?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),pt==="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."]})]})]})]}),pt==="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(L=>s.jsx("button",{type:"button",className:`btn btn-sm ${xt===L.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ve(L.id),children:L.label},L.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:te,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:Kt.map(L=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${et===L.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:L.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:L.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:L.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:et===L.id?bt.length>0?`${bt.join(" ")} ...`:"Listening...":Qe[L.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{gt(L.id),dt([])},children:et===L.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Q={...Qe};Q[L.id]="",ht(Q)},children:"Disable"})]})]})},L.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Fe?"⌘⇧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 Ka=[{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 iv({onClose:e}){const[t,r]=i.useState(0),n=Ka[t],a=t===Ka.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(wt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Ka.map((o,l)=>s.jsx("div",{style:{width:l===t?24:8,height:8,borderRadius:4,background:l===t?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},l))}),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:`
|
|
64
|
+
`,Y.style.top="52px",Y.style.height="calc(100% - 52px)";const $e=Ae.querySelector("[data-adhdev-popout-focus]");$e&&($e.onclick=()=>{window.focus()});const Fe=Ae.querySelector("[data-adhdev-popout-dock]");Fe&&(Fe.disabled=!se,Fe.style.opacity=se?"1":"0.5",Fe.style.cursor=se?"pointer":"default",Fe.onclick=()=>{var Me;se&&ve(se),(Me=K.defaultView)==null||Me.focus()})}},[G,ve]),ie=i.useCallback(U=>{var ae;const V=N.current,Z=V==null?void 0:V.getPanel(U);if(!(!V||!Z)){Z.group.model.openPanel(Z),Z.api.setActive(),he(U,"dockview-shortcut");try{const K=Z.group.model.location;K.type==="popout"?K.getWindow().focus():_a((ae=Z.group.element)==null?void 0:ae.ownerDocument)}catch{}}},[he]),pe=i.useCallback(U=>{const V=N.current,Z=V==null?void 0:V.activePanel,ae=(V==null?void 0:V.activeGroup)||(Z==null?void 0:Z.group);if(!V||!Z||!ae)return;const K=ae.panels||[];if(K.length<=1)return;const Y=K.findIndex(ke=>ke.id===Z.id);if(Y<0)return;const se=(Y+U+K.length)%K.length,oe=K[se];oe&&(oe.group.model.openPanel(oe),oe.api.setActive(),Bt(oe.id)||he(oe.id,"dockview-shortcut"))},[he]),le=i.useCallback(U=>{var $e;const V=N.current,Z=(V==null?void 0:V.activeGroup)||(($e=V==null?void 0:V.activePanel)==null?void 0:$e.group);if(!V||!Z)return;const ae=V.groups||[],K=ae.find(Fe=>Fe.id===Z.id);if(!K)return;const Y=K.element.getBoundingClientRect(),se=Y.left+Y.width/2,oe=Y.top+Y.height/2,ke=(Fe,Me,Qe,et)=>Math.max(0,Math.min(Me,et)-Math.max(Fe,Qe)),Pe=Fe=>{const Me=Fe.element.getBoundingClientRect(),Qe=Me.left+Me.width/2,et=Me.top+Me.height/2;let bt=0,gt=0,dt=0,ht=!1;if(U==="left"?(ht=Qe<se,bt=Math.max(0,Y.left-Me.right),gt=Math.abs(et-oe),dt=ke(Y.top,Y.bottom,Me.top,Me.bottom)):U==="right"?(ht=Qe>se,bt=Math.max(0,Me.left-Y.right),gt=Math.abs(et-oe),dt=ke(Y.top,Y.bottom,Me.top,Me.bottom)):U==="above"?(ht=et<oe,bt=Math.max(0,Y.top-Me.bottom),gt=Math.abs(Qe-se),dt=ke(Y.left,Y.right,Me.left,Me.right)):(ht=et>oe,bt=Math.max(0,Me.top-Y.bottom),gt=Math.abs(Qe-se),dt=ke(Y.left,Y.right,Me.left,Me.right)),!ht)return Number.POSITIVE_INFINITY;const Ue=dt>0?0:120;return bt*3+gt+Ue};let Ee=null,Ae=Number.POSITIVE_INFINITY;for(const Fe of ae){if(Fe.id===K.id)continue;const Me=Pe(Fe);Number.isFinite(Me)&&(Me>=Ae||(Ae=Me,Ee=Fe))}return Ee||void 0},[]),B=i.useCallback(U=>{var ae;const V=le(U);if(!V)return;const Z=V.activePanel||V.panels[0];Z&&(V.model.openPanel(Z),Z.api.setActive(),Bt(Z.id)||he(Z.id,"dockview-focus"),_a((ae=V.element)==null?void 0:ae.ownerDocument))},[le,he]),z=i.useCallback((U,V)=>{const Z=N.current,ae=Z==null?void 0:Z.activePanel,K=(Z==null?void 0:Z.activeGroup)||(ae==null?void 0:ae.group);if(!Z||!ae||!K)return;let Y=le(U);!Y&&(V!=null&&V.createGroupIfMissing)&&(Y=Z.addGroup({referenceGroup:K,direction:U})),Y&&(ae.api.moveTo({group:Y,position:"center"}),ae.group.model.openPanel(ae),ae.api.setActive(),Bt(ae.id)||he(ae.id,V!=null&&V.createGroupIfMissing?"dockview-split":"dockview-move"))},[le,he]),{isMac:de,tabShortcuts:re,shortcutListening:R,setShortcutListening:q,saveShortcuts:ce}=au({sortedTabKeys:e.map(U=>U.tabKey),onFocus:ye,onSelectTab:ie}),Ne=i.useCallback(()=>{var Z;const U=N.current;if(!U)return;const V=U.activePanel;if(V){if(Bt(V.id)){const ae=((Z=V.params)==null?void 0:Z.routeId)||V.id.slice(7),K=Wt(e,ae);K!=null&&K.tabKey&&q(K.tabKey);return}G.has(V.id)&&q(V.id)}},[G,ie,q,e]),je=i.useCallback(U=>{const V=[];return U.metaKey&&V.push(de?"⌘":"Meta"),U.ctrlKey&&V.push("Ctrl"),U.altKey&&V.push(de?"⌥":"Alt"),U.shiftKey&&U.key.length!==1&&V.push(de?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(U.key)?null:(V.push(cu(U.key)),V.join("+"))},[de]),O=i.useCallback(U=>{var V,Z;switch(U){case"splitActiveTabRight":z("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":z("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const ae=be();ae&&fe(ae);return}case"popoutActiveTab":{const ae=be();ae&&Se(ae);return}case"dockActiveTab":{const ae=be();if(!ae)return;X(ae)?ve(ae):we(ae)&&Ce(ae);return}case"focusLeftPane":B("left");return;case"focusRightPane":B("right");return;case"focusUpPane":B("above");return;case"focusDownPane":B("below");return;case"moveActiveTabToLeftPane":z("left");return;case"moveActiveTabToRightPane":z("right");return;case"moveActiveTabToUpPane":z("above");return;case"moveActiveTabToDownPane":z("below");return;case"selectPreviousGroupTab":pe(-1);return;case"selectNextGroupTab":pe(1);return;case"setActiveTabShortcut":Ne();return;case"hideCurrentTab":{const ae=(Z=(V=N.current)==null?void 0:V.activePanel)==null?void 0:Z.id;ae&&!Bt(ae)&&xe(ae);return}default:return}},[pe,Ce,B,fe,be,xe,we,X,ve,z,Se,Ne]);i.useEffect(()=>{if(!I)return;const U=I.sourceDocument,V=U.defaultView??window,Z=ae=>{const K=U.querySelector("[data-dockview-tab-context-menu]");K&&K.contains(ae.target)||y(null)};return V.addEventListener("mousedown",Z,!0),V!==window&&window.addEventListener("mousedown",()=>y(null),!0),()=>{V.removeEventListener("mousedown",Z,!0),V!==window&&window.removeEventListener("mousedown",()=>y(null),!0)}},[I]);const Ie=i.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:G,hasDetachedConversationPanels:J,ides:r,isStandalone:l,hasRegisteredMachines:c,onOpenNewSession:b,liveSessionInboxState:T,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:xe,userName:m,scrollToBottomRequest:C,tabShortcuts:re,openTabContextMenu:({x:U,y:V,tabKey:Z,sourceDocument:ae})=>y({x:U,y:V,tabKey:Z,sourceDocument:ae??document}),popoutTab:Se,moveTabBackToMain:ve,isTabInPopout:X,floatTab:fe,isTabFloating:we}),[n,t,G,J,r,l,c,b,T,a,o,xe,m,C,re,Se,ve,X,fe,we]),Le=I?My({isTabInPopout:X(I.tabKey),isTabFloating:we(I.tabKey),tabShortcut:re[I.tabKey],actionShortcuts:h}):[],He=i.useCallback(U=>{var ae;const V=N.current;if((((ae=V==null?void 0:V.activePanel)==null?void 0:ae.id)??null)===U.id){U.group.model.openPanel(U);return}U.group.model.openPanel(U),U.api.setActive()},[]),ze=i.useCallback((U,V="requested-tab")=>{if(!U)return!1;const Z=N.current;if(!Z)return!1;const ae=Z.getPanel(U);return ae?(He(ae),he(U,V),f==null||f(),!0):!1},[He,f,he]),Xe=i.useCallback(()=>{if(W.current)return!1;const U=ze(H.current,"stored-layout-restore");return U&&(W.current=!0),U},[ze]),Je=i.useCallback(()=>{var V;const U=N.current;U&&og(k,{activeTabId:((V=U.activePanel)==null?void 0:V.id)??null,layout:U.toJSON()})},[k]),rt=i.useCallback(()=>{lg(k,E.current)},[k]),pt=i.useCallback(U=>{var ae,K,Y,se;const V=N.current;if(!V)return{kind:"grid"};const Z=V.toJSON();for(const oe of Z.floatingGroups||[])if((K=(ae=oe.data)==null?void 0:ae.views)!=null&&K.includes(U)&&oe.position)return{kind:"floating",position:oe.position};for(const oe of Z.popoutGroups||[])if((se=(Y=oe.data)==null?void 0:Y.views)!=null&&se.includes(U))return{kind:"popout",position:oe.position,popoutUrl:oe.url};return{kind:"grid"}},[]),xt=i.useCallback(U=>{const V=N.current;if(!V)return;const Z=V.getPanel(U),ae=E.current[U];if(!Z||!ae||ae.kind==="grid")return;if(Z.group.model.location.type===ae.kind){delete E.current[U],rt();return}if(ae.kind==="floating"){V.addFloatingGroup(Z,{x:ae.position.left??24,y:ae.position.top??24,width:ae.position.width,height:ae.position.height}),delete E.current[U],rt();return}delete E.current[U],rt()},[rt]);i.useEffect(()=>(x==null||x({setShortcutForActiveTab:Ne,restoreHiddenTabToSavedLocation:xt,activateConversationTab:ie,resetAllPanelsToMain:ee,activatePreviousTabInGroup:()=>pe(-1),activateNextTabInGroup:()=>pe(1),floatActiveTab:()=>{const U=be();U&&fe(U)},popoutActiveTab:()=>{const U=be();U&&Se(U)},dockActiveTab:()=>{const U=be();U&&(X(U)?ve(U):we(U)&&Ce(U))},splitActiveTabRight:()=>z("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>z("below",{createGroupIfMissing:!0}),focusLeftPane:()=>B("left"),focusRightPane:()=>B("right"),focusUpPane:()=>B("above"),focusDownPane:()=>B("below"),moveActiveTabToLeftPane:()=>z("left"),moveActiveTabToRightPane:()=>z("right"),moveActiveTabToUpPane:()=>z("above"),moveActiveTabToDownPane:()=>z("below")}),()=>x==null?void 0:x(null)),[pe,Ce,fe,B,be,we,X,z,ve,Se,x,ee,xt,ie,Ne]),i.useEffect(()=>()=>{var U;(U=D.current)==null||U.call(D),D.current=null},[]);const vt=i.useCallback(U=>{var Z,ae;N.current=U.api,(Z=D.current)==null||Z.call(D),D.current=null;const V=ag(k);if(H.current=(V==null?void 0:V.activeTabId)??null,V!=null&&V.layout&&U.api.fromJSON(V.layout,{reuseExistingPanels:!1}),j.current=kl({hasStoredLayout:!!(V!=null&&V.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),j.current||(Ml(U.api,e),Al(U.api,e,v)),U.api.totalPanels===0&&e.length>0){const K=$y(U.api,e,g);if(K){const Y=U.api.getPanel(K);Y&&He(Y)}}else!j.current&&!ze(g)&&Xe();if(M.current=!0,U.api.onDidActivePanelChange(K=>{var se;if(H.current=(K==null?void 0:K.id)??null,W.current=!0,me(),K&&Bt(K.id)){const oe=((se=K.params)==null?void 0:se.routeId)||K.id.slice(7),ke=Wt(e,oe);S((ke==null?void 0:ke.tabKey)??null),Je();return}if(S((K==null?void 0:K.id)??null),Je(),!K)return;const Y=G.get(K.id);(Y==null?void 0:Y.streamSource)==="agent-stream"&&Y.agentType&&_(Y.routeId,qc(),{agentType:Y.agentType,...Y.sessionId&&{targetSessionId:Y.sessionId}}).catch(()=>{})}),U.api.onDidLayoutChange(()=>{Je(),me(),P(K=>K+1)}),Ry()){const K=Ae=>({clientX:Ae.clientX,clientY:Ae.clientY}),Y=Ae=>{const $e=Ae==null?void 0:Ae.getBoundingClientRect();return $e?{left:$e.left,right:$e.right,top:$e.top,bottom:$e.bottom}:null},se=Ae=>{var Fe;const $e=(Fe=w.current)==null?void 0:Fe.getBoundingClientRect();return $e?Ae.clientX<$e.left||Ae.clientX>$e.right||Ae.clientY<$e.top||Ae.clientY>$e.bottom:!1},oe=Ly({detachDelayMs:uu,onDetach:({panelId:Ae,clientX:$e,clientY:Fe})=>{var dt,ht;const Me=U.api.getPanel(Ae);if(!Me)return;try{if(Me.group.model.location.type!=="grid")return}catch{return}const Qe=(dt=w.current)==null?void 0:dt.getBoundingClientRect(),et=(ht=Me.group.element)==null?void 0:ht.getBoundingClientRect(),bt=Math.round(Math.min(Math.max((et==null?void 0:et.width)??600,360),720)),gt=Math.round(Math.min(Math.max((et==null?void 0:et.height)??500,260),640));U.api.addFloatingGroup(Me,{x:Qe?Math.max(0,$e-Qe.left-32):void 0,y:Qe?Math.max(0,Fe-Qe.top-18):void 0,width:bt,height:gt}),Me.api.setActive(),Je(),me(),P(Ue=>Ue+1)}}),ke=[U.api.onWillDragPanel(Ae=>{if(!(Ae.nativeEvent.defaultPrevented||Ae.nativeEvent.shiftKey)){try{if(Ae.panel.group.model.location.type!=="grid")return}catch{return}oe.startDrag({panelId:Ae.panel.id,selfPanelBounds:Y(Ae.panel.group.element),...K(Ae.nativeEvent)})}}),U.api.onWillShowOverlay(Ae=>{if(oe.hasDetached()){Ae.preventDefault();return}oe.markDockTarget(K(Ae.nativeEvent))}),U.api.onWillDrop(Ae=>{if(oe.hasDetached()){Ae.preventDefault(),oe.endDrag();return}oe.markDockTarget(K(Ae.nativeEvent))}),U.api.onDidDrop(()=>oe.endDrag()),U.api.onUnhandledDragOverEvent(Ae=>{oe.isDragging()&&oe.markSelfPanel(K(Ae.nativeEvent))})],Pe=Ae=>{if(!oe.isDragging())return;const $e=K(Ae);se($e)&&oe.markNonSelfPanel($e)},Ee=()=>oe.endDrag();window.addEventListener("dragover",Pe,!0),window.addEventListener("drop",Ee,!0),window.addEventListener("dragend",Ee,!0),D.current=()=>{oe.dispose();for(const Ae of ke)Ae.dispose();window.removeEventListener("dragover",Pe,!0),window.removeEventListener("drop",Ee,!0),window.removeEventListener("dragend",Ee,!0)}}U.api.onDidAddGroup(K=>{requestAnimationFrame(()=>{var Y,se;try{const oe=(Y=K.element)==null?void 0:Y.ownerDocument;if(!oe||oe===document)return;(se=oe.getElementById("dv-popout-window"))==null||se.classList.add("adhdev-dockview");const ke=document.documentElement.getAttribute("data-theme");ke&&oe.documentElement.setAttribute("data-theme",ke),oe.body.className=document.body.className;const Pe=document.documentElement.getAttribute("style");Pe&&oe.documentElement.setAttribute("style",Pe)}catch{}me(),P(oe=>oe+1)})}),S(((ae=U.api.activePanel)==null?void 0:ae.id)??null)},[He,ze,G,r,d,k,S,Je,g,v,_,me,e]);i.useLayoutEffect(()=>{const U=N.current;if(!U||!M.current||j.current&&kl({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;j.current&&(j.current=!1);const V=$.current,Z=new Set(V),ae=e.map(Ee=>Ee.tabKey),K=new Set(ae),Y=Ay({previousVisibleConversationCount:V.length,visibleConversationCount:e.length,ides:r});let se=!1;for(const Ee of V)K.has(Ee)||Y||(E.current[Ee]=pt(Ee),se=!0);se&&rt(),Y||(Ml(U,e),Al(U,e,v));const oe=ae.filter(Ee=>!Z.has(Ee));let ke=!1;for(const Ee of oe){const Ae=U.getPanel(Ee),$e=E.current[Ee];if(!Ae||!$e||$e.kind==="grid")continue;if(Ae.group.model.location.type===$e.kind){delete E.current[Ee],ke=!0;continue}if($e.kind==="floating"){U.addFloatingGroup(Ae,{x:$e.position.left??24,y:$e.position.top??24,width:$e.position.width,height:$e.position.height}),delete E.current[Ee],ke=!0;continue}}if(ke&&rt(),$.current=ae,g&&ze(g))return;!U.activePanel&&U.panels[0]&&He(U.panels[0]),!!(U.activePanel&&U.getPanel(U.activePanel.id))||Xe()},[He,ze,Xe,r,d,rt,pt,g,v,e]),i.useEffect(()=>{M.current&&ze(g)},[ze,g]),i.useEffect(()=>{const U=Z=>{const ae=Z.target;if(!ae)return;const K=ae.querySelector("[data-tab-key]")||ae.closest("[data-tab-key]");if(K){const Y=K.getAttribute("data-tab-key");if(Y&&Z.dataTransfer){const se=ae.closest(".dv-tab")||K.closest(".dv-tab")||K;Z.dataTransfer.effectAllowed="move",Z.dataTransfer.setData("text/tab-key",Y),se instanceof HTMLElement&&Z.dataTransfer.setDragImage(se,Math.max(12,Math.round(se.clientWidth/2)),Math.max(10,Math.round(se.clientHeight/2)))}}};window.addEventListener("dragstart",U);const V=Tl(N.current);for(const Z of V)Z.addEventListener("dragstart",U);return()=>{window.removeEventListener("dragstart",U);for(const Z of V)Z.removeEventListener("dragstart",U)}},[F]),i.useEffect(()=>{var V;const U=(V=w.current)==null?void 0:V.querySelector(".adhdev-dockview");U instanceof HTMLElement&&La(U,A),ue(),me()},[me,ue,A]),i.useEffect(()=>{me()},[me]),i.useEffect(()=>{const U=V=>{if(V.defaultPrevented||R)return;const Z=je(V);if(!Z)return;const ae=V.metaKey||V.ctrlKey||V.altKey;wo(V.target)&&!ae||On(de).setActiveTabShortcut!==Z||(V.preventDefault(),V.stopPropagation(),Ne())};return window.addEventListener("keydown",U,!0),()=>window.removeEventListener("keydown",U,!0)},[je,de,R,Ne]),i.useEffect(()=>{const U=w.current;if(!U)return;const V=Z=>{var oe,ke;if(!Z.isTrusted)return;const ae=(ke=(oe=Z.target)==null?void 0:oe.closest)==null?void 0:ke.call(oe,".dv-scrollable");if(!ae)return;Z.preventDefault(),Z.stopPropagation();const K=Math.abs(Z.deltaX),Y=Math.abs(Z.deltaY),se=K>Y?Z.deltaX:Z.deltaY;ae.dispatchEvent(new WheelEvent("wheel",{deltaY:se,deltaMode:Z.deltaMode,bubbles:!1,cancelable:!0}))};return U.addEventListener("wheel",V,{passive:!1,capture:!0}),()=>U.removeEventListener("wheel",V,{capture:!0})},[]),i.useEffect(()=>{const U=Tl(N.current);if(U.length===0)return;const V=U.map(Z=>{let ae=[],K=null;const Y=()=>{K!=null&&Z.clearTimeout(K),K=null,ae=[]},se=()=>{K!=null&&Z.clearTimeout(K),K=Z.setTimeout(()=>{K=null,ae=[]},1200)},oe=Pe=>{if(!Pe.ctrlKey&&!Pe.metaKey&&!Pe.altKey)return;const Ee=je(Pe);if(!Ee)return;const Ae=nu();for(const[$e,Fe]of Object.entries(Ae))if(e.some(Me=>Me.tabKey===$e)&&Fe===Ee){Pe.preventDefault(),ie($e);return}},ke=Pe=>{if(Pe.defaultPrevented||R)return;const Ee=je(Pe);if(!Ee)return;const Ae=Pe.metaKey||Pe.ctrlKey||Pe.altKey;if(wo(Pe.target))return;const $e=On(de),Fe=Object.entries($e).filter(([Ue,Kt])=>!!Kt&&(Ue==="splitActiveTabRight"||Ue==="splitActiveTabDown"||Ue==="floatActiveTab"||Ue==="popoutActiveTab"||Ue==="dockActiveTab"||Ue==="focusLeftPane"||Ue==="focusRightPane"||Ue==="focusUpPane"||Ue==="focusDownPane"||Ue==="moveActiveTabToLeftPane"||Ue==="moveActiveTabToRightPane"||Ue==="moveActiveTabToUpPane"||Ue==="moveActiveTabToDownPane"||Ue==="selectPreviousGroupTab"||Ue==="selectNextGroupTab"||Ue==="setActiveTabShortcut"||Ue==="hideCurrentTab")),Me=Ae?[Ee]:[...ae.slice(-1),Ee].slice(-2),Qe=Me.join(" "),et=Me[Me.length-1],bt=Fe.find(([,Ue])=>Ue===Qe);if(bt){Pe.preventDefault(),Y(),O(bt[0]);return}if(Fe.some(([,Ue])=>Ue.startsWith(`${Qe} `))){Pe.preventDefault(),ae=Me,se();return}const dt=Fe.find(([,Ue])=>Ue===et);if(dt){Pe.preventDefault(),Y(),O(dt[0]);return}if(Fe.some(([,Ue])=>Ue.startsWith(`${et} `))){Pe.preventDefault(),ae=[et],se();return}Y()};return Z.addEventListener("keydown",oe),Z.addEventListener("keydown",ke),()=>{Y(),Z.removeEventListener("keydown",oe),Z.removeEventListener("keydown",ke)}});return()=>{for(const Z of V)Z()}},[je,de,F,ie,R,O,e]);const Te=A==="light"?eo:to,Ve=((ot=(Ge=(tt=N.current)==null?void 0:tt.activePanel)==null?void 0:Ge.group.element)==null?void 0:ot.ownerDocument)??document;return s.jsxs(mu.Provider,{value:Ie,children:[s.jsx("div",{ref:w,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(hm,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:By,remote:Oy},defaultTabComponent:Wy,watermarkComponent:Fy,onReady:vt,singleTabMode:"default",tabAnimation:"smooth",theme:Te,popoutUrl:"/popout.html"})}),I&&Tr.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:I.x,top:I.y},children:Le.map(U=>{if(U.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},U.id);let V=s.jsx(bp,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{};switch(U.id){case"dockInWindow":case"dockBackToGrid":V=s.jsx(yp,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{Ce(I.tabKey),y(null)};break;case"moveBackToMain":V=s.jsx(xp,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{ve(I.tabKey),y(null)};break;case"floatAsPanel":V=s.jsx(gp,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{fe(I.tabKey),y(null)};break;case"openInNewWindow":V=s.jsx(fp,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{Se(I.tabKey),y(null)};break;case"setShortcut":Z=ae=>{ae.stopPropagation(),q(I.tabKey),y(null)};break;case"removeShortcut":V=s.jsx(wt,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{const ae={...re};delete ae[I.tabKey],ce(ae),y(null)};break;case"hideTab":V=s.jsx(Lo,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{xe(I.tabKey),y(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 ${U.tone==="muted"?"text-text-muted":""}`,onMouseDown:Dy,onClick:Z,children:[V,s.jsx("span",{className:"flex-1 min-w-0",children:U.label}),U.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:U.shortcut}):null]},U.id)})}),I.sourceDocument.body),R&&Tr.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:()=>q(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:U=>U.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. ",de?"⌘+1":"Ctrl+1",", ",de?"⌥+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"})]})}),Ve.body)]})}const pu="adhdev-recent-launch-args-v1",Hy=8;function hu(e){return String(e||"").trim().replace(/\s+/g," ")}function di(e,t){return`${e.trim()}::${t.trim()}`}function ui(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(pu)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function fu(e){if(!(typeof window>"u"))try{window.localStorage.setItem(pu,JSON.stringify(e))}catch{}}function jo(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=ui().byKey[di(r,n)])==null?void 0:o.items)||[]}function xu(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=hu(r);if(!n||!a||!o)return;const l=ui(),c=di(n,a),d=((u=l.byKey[c])==null?void 0:u.items)||[],m=[o,...d.filter(h=>h!==o)].slice(0,Hy);l.byKey[c]={items:m},fu(l)}function Uy(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=hu(r);if(!n||!a||!o)return;const l=ui(),c=di(n,a),m=(((u=l.byKey[c])==null?void 0:u.items)||[]).filter(h=>h!==o);m.length>0?l.byKey[c]={items:m}:delete l.byKey[c],fu(l)}function bu(e){return!e.hasLoadedInitialResults&&!e.isLoading}function wn({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 zy({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 gu({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:l,onOpenHistory:c,onClearSelection:d}){const m=o?tu(o):null,u=zy({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(wn,{title:"Saved history",description:Jo(),action:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:l,children:t?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:c,children:Lx()})]}),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:d,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:u}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function yu({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 Vy({workspaceMode:e,activeKind:t,cliEnabled:r,ideEnabled:n,acpEnabled:a,busy:o,onSelect:l}){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:"IDE",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:()=>l(c.id),disabled:!c.enabled||o,children:c.label},c.id))})]})}function Ra(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>Ts(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>Ts(a,"acp"))?"acp":null}function on(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Gy({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:l,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var Ue,Kt;const u=Er(),h=i.useMemo(()=>[...e].sort(Fo),[e]),[x,S]=i.useState(((Ue=h[0])==null?void 0:Ue.id)||""),b=i.useMemo(()=>h.find(te=>te.id===x)||h[0],[x,h]),p=i.useMemo(()=>((b==null?void 0:b.workspaces)||[]).map(te=>({id:te.id,path:te.path,label:te.label})),[b]),g=(b==null?void 0:b.defaultWorkspaceId)||null,[v,f]=i.useState("workspace"),[C,T]=i.useState(""),[k,A]=i.useState(""),[_,N]=i.useState([]),[w,D]=i.useState(""),[M,j]=i.useState(!1),[W,H]=i.useState(null),[$,I]=i.useState(""),[y,F]=i.useState(Ra(h[0])),[P,E]=i.useState(""),[G,J]=i.useState(""),[ye,he]=i.useState([]),[ne,ue]=i.useState(""),[Se,ve]=i.useState([]),[X,xe]=i.useState(!1),[fe,we]=i.useState(!1),[be,Ce]=i.useState(""),[ee,me]=i.useState(!1),[ie,pe]=i.useState(()=>Ct()),[le,B]=i.useState(null),[z,de]=i.useState(!1),[re,R]=i.useState(""),[q,ce]=i.useState(null),[Ne,je]=i.useState(!1),[O,Ie]=i.useState(""),[Le,He]=i.useState([]),[ze,Xe]=i.useState(!1),[Je,rt]=i.useState(""),[pt,xt]=i.useState(!1),vt=i.useRef(null),Te=i.useRef(0);i.useEffect(()=>{var te;!x&&((te=h[0])!=null&&te.id)&&S(h[0].id)},[x,h]),i.useEffect(()=>{!b||!(!b.workspaces||!b.availableProviders||!b.detectedIdes||!b.recentLaunches)||u(b.id,{minFreshMs:3e4}).catch(()=>{})},[u,b]);const Ve=i.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(te=>Ts(te,"cli")),[b]),tt=i.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(te=>Ts(te,"acp")),[b]),Ge=i.useMemo(()=>((b==null?void 0:b.detectedIdes)||[]).map(te=>({id:te.type,label:te.name||te.type,meta:te.running?"Detected locally":"Available to open"})),[b]),ot=i.useMemo(()=>y==="cli"?Ve.map(te=>({id:te.type,label:te.displayName||te.type,meta:"CLI provider"})):y==="acp"?tt.map(te=>({id:te.type,label:te.displayName||te.type,meta:"ACP provider"})):Ge,[tt,y,Ve,Ge]),U=i.useMemo(()=>_.find(te=>te.id===w)||null,[_,w]),V=i.useMemo(()=>Ve.find(te=>te.type===P)||null,[Ve,P]),Z=i.useMemo(()=>qd(V==null?void 0:V.meshCoordinator,{meshId:(U==null?void 0:U.id)||"",workspace:(U==null?void 0:U.workspace)||""}),[V,U]),ae=q||Z,K=i.useCallback(async te=>{j(!0),I("");try{const De=await c(te);N(De),D(L=>{var Q;return De.some(ge=>ge.id===L)?L:((Q=De[0])==null?void 0:Q.id)||""}),H(te)}catch(De){N([]),D(""),H(te),I(De instanceof Error?De.message:"Could not load meshes")}finally{j(!1)}},[c]);i.useEffect(()=>{var De;if(!b)return;if(vt.current!==b.id){vt.current=b.id,f("workspace"),T(g||((De=p[0])==null?void 0:De.id)||"__home__"),A(""),N([]),D(""),H(null),I(""),F(Ra(b)),E(""),J(""),ue(""),ve([]),we(!1),Ce(""),pe(Ct()),R(""),ce(null);return}T(L=>{var Q;return L==="__custom__"||L==="__home__"||p.some(ge=>ge.id===L)?L:g||((Q=p[0])==null?void 0:Q.id)||"__home__"}),F(L=>L==="ide"&&Ge.length>0||L==="cli"&&Ve.length>0||L==="acp"&&tt.length>0?L:Ra(b))},[tt.length,Ve.length,g,Ge.length,b,p]),i.useEffect(()=>{!b||v!=="mesh"||W===b.id||M||K(b.id)},[K,W,M,b,v]),i.useEffect(()=>{v==="mesh"&&y!=="cli"&&Ve.length>0&&F("cli")},[y,Ve.length,v]),i.useEffect(()=>{var te;y&&(ot.some(De=>De.id===P)||E(((te=ot[0])==null?void 0:te.id)||""))},[y,ot,P]),i.useEffect(()=>{ce(null)},[b==null?void 0:b.id,w,P,v]);const Y=i.useCallback(async(te,De)=>{const L=Te.current+1;return Te.current=L,xe(!0),Ce(""),m(te,De).then(Q=>{Te.current===L&&ve(Q)}).catch(Q=>{Te.current===L&&(ve([]),Ce(Q instanceof Error?Q.message:"Could not load saved sessions"))}).finally(()=>{Te.current===L&&(xe(!1),we(!0))})},[m]),se=i.useCallback((te,De)=>{he(jo(te,De))},[]);i.useEffect(()=>{Te.current+=1,ue(""),pe(Ct()),!b||!P||y==="ide"?he([]):se(b.id,P),we(!1),ve([]),Ce(""),xe(!1)},[y,se,Y,b,P]),i.useEffect(()=>{if(!ne)return;const te=Se.find(De=>De.providerSessionId===ne);te!=null&&te.canResume||ue("")},[Se,ne]);const oe=C==="__custom__"?k.trim():C==="__home__"?"":((Kt=p.find(te=>te.id===C))==null?void 0:Kt.path)||"",ke=i.useMemo(()=>b?t.filter(te=>te.id!==b.id&&te.daemonId===b.id).map(te=>te.workspace):[],[t,b]),Pe=i.useMemo(()=>((b==null?void 0:b.recentLaunches)||[]).map(te=>te.workspace),[b]),Ee=i.useCallback(te=>{const De=String(te.workspace||"").trim();if(!De)return;const L=p.find(Q=>on(Q.path)===on(De));if(L){T(L.id),A("");return}T("__custom__"),A(De)},[p]),Ae=i.useCallback(te=>{const De=String(te.workspace||"").trim();if(!De)return{workspaceId:null,workspacePath:null};const L=p.find(Q=>on(Q.path)===on(De));return L?{workspaceId:L.id,workspacePath:null}:{workspaceId:null,workspacePath:De}},[p]),$e=i.useMemo(()=>Se.find(te=>te.providerSessionId===ne)||null,[Se,ne]),Fe=i.useMemo(()=>{var De;if(y!=="cli"||!b||!P)return null;const te=((De=Ve.find(L=>L.type===P))==null?void 0:De.displayName)||P;return{routeId:b.id,daemonId:b.id,providerSessionId:ne||void 0,transport:"pty",mode:"chat",agentName:te,agentType:P,status:"idle",title:te,messages:[],ideType:P,workspaceName:oe,workspacePath:oe,displayPrimary:te,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${b.id}:${P}`,machineName:At(b,{fallbackId:b.id})}},[y,Ve,oe,b,ne,P]),Me=i.useCallback(()=>{var De;if(!b)return;T("__custom__"),je(!0),rt("");const te=Qn(b.platform,Jn(k.trim(),oe,ke,Pe,b.defaultWorkspacePath,(De=p.find(L=>L.id===g))==null?void 0:De.path,p.map(L=>L.path)));Xe(!0),n(b.id,te).then(L=>{Ie(L.path),A(L.path),He(L.directories)}).catch(L=>{rt(L instanceof Error?L.message:"Could not load folder")}).finally(()=>Xe(!1))},[k,g,Pe,ke,n,oe,b,p]),Qe=i.useCallback(te=>{b&&(Xe(!0),rt(""),n(b.id,te).then(De=>{Ie(De.path),A(De.path),He(De.directories)}).catch(De=>{rt(De instanceof Error?De.message:"Could not load folder")}).finally(()=>Xe(!1)))},[n,b]),et=i.useCallback(async()=>{if(!b||!oe)return;xt(!0),R("");const te=await a(b.id,oe);if(xt(!1),!te.ok){R(te.error||"Could not save workspace");return}R("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,oe,b]),bt=i.useCallback(async()=>{if(!b)return;if(v==="mesh"){if(!w||!P)return;de(!0),R(""),ce(null);const L=await d(b.id,w,P);if(de(!1),!L.ok){if(L.code==="mesh_coordinator_manual_mcp_setup_required"&&L.manualSetup){ce(L.manualSetup),R("Manual MCP setup required before this provider can act as mesh coordinator.");return}R(L.error||"Could not start mesh coordinator");return}r();return}if(!y||!P)return;de(!0),R("");const te=G.trim()?G.trim().split(/\s+/).filter(Boolean):[],De=y==="ide"?await o(b.id,P,{workspacePath:oe||null}):await l(b.id,y,P,{workspaceId:C!=="__home__"&&C!=="__custom__"?C:null,workspacePath:C==="__custom__"&&oe||null,resumeSessionId:y==="cli"&&ne?ne:null,cliArgs:te});if(de(!1),!De.ok){R(De.error||"Could not start session");return}y!=="ide"&&G.trim()&&(xu(b.id,P,G),se(b.id,P)),r()},[y,G,se,r,o,d,l,oe,b,w,ne,P,C,v]),gt=v==="mesh"?"Start mesh coordinator":y?hd(y,y==="cli"&&!!ne):"Start",dt=v==="mesh"?"Starting coordinator…":y?fd(y,y==="cli"&&!!ne):"Starting…",ht=h.length>5;return b?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(wt,{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:[s.jsx(wn,{title:"Machine",children:ht?s.jsx("select",{"aria-label":"Machine",value:b.id,onChange:te=>S(te.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:z,children:h.map(te=>s.jsx("option",{value:te.id,children:At(te,{fallbackId:te.id})},te.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:h.map(te=>{const De=At(te,{fallbackId:te.id}),L=b.id===te.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${De}`,"aria-pressed":L,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${L?"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:()=>S(te.id),disabled:z,title:De,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${te.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:De})]},te.id)})})}),s.jsxs(wn,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:v==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Me,disabled:z,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(te=>s.jsxs("button",{type:"button",role:"radio","aria-checked":v===te.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${v===te.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:()=>{f(te.id),R(""),te.id==="mesh"&&b&&W!==b.id&&!M&&K(b.id)},disabled:z,children:[s.jsx("div",{className:"text-sm font-semibold",children:te.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:te.desc})]},te.id))}),v==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:C,onChange:te=>{const De=te.target.value;T(De),De==="__custom__"?Me():R("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:z,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),p.map(te=>s.jsxs("option",{value:te.id,children:[te.id===g?"⭐ ":"",Vn(te.path,te.label)||te.path]},te.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:C==="__home__"?"Launch without a workspace.":oe||"Select a workspace folder."}),C==="__custom__"&&oe&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Me,disabled:z,children:[s.jsx(Ns,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:et,disabled:z||pt,children:pt?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[M&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!M&&$&&s.jsx("div",{className:"rounded-lg border border-status-error/25 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:$}),!M&&!$&&_.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."}),_.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:_.map(te=>s.jsxs("button",{type:"button",role:"radio","aria-checked":w===te.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${w===te.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>D(te.id),disabled:z,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:te.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[te.repoIdentity||"Repo mesh",typeof te.nodesCount=="number"?` · ${te.nodesCount} node${te.nodesCount===1?"":"s"}`:""]}),te.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",te.workspace]})]},te.id))}),U&&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(Vy,{workspaceMode:v,activeKind:y,cliEnabled:Ve.length>0,ideEnabled:Ge.length>0,acpEnabled:tt.length>0,busy:z,onSelect:F}),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:y==="ide"?"Choose IDE":y==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[ot.map(te=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${P===te.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>E(te.id),disabled:z,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:te.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:te.meta})]},te.id)),ot.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."})]})]}),v==="mesh"&&ae&&s.jsx(yu,{setup:ae,providerName:(V==null?void 0:V.displayName)||(V==null?void 0:V.name)||P}),v!=="mesh"&&y!=="ide"&&s.jsxs(wn,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:G,onChange:te=>J(te.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:z}),ye.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:ye.map(te=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>J(te),disabled:z,title:te,children:te},te))})]}),v!=="mesh"&&y==="cli"&&s.jsx(gu,{busy:z,savedSessionsLoading:X,savedSessionsError:be,selectedSession:$e,onRefresh:()=>{!b||!P||Y(b.id,P)},onOpenHistory:()=>{!b||!P||(me(!0),bu({hasLoadedInitialResults:fe,isLoading:X})&&Y(b.id,P))},onClearSelection:()=>ue("")}),re&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${re.includes("saved")||re.includes("requested")||re.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:re})]}),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:z,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:bt,disabled:z||(v==="mesh"?!w||!P||y!=="cli"||M:!y||!P||C==="__custom__"&&!oe),children:[s.jsx(Po,{size:14}),z?dt:gt]})]})]})}),Ne&&s.jsx(ea,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:O,directories:Le,busy:ze,error:Je,onClose:()=>je(!1),onNavigate:Qe,onConfirm:te=>{A(te),Ie(te),T("__custom__"),je(!1)}}),ee&&Fe&&s.jsx(ei,{activeConv:Fe,ides:[],isCreatingChat:!1,isRefreshingHistory:X,savedSessions:Se,isSavedSessionsLoading:X,isResumingSavedSessionId:le,savedHistoryFilters:ie,missingWorkspaceResumePath:oe||null,onSavedHistoryFiltersChange:pe,onClose:()=>me(!1),onNewChat:()=>{ue(""),me(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!b||!P||Y(b.id,P)},onResumeSavedSession:te=>{if(!b||!P||le||!te.canResume)return;const De=Ae(te);ue(te.providerSessionId),Ee(te),B(te.providerSessionId),me(!1),de(!0),R(""),l(b.id,"cli",P,{workspaceId:De.workspaceId,workspacePath:De.workspacePath,resumeSessionId:te.providerSessionId}).then(L=>{if(!L.ok){R(L.error||"Could not resume session");return}r()}).finally(()=>{de(!1),B(L=>L===te.providerSessionId?null:L)})}})]}):null}const qy=5*60*1e3;function vu(e){var t,r;return((t=e.git)==null?void 0:t.isGitRepo)===!0?!1:!!(e.gitProbePending||((r=e.connection)==null?void 0:r.state)==="connecting")}function Yy(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function wu(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function ju(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function Fn(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function Xy(e){return Fn(e)?"degraded":ju(e)?"dirty":"online"}function Jy(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function _l(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 Pa(e){return e.length===0?"unknown":e.reduce((t,r)=>_l(r)>_l(t)?r:t)}function Qy(e){var o,l,c,d,m;const t=new Map,r=new Map;for(const u of e){const h=(l=(o=u.git)==null?void 0:o.branch)==null?void 0:l.trim();h&&(r.set(h,(r.get(h)??0)+1),(c=u.git)!=null&&c.upstream&&t.set(h,(t.get(h)??0)+1))}const n=[...t.entries()].sort((u,h)=>{if(h[1]!==u[1])return h[1]-u[1];const x=["main","master","develop","dev"],S=x.indexOf(u[0]),b=x.indexOf(h[0]);return S!==-1||b!==-1?S===-1?1:b===-1?-1:S-b:u[0].localeCompare(h[0])});return(d=n[0])!=null&&d[0]?n[0][0]:((m=[...r.entries()].sort((u,h)=>h[1]-u[1])[0])==null?void 0:m[0])??null}function Zy(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 Ll(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 e0(e){return e.reduce((t,r)=>Ll(r.status)>Ll(t.status)?r:t)}function t0(e,t){if(!t||vu(e))return null;const r=e.git,n=(r==null?void 0:r.branch)??null,a=(r==null?void 0:r.upstream)??null,o=(r==null?void 0:r.upstreamStatus)??null,l=(r==null?void 0:r.ahead)??0,c=(r==null?void 0:r.behind)??0,d=wu(r)||ju(r),m=!!(r!=null&&r.hasConflicts)||Fn(r),u={branch:n,defaultBranch:t,upstream:a,upstreamStatus:o,ahead:l,behind:c,dirty:d,hasConflicts:m};return(r==null?void 0:r.isGitRepo)!==!0?{...u,status:"blocked_review",needsConvergence:!0,reason:"git_status_unavailable",nextStep:`Resolve git status for '${e.machineLabel||e.nodeId}' before declaring the mesh converged.`}:n?m||d?{...u,status:"not_mergeable",needsConvergence:!0,reason:r!=null&&r.hasConflicts?"conflicts_present":Fn(r)?"submodule_out_of_sync":"dirty_workspace",nextStep:`Commit, checkpoint, or resolve '${n}' before any convergence step into ${t}.`}:a&&o&&o!=="fresh"?{...u,status:"blocked_review",needsConvergence:!0,reason:"upstream_unverified",nextStep:`Refresh '${n}' against ${a} before claiming the mesh is converged.`}:n===t?l>0||c>0?{...u,status:"blocked_review",needsConvergence:!0,reason:"default_branch_not_even_with_upstream",nextStep:`Bring ${t} even with ${a??"its upstream"} before declaring convergence complete.`}:{...u,status:"merged_to_main",needsConvergence:!1,reason:"clean_default_branch",nextStep:null}:e.isLocalWorktree?{...u,status:"cleanup_candidate",needsConvergence:!0,reason:"clean_non_default_worktree_branch",nextStep:`Run refine / cleanup for '${n}' or explicitly classify the worktree before ending the task.`}:!a||l>0||c>0?{...u,status:"blocked_review",needsConvergence:!0,reason:a?"feature_branch_not_even_with_upstream":"feature_branch_missing_upstream",nextStep:`Push or reconcile '${n}', then merge it into ${t} or mark it blocked with a reason.`}:{...u,status:"pushed_feature_branch_needs_merge",needsConvergence:!0,reason:"clean_non_default_branch",nextStep:`Review and merge '${n}' into ${t}; do not treat it as fully complete while it remains off ${t}.`}:{...u,status:"blocked_review",needsConvergence:!0,reason:"branch_unknown",nextStep:`Inspect '${e.machineLabel||e.nodeId}' and confirm which branch should converge into ${t}.`}}function s0(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function r0(e){var d,m,u;const{nodeStatus:t,expectedSubmodulePaths:r,refreshedAtMs:n}=e,a=[],o=t.machineLabel||t.nodeId,l=t.git;if(!l){if(vu(t))return a.push(`${o} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:a};const h=t.health==="online"||t.machineStatus==="online"||((d=t.connection)==null?void 0:d.state)==="connected"||((m=t.connection)==null?void 0:m.state)==="self";return a.push(h?`${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((l.submodules??[]).map(h=>h.path));if(r.size>0){const h=[...r].filter(x=>!c.has(x));h.length>0&&a.push(`${o} is missing submodule visibility for ${h.join(", ")} even though another peer reported it.`)}return((u=t.connection)==null?void 0:u.state)!=="self"&&n!==null&&typeof l.lastCheckedAt=="number"&&n-l.lastCheckedAt>qy&&a.push(`${o} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),a.some(h=>h.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:a}:a.some(h=>h.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:a}:{snapshotCompleteness:"complete",snapshotWarnings:a}}function ku(e){var D;const r=(typeof e.defaultBranch=="string"&&e.defaultBranch.trim().length>0?e.defaultBranch.trim():null)??Qy(e.nodes),n=Yy(e.refreshedAt),a=new Set(e.nodes.flatMap(M=>{var j;return(((j=M.git)==null?void 0:j.submodules)??[]).map(W=>W.path)})),o=[],l=[],c=[],d=new Map;for(const M of e.nodes){const j=M.git,W=(j==null?void 0:j.branch)??null,H=Xy(j),$=wu(j)||H==="dirty",I=Zy(M,r),y=t0(M,r),F=r0({nodeStatus:M,expectedSubmodulePaths:a,refreshedAtMs:n}),P={id:M.nodeId,type:I.length>0?"orphanNode":"worktreeNode",label:M.machineLabel||M.nodeId.slice(0,8),workspace:M.workspace,branch:W,upstream:(j==null?void 0:j.upstream)??null,upstreamStatus:(j==null?void 0:j.upstreamStatus)??null,machineLabel:M.machineLabel||null,health:Pa([M.health,H]),ahead:(j==null?void 0:j.ahead)??0,behind:(j==null?void 0:j.behind)??0,dirty:$,dirtyFiles:Jy(j),hasConflicts:(j==null?void 0:j.hasConflicts)??!1,activeSessionCount:((D=M.activeSessions)==null?void 0:D.length)??0,activeSessions:M.activeSessions??[],providers:M.providers??[],isOrphan:I.length>0,orphanReasons:I,error:M.error,nextStepHint:F.snapshotWarnings[0]??I[0]??(y==null?void 0:y.nextStep)??void 0,parentNodeId:null,submodulePath:null,submoduleCommit:(j==null?void 0:j.headCommit)??null,outOfSync:Fn(j),snapshotCompleteness:F.snapshotCompleteness,snapshotWarnings:F.snapshotWarnings,branchConvergence:y,source:M};if(o.push(P),W){const E=d.get(W)??[];E.push(P.id),d.set(W,E)}for(const E of(j==null?void 0:j.submodules)??[]){const G=`${P.id}::submodule::${E.path}`,J=E.path.split("/").filter(Boolean).pop()||E.path;o.push({id:G,type:"submoduleNode",label:J,workspace:E.repoPath,branch:null,upstream:null,upstreamStatus:null,machineLabel:P.machineLabel,health:s0(E),ahead:0,behind:0,dirty:E.dirty,dirtyFiles:E.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],error:E.error,nextStepHint:E.error||(E.outOfSync?`${E.path} is out of sync with the parent checkout`:E.dirty?`${E.path} has local changes`:`${E.path} is in sync with the parent checkout`),parentNodeId:P.id,submodulePath:E.path,submoduleCommit:E.commit,outOfSync:E.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:P.id,parentWorkspace:M.workspace,submodule:E}}),l.push({id:`${P.id}--${G}`,source:P.id,target:G,type:"submoduleLink",label:E.outOfSync?"submodule out of sync":"submodule"})}}const m=r?`__branch_${r}`:null;if(m&&r){const j=(d.get(r)??[]).map(y=>o.find(F=>F.id===y)).filter(Boolean),W=j.map(y=>y.branchConvergence).filter(Boolean),H=W.length>0?e0(W):null,$=W.filter(y=>y.needsConvergence).length,I={id:m,type:"defaultBranchNode",label:r,workspace:e.repoIdentity,branch:r,upstream:null,upstreamStatus:null,machineLabel:"default branch",health:Pa(j.map(y=>y.health)),ahead:0,behind:0,dirty:j.some(y=>y.dirty),dirtyFiles:j.reduce((y,F)=>y+F.dirtyFiles,0),hasConflicts:j.some(y=>y.hasConflicts),activeSessionCount:j.reduce((y,F)=>y+F.activeSessionCount,0),activeSessions:j.flatMap(y=>y.activeSessions),providers:[...new Set(j.flatMap(y=>y.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:$>0?`${$} workspace(s) on ${r} still need follow-up`:j.length>0?`${j.length} workspace(s) currently on ${r}`:"No workspaces currently checked out to the default branch",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:H,source:{nodeId:m,machineLabel:r,workspace:e.repoIdentity,health:Pa(j.map(y=>y.health)),providers:[],activeSessions:[]}};o.push(I);for(const y of o)if(!(y.id===m||y.type==="submoduleNode")){if(y.branch===r){l.push({id:`${m}--${y.id}`,source:m,target:y.id,type:"parentBranch",label:"checked out"});continue}if(y.branch){l.push({id:`${m}--${y.id}`,source:m,target:y.id,type:y.isOrphan?"orphanLink":"parentBranch",label:y.branch});continue}y.isOrphan&&l.push({id:`${m}--${y.id}`,source:m,target:y.id,type:"orphanLink",label:"detached"})}}for(const[M,j]of d){if(j.length<2)continue;const W=j.map(H=>o.find($=>$.id===H)).filter(Boolean);W.sort((H,$)=>H.label.localeCompare($.label));for(let H=1;H<W.length;H+=1)l.push({id:`wt_${W[H-1].id}--${W[H].id}`,source:W[H-1].id,target:W[H].id,type:"worktreeLink",label:H===1?`${M} peers`:void 0})}const u=o.filter(M=>M.type!=="defaultBranchNode"),h=u.filter(M=>M.isOrphan).length,x=u.filter(M=>M.hasConflicts).length,S=u.filter(M=>M.health==="offline").length,b=u.filter(M=>M.type==="submoduleNode"&&M.outOfSync).length,p=u.filter(M=>{var j;return M.type!=="submoduleNode"&&((j=M.branchConvergence)==null?void 0:j.needsConvergence)}).length,g=u.filter(M=>{var j;return((j=M.branchConvergence)==null?void 0:j.status)==="blocked_review"}).length,v=u.filter(M=>{var j;return((j=M.branchConvergence)==null?void 0:j.status)==="pushed_feature_branch_needs_merge"}).length,f=u.filter(M=>{var j;return((j=M.branchConvergence)==null?void 0:j.status)==="cleanup_candidate"}).length,C=u.filter(M=>{var j;return((j=M.branchConvergence)==null?void 0:j.status)==="not_mergeable"}).length,T=u.filter(M=>M.snapshotWarnings.length>0).length,k=u.filter(M=>M.snapshotCompleteness==="pending_git").length,A=u.filter(M=>M.snapshotCompleteness==="missing_git").length,_=u.filter(M=>M.snapshotCompleteness==="missing_submodule_report").length,N=u.filter(M=>M.snapshotCompleteness==="stale").length,w=[k>0?`${k} node(s) are still waiting for a live peer git snapshot`:null,A>0?`${A} node(s) have no visible peer git snapshot`:null,_>0?`${_} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,N>0?`${N} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return p>0&&c.push(`${p} workspace(s) still need follow-up before the mesh is converged`),h>0&&c.push(`${h} workspace(s) need attention before safe coordination`),g>0&&c.push(`${g} workspace(s) are blocked on branch convergence or upstream sync`),v>0&&c.push(`${v} clean feature branch workspace(s) still need merge follow-up`),f>0&&c.push(`${f} worktree workspace(s) are ready for refine / cleanup`),C>0&&c.push(`${C} workspace(s) have local changes or conflicts blocking convergence`),x>0&&c.push(`${x} workspace(s) report merge conflicts`),S>0&&c.push(`${S} node(s) are currently offline`),b>0&&c.push(`${b} submodule(s) are out of sync with their parent checkout`),c.push(...w),r||c.push("Could not infer a default branch from live mesh status"),{meshId:e.meshId,meshName:e.meshName,repoIdentity:e.repoIdentity,refreshedAt:e.refreshedAt,nodes:o,edges:l,stats:{totalNodes:u.length,onlineNodes:u.filter(M=>M.health==="online").length,dirtyNodes:u.filter(M=>M.dirty).length,orphanNodes:h,errorNodes:u.filter(M=>!!M.error||M.outOfSync).length,offlineNodes:S,followUpNodes:p,blockedReviewNodes:g,mergeReadyNodes:v,cleanupCandidateNodes:f,notMergeableNodes:C,incompleteSnapshotNodes:T,missingGitSnapshotNodes:A,missingSubmoduleSnapshotNodes:_,staleGitSnapshotNodes:N,totalActiveSessions:u.reduce((M,j)=>M+j.activeSessionCount,0)},warnings:c,snapshotWarnings:w}}function Su(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 Nu(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=Su(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(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 Cu(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function n0(e){var t;return!Cu(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 ln(e){return[...new Set(e.filter(t=>!!t))]}function Iu(e){return e.nodes.filter(t=>t.type!=="submoduleNode")}function a0(e){const t=e.nodes.find(l=>l.type==="defaultBranchNode")??null,r=(t==null?void 0:t.branch)??null,n=e.nodes.filter(l=>l.type!=="defaultBranchNode"&&l.type!=="submoduleNode"&&!l.isOrphan&&!!r&&l.branch===r),a=e.nodes.filter(l=>l.type!=="submoduleNode"&&!l.isOrphan),o=Iu(e);return t||n.length>0?ln([t==null?void 0:t.id,...n.map(l=>l.id)]):a.length>0?ln(a.map(l=>l.id)):o.length>0?ln(o.map(l=>l.id)):ln(e.nodes.map(l=>l.id))}function o0(e){const t=Iu(e),r=new Set(t.map(o=>o.branch).filter(o=>!!o)).size,n=e.nodes.filter(o=>o.type==="submoduleNode").length,a=t.filter(o=>o.isOrphan).length;return t.length>=6||r>=3||n>=3||a>0}function Tu(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 i0(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${Tu(e)}::${n}x${a}`}const l0={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"},c0={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"},d0={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"},u0={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 tr(e){return e==="light"?{theme:e,isDark:!1,flowColorMode:"light",textPrimary:"text-slate-900",textSecondary:"text-slate-700",textMuted:"text-slate-500",graphShellClass:"relative 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",graphMiniMapClass:"!bottom-4 !right-4 !bg-white/95 !border !border-slate-200 !rounded-xl !shadow-md",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 overflow-y-auto 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=>c0[t],actionButton:t=>u0[t]}:{theme:e,isDark:!0,flowColorMode:"dark",textPrimary:"text-slate-100",textSecondary:"text-slate-300",textMuted:"text-slate-400",graphShellClass:"relative 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",graphMiniMapClass:"!bottom-4 !right-4 !bg-slate-950/85 !border !border-white/10 !rounded-xl",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 overflow-y-auto 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=>l0[t],actionButton:t=>d0[t]}}const Rl=390,Pl=192,Dl=120,m0=36,El=148,p0=24,Mu=i.createContext(tr("dark"));function h0(e,t,r){const n=t?"border-cyan-400/70 shadow-[0_0_0_1px_rgba(34,211,238,0.35),0_24px_60px_rgba(8,145,178,0.18)]":r?"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)]",a=Nu(e);if((a==null?void 0:a.tone)==="danger")return`${n} ${r?"bg-rose-500/12":"bg-rose-50/95"}`;if((a==null?void 0:a.tone)==="warn")return`${n} ${r?"bg-amber-500/10":"bg-amber-50/95"}`;if((a==null?void 0:a.tone)==="info")return`${n} ${r?"bg-violet-500/10":"bg-violet-50/95"}`;switch(e.health){case"online":return`${n} ${r?"bg-emerald-500/8":"bg-emerald-50/95"}`;case"dirty":return`${n} ${r?"bg-amber-500/8":"bg-amber-50/95"}`;case"degraded":return`${n} ${r?"bg-rose-500/10":"bg-rose-50/95"}`;case"wrong_branch":return`${n} ${r?"bg-violet-500/10":"bg-violet-50/95"}`;case"offline":return`${n} ${r?"bg-slate-500/12":"bg-slate-100/95"}`;default:return`${n} ${r?"bg-slate-950/78":"bg-white/96"}`}}function qt(e,t){switch(e){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 f0(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 Au(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 x0(e){return e.replace(/_/g," ")}function b0(e){return!e.upstream||e.upstreamStatus==="fresh"}function g0(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),!b0(e))t.push("upstream unverified");else{const n=Su(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 y0({data:e,selected:t}){const r=i.useContext(Mu),n=e.graphNode,a=n.type==="defaultBranchNode",o=n.type==="submoduleNode",l=n0(n),c=a?"default branch anchor":o?n.submodulePath||"submodule checkout":n.machineLabel||n.workspace,d=n.submoduleCommit?n.submoduleCommit.slice(0,7):null,m=Nu(n),u=g0(n),h=Cu(n);return s.jsxs("div",{className:`${o?"w-[204px]":"w-[220px]"} rounded-2xl border px-3.5 py-3 backdrop-blur-sm transition-all ${h0(n,t,r.isDark)}`,children:[s.jsx(ki,{type:"target",position:Si.Top,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:n.label}),s.jsx("div",{className:`truncate text-[11px] ${r.textMuted}`,children:c})]}),s.jsx("span",{className:"mt-0.5 h-2.5 w-2.5 shrink-0 rounded-full",style:{backgroundColor:Au(n.health)},"aria-hidden":!0})]}),m&&s.jsx("div",{className:`mt-3 inline-flex max-w-full items-center rounded-full border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] ${f0(m.tone,r.isDark)}`,children:s.jsx("span",{className:"truncate",children:m.label})}),s.jsxs("div",{className:"mt-3 flex flex-wrap gap-1.5 text-[10px]",children:[s.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${qt("health",r.isDark)}`,children:x0(n.health)}),o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("submodule",r.isDark)}`,children:"submodule"}),n.branch&&!o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("meta",r.isDark)}`,children:n.branch}),d&&o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("meta",r.isDark)}`,children:d}),n.dirty&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("dirty",r.isDark)}`,children:o?"local changes":`${n.dirtyFiles} dirty`}),n.outOfSync&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("conflict",r.isDark)}`,children:"out of sync"}),n.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("conflict",r.isDark)}`,children:"conflicts"}),!o&&n.upstream&&n.upstreamStatus!=="fresh"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("orphan",r.isDark)}`,children:"upstream unverified"}),n.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("orphan",r.isDark)}`,children:"needs follow-up"})]}),s.jsx("div",{className:`mt-3 text-[11px] leading-5 ${r.textSecondary}`,children:u}),l&&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"}`,children:h}),s.jsx(ki,{type:"source",position:Si.Bottom,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const v0={meshNode:y0};function Da(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)}function w0(e,t=tr("dark")){const r=[...e.nodes].sort(Da),n=r.find(p=>p.type==="defaultBranchNode")??null,a=new Map;for(const p of r){if(p.type!=="submoduleNode"||!p.parentNodeId)continue;const g=a.get(p.parentNodeId)??[];g.push(p),a.set(p.parentNodeId,g)}const o=r.filter(p=>p.id!==(n==null?void 0:n.id)&&p.type!=="submoduleNode"),l=new Map,c=[];for(const p of o){if(p.isOrphan||!p.branch){c.push(p);continue}const g=p.branch,v=l.get(g)??[];v.push(p),l.set(g,v)}const d=[...l.entries()].sort(([p],[g])=>n!=null&&n.branch&&p===n.branch&&g!==n.branch?-1:n!=null&&n.branch&&g===n.branch&&p!==n.branch?1:p.localeCompare(g));c.length>0&&d.push(["__orphans__",[...c].sort(Da)]),d.length===0&&d.push(["__nodes__",[]]);const m=[],u=d.length,h=Math.max(1,u-1)*Rl,x=n?0:80,S=n?Pl:0;n&&m.push({id:n.id,type:"meshNode",position:{x:h/2,y:x},data:{graphNode:n},selected:!1,draggable:!1,selectable:!0}),d.forEach(([p,g],v)=>{const f=v*Rl,C=g.length>0?g:o.length>0?o:[];let T=S;C.forEach(k=>{m.push({id:k.id,type:"meshNode",position:{x:f,y:T},data:{graphNode:k},selected:!1,draggable:!1,selectable:!0});const A=[...a.get(k.id)??[]].sort(Da);if(A.length>0){A.forEach((_,N)=>{m.push({id:_.id,type:"meshNode",position:{x:f+m0,y:T+El+N*Dl},data:{graphNode:_},selected:!1,draggable:!1,selectable:!0})}),T+=El+A.length*Dl+p0;return}T+=Pl}),p==="__nodes__"&&o.length===0&&n&&m.push({id:`${n.id}__placeholder`,type:"meshNode",position:{x:f,y:S},data:{graphNode:{id:`${n.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:e.repoIdentity,branch:n.branch,upstream:null,upstreamStatus:null,machineLabel:null,health:"unknown",ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],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:`${n.id}__placeholder`,machineLabel:"",workspace:e.repoIdentity,health:"unknown",providers:[],activeSessions:[]}}},selected:!1,draggable:!1,selectable:!1})});const b=e.edges.map(p=>({id:p.id,source:p.source,target:p.target,label:p.label,type:p.type==="worktreeLink"||p.type==="submoduleLink"?"smoothstep":"bezier",animated:p.type==="orphanLink",markerEnd:{type:vm.ArrowClosed,width:p.type==="submoduleLink"?16:18,height:p.type==="submoduleLink"?16:18,color:$l(p)},style:{stroke:$l(p),strokeWidth:p.type==="orphanLink"?2.25:p.type==="submoduleLink"?1.7:p.type==="worktreeLink"?1.8:2,strokeDasharray:p.type==="orphanLink"?"5 4":p.type==="submoduleLink"?"4 3":void 0},labelStyle:{fill:t.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:t.edgeLabelBackgroundColor,fillOpacity:1,stroke:t.edgeLabelBorderColor},labelBgPadding:[5,3],labelBgBorderRadius:6}));return{nodes:m,edges:b}}function $l(e){switch(e.type){case"parentBranch":return"#38bdf8";case"worktreeLink":return"#a78bfa";case"sessionLink":return"#34d399";case"orphanLink":return"#f97316";case"submoduleLink":return"#c084fc";default:return"#64748b"}}function j0({data:e,viewportKey:t}){const r=wm(),n=jm(),a=i.useRef(null),o=i.useMemo(()=>Tu(e),[e]),l=i.useMemo(()=>a0(e),[e]);return i.useEffect(()=>{if(!r||e.nodes.length===0||a.current===t)return;let c=!1;const d=requestAnimationFrame(()=>{if(c)return;const m=l.length>0&&l.length<e.nodes.length;n.fitView({nodes:m?l.map(u=>({id:u})):void 0,padding:m?.2:.16,maxZoom:m?1.04:.96,duration:260}),a.current=t});return()=>{c=!0,cancelAnimationFrame(d)}},[e.nodes.length,l,o,r,n,t]),null}function k0({data:e,selectedNodeId:t=null,onNodeClick:r}){const{theme:n}=er(),a=i.useMemo(()=>tr(n),[n]),o=i.useMemo(()=>w0(e,a),[e,a]),l=i.useMemo(()=>o0(e),[e]),c=i.useRef(null),[d,m]=i.useState({width:0,height:0}),u=i.useMemo(()=>i0(e,d.width,d.height),[e,d.height,d.width]),h=i.useMemo(()=>o.nodes.map(x=>({...x,selected:x.id===t})),[o.nodes,t]);return i.useEffect(()=>{const x=c.current;if(!x)return;const S=()=>{const p=Math.max(0,Math.round(x.clientWidth)),g=Math.max(0,Math.round(x.clientHeight));m(v=>v.width===p&&v.height===g?v:{width:p,height:g})};S();const b=typeof ResizeObserver=="function"?new ResizeObserver(()=>S()):null;return b==null||b.observe(x),window.addEventListener("resize",S),()=>{b==null||b.disconnect(),window.removeEventListener("resize",S)}},[]),s.jsx(Mu.Provider,{value:a,children:s.jsxs("div",{ref:c,className:a.graphShellClass,children:[s.jsxs("div",{className:`absolute inset-x-3 top-3 z-10 flex flex-wrap items-center justify-between gap-2 text-[11px] ${a.textSecondary}`,children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsxs("span",{className:a.graphStatChipClass,children:[e.stats.totalNodes," node",e.stats.totalNodes===1?"":"s"]}),s.jsxs("span",{className:a.graphStatChipClass,children:[e.stats.totalActiveSessions," active session",e.stats.totalActiveSessions===1?"":"s"]}),e.stats.orphanNodes>0&&s.jsxs("span",{className:a.isDark?"rounded-full border border-orange-400/25 bg-orange-500/12 px-3 py-1 text-orange-100":"rounded-full border border-orange-300 bg-orange-50 px-3 py-1 text-orange-700",children:[e.stats.orphanNodes," need attention"]})]}),s.jsx("div",{className:a.graphHintChipClass,children:"Focused on the main path first · drag or scroll to pan"})]}),s.jsx("div",{className:"h-[420px] w-full min-w-0 min-h-[420px] sm:h-[520px] xl:h-[640px]",children:s.jsxs(fm,{nodes:h,edges:o.edges,nodeTypes:v0,minZoom:.25,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!1,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(x,S)=>r==null?void 0:r(S.data.graphNode),className:"h-full w-full",colorMode:a.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(j0,{data:e,viewportKey:u}),l&&s.jsx(xm,{className:a.graphMiniMapClass,nodeColor:x=>Au(x.data.graphNode.health)}),s.jsx(bm,{className:a.graphControlsClass,showInteractive:!1}),s.jsx(gm,{variant:ym.Dots,gap:18,size:1.2,color:a.graphBackgroundDotColor})]})})]})})}const Bl=new Set(["pending","assigned"]),S0={pending:0,assigned:0},N0={recentFailures:0},Or=i.createContext(tr("dark"));function Ke({label:e,tone:t="default"}){const r=i.useContext(Or);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 hr({title:e,subtitle:t,children:r,className:n=""}){const a=i.useContext(Or);return s.jsxs("section",{className:`${a.cardClass} ${n}`,children:[s.jsxs("div",{className:a.cardHeaderClass,children:[s.jsx("div",{className:a.cardTitleClass,children:e}),t&&s.jsx("div",{className:a.cardSubtitleClass,children:t})]}),s.jsx("div",{className:"px-4 py-3",children:r})]})}function qe({label:e,value:t}){const r=i.useContext(Or);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 Ht({label:e,onClick:t,tone:r="default"}){const n=i.useContext(Or);return s.jsx("button",{type:"button",onClick:t,className:`rounded-full border px-2.5 py-1 text-[11px] transition ${n.actionButton(r)}`,children:e})}function ps(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function Rs(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleString()}function Ea(e){switch(e){case"completed":return"good";case"failed":case"cancelled":return"danger";case"assigned":return"info";case"pending":return"warn";default:return"default"}}function Ol(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 cn(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 Fl(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 _u(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 $a(e){return e===!0?"yes":e===!1?"no":"unknown"}function Wl(e,t){if(!t)return null;const r=new URLSearchParams;return e&&r.set("daemonId",e),r.set("targetSessionId",t),`/dashboard?${r.toString()}`}function Kl(e){if(e.gitProbePending)return"Git probe pending";const t=e.git;if(!t)return"No git probe";const r=(t.staged??0)+(t.modified??0)+(t.untracked??0)+(t.deleted??0)+(t.renamed??0),n=[];t.branch&&n.push(t.branch),t.upstream&&t.upstreamStatus!=="fresh"&&n.push("upstream unverified"),t.upstreamStatus==="fresh"&&((t.ahead??0)>0||(t.behind??0)>0)&&n.push(`↑${t.ahead??0}/↓${t.behind??0}`),r>0&&n.push(`${r} dirty`);const a=(t.submodules??[]).filter(l=>l.dirty),o=(t.submodules??[]).filter(l=>l.outOfSync||l.error);return a.length>0&&n.push(`${a.length} submodule dirty`),o.length>0&&n.push(`${o.length} submodule drift`),t.hasConflicts&&n.push("conflicts"),n.join(" · ")||"Clean"}function C0(e){switch(e){case"merged_to_main":return"merged to default branch";case"pushed_feature_branch_needs_merge":return"feature branch still needs merge";case"cleanup_candidate":return"worktree still needs refine / cleanup";case"blocked_review":return"review blocked before convergence";case"not_mergeable":return"not mergeable yet";default:return null}}function I0(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 Ba(e){const t=e.assignedNodeId||e.targetNodeId||"unbound",r=e.assignedSessionId||e.targetSessionId||"no session";return`${t} · ${r}`}function dn(e){return e.assignedNodeId||e.targetNodeId||null}function Oa(e){var t;return e.assignedSessionId||e.targetSessionId||((t=e.autoLaunch)==null?void 0:t.sessionId)||null}function Cr(e){return e?e.slice(0,7):null}function T0(e,t){var o,l,c;const r=Cr((o=e==null?void 0:e.git)==null?void 0:o.headCommit),n=((c=(l=e==null?void 0:e.git)==null?void 0:l.headMessage)==null?void 0:c.trim())||"";if(r||n)return[r,n].filter(Boolean).join(" · ");const a=t[0];return a?[Cr(a.commit),a.message].filter(Boolean).join(" · "):null}function M0(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 A0(e){var r,n,a,o,l,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)||((l=e.selectedNodeStatus)==null?void 0:l.workspace)||null;if(t&&e.selectedSessionEntry){const d=((c=e.selectedNodeStatus)==null?void 0:c.daemonId)||e.coordinatorDaemonId;return d?{daemonId:d,workspace:t}:null}if(t&&e.selectedNodeStatus){const d=e.selectedNodeStatus.daemonId||e.coordinatorDaemonId;return d?{daemonId:d,workspace:t}:null}return null}function _0(e){return(e.providers??[]).length>0?e.providers.join(", "):((e.providerPriority??[]).length>0,"not reported yet")}function Hl(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":_u(e.connection)}function Ul(e,t){return ps(e)??e??(t?"pending live refresh":"not reported")}function Lu({graph:e,status:t,emptyMessage:r="No live mesh graph is available for this coordinator yet.",daemonId:n=null,sendDaemonCommand:a=null}){var Se,ve,X,xe,fe,we,be,Ce,ee,me,ie,pe,le,B,z,de,re;const{theme:o}=er(),l=i.useMemo(()=>tr(o),[o]),c=As(),[d,m]=i.useState(null),[u,h]=i.useState(null),[x,S]=i.useState("active"),[b,p]=i.useState({}),g=i.useMemo(()=>new Map(t.nodes.map(R=>[R.nodeId,R])),[t.nodes]),v=i.useMemo(()=>new Map(e.nodes.map(R=>[R.id,R])),[e.nodes]),f=((Se=t.queue)==null?void 0:Se.tasks)??[],C=((ve=t.queue)==null?void 0:ve.summary)??null,T=(C==null?void 0:C.activeCounts)??S0,k=((X=t.ledger)==null?void 0:X.summary)??N0,A=i.useMemo(()=>I0(t),[t]),_=i.useMemo(()=>{const R=new Map;for(const q of A){const ce=q.session.state||q.session.lifecycle||"unknown";R.set(ce,(R.get(ce)??0)+1)}return[...R.entries()].sort((q,ce)=>ce[1]-q[1])},[A]),N=i.useMemo(()=>x==="all"?f:x==="active"?f.filter(R=>Bl.has(R.status)):f.filter(R=>!Bl.has(R.status)),[x,f]);i.useEffect(()=>{d&&(v.has(d)||(m(null),h(R=>!R||"nodeId"in R&&R.nodeId===d?null:R)))},[v,d]);const w=d?v.get(d)??null:null,D=d?g.get(d)??null:null,M=(u==null?void 0:u.kind)==="queue"?f.find(R=>R.id===u.taskId)??null:null,j=(u==null?void 0:u.kind)==="session"?A.find(R=>R.nodeId===u.nodeId&&R.session.sessionId===u.sessionId)??null:null,W=i.useMemo(()=>A.filter(R=>R.nodeId===d),[d,A]),H=i.useMemo(()=>f.filter(R=>dn(R)===d),[f,d]),$=A0({coordinatorDaemonId:n,selectedNodeStatus:D,selectedSessionEntry:j}),I=($==null?void 0:$.workspace)??null,y=I?b[I]??null:null,F=D!=null&&D.gitProbePending&&!((xe=y==null?void 0:y.entries)!=null&&xe.length)?"Pending live git probe":T0(D,(y==null?void 0:y.entries)??[]),P=i.useCallback(R=>{R&&c(Zt(R),{state:{openRemoteForTabKey:R}})},[c]),E=i.useCallback((R,q)=>{m(R),h({kind:"session",nodeId:R,sessionId:q})},[]),G=i.useCallback(R=>{m(R),h({kind:"node",nodeId:R})},[]);i.useEffect(()=>{if(!$||!a)return;const{daemonId:R,workspace:q}=$,ce=b[q];if(ce!=null&&ce.loading||ce&&(ce.entries.length>0||ce.error))return;let Ne=!1;return p(je=>{var O;return{...je,[q]:{loading:!0,error:null,entries:((O=je[q])==null?void 0:O.entries)??[]}}}),a(R,"git_log",{workspace:q,limit:5}).then(je=>{Ne||p(O=>({...O,[q]:{loading:!1,error:null,entries:M0(je)}}))}).catch(je=>{Ne||p(O=>({...O,[q]:{loading:!1,error:je instanceof Error?je.message:"git_log failed",entries:[]}}))}),()=>{Ne=!0}},[b,$,a]);const J=[...e.warnings??[],...t.nodes.filter(R=>R.machineStatus&&R.machineStatus!=="online").map(R=>`${R.machineLabel}: ${R.machineStatus}`)],ye=e.stats.incompleteSnapshotNodes>0,he=e.stats.followUpNodes>0?`${e.stats.followUpNodes} need follow-up`:ye?"mesh visibility incomplete":"mesh converged",ne=e.stats.followUpNodes>0?"danger":ye?"warn":"good",ue=!!(M||j||w);return s.jsx(Or.Provider,{value:l,children:s.jsxs("div",{className:"flex min-h-0 flex-col gap-4 xl:flex-row",children:[s.jsx("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col gap-4",children:s.jsxs("div",{className:`${l.cardClass} min-h-0 flex-1 rounded-[28px] p-3 sm:p-4`,style:{minHeight:420},children:[s.jsxs("div",{className:`mb-3 flex flex-wrap items-start justify-between gap-3 rounded-2xl px-3.5 py-3 ${l.isDark?"border border-white/10 bg-slate-950/45":"border border-slate-200 bg-white/95 shadow-sm"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-wrap gap-2 text-xs ${l.textSecondary}`,children:[s.jsx(Ke,{label:he,tone:ne}),e.stats.blockedReviewNodes>0&&s.jsx(Ke,{label:`${e.stats.blockedReviewNodes} blocked review`,tone:"danger"}),e.stats.notMergeableNodes>0&&s.jsx(Ke,{label:`${e.stats.notMergeableNodes} not mergeable`,tone:"danger"}),e.stats.mergeReadyNodes>0&&s.jsx(Ke,{label:`${e.stats.mergeReadyNodes} need merge`,tone:"warn"}),e.stats.cleanupCandidateNodes>0&&s.jsx(Ke,{label:`${e.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info"}),e.stats.offlineNodes>0&&s.jsx(Ke,{label:`${e.stats.offlineNodes} offline`,tone:"danger"}),e.stats.incompleteSnapshotNodes>0&&s.jsx(Ke,{label:`${e.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn"}),e.stats.missingGitSnapshotNodes>0&&s.jsx(Ke,{label:`${e.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn"}),e.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(Ke,{label:`${e.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn"}),e.stats.staleGitSnapshotNodes>0&&s.jsx(Ke,{label:`${e.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn"}),((C==null?void 0:C.active)??0)>0&&s.jsx(Ke,{label:`${(C==null?void 0:C.active)??0} active queue`,tone:"info"}),s.jsx(Ke,{label:`${e.stats.totalNodes} nodes`,tone:"default"}),e.stats.totalActiveSessions>0&&s.jsx(Ke,{label:`${e.stats.totalActiveSessions} active sessions`,tone:"info"})]}),s.jsxs("details",{className:`max-w-full rounded-xl px-3 py-2 text-xs ${l.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 ${l.textSecondary} [&::-webkit-details-marker]:hidden`,children:"Legend & secondary details"}),s.jsxs("div",{className:"mt-3 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ke,{label:`${e.stats.dirtyNodes} dirty`,tone:e.stats.dirtyNodes>0?"warn":"good"}),s.jsx(Ke,{label:`${e.stats.orphanNodes} orphan`,tone:e.stats.orphanNodes>0?"warn":"good"}),s.jsx(Ke,{label:`${k.recentFailures} recent failures`,tone:k.recentFailures>0?"danger":"good"}),_.length===0?s.jsx(Ke,{label:"no session metadata"}):_.slice(0,2).map(([R,q])=>s.jsx(Ke,{label:`${q} ${R}`,tone:cn(R)},R))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ke,{label:"Anchor = default branch",tone:"info"}),s.jsx(Ke,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(Ke,{label:"Submodule link = child checkout",tone:"warn"})]}),J.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:J.map(R=>s.jsx("span",{className:l.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:R},R))}),s.jsx("div",{className:`text-xs ${l.textMuted}`,children:"Click a node only when you want drill-down details. The graph itself now carries the convergence state."})]})]})]}),e.nodes.length>0?s.jsx(k0,{data:e,selectedNodeId:d,onNodeClick:R=>{if((u==null?void 0:u.kind)==="node"&&d===R.id){m(null),h(null);return}m(R.id),h({kind:"node",nodeId:R.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:r})]})}),ue&&s.jsxs("div",{className:"flex w-full shrink-0 flex-col gap-4 xl:w-[420px]",children:[s.jsx(hr,{title:"Selected detail",subtitle:"Node, session, or queue item drill-down.",children:s.jsx("div",{className:"flex flex-col gap-3",children:(u==null?void 0:u.kind)==="queue"&&M?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(Ke,{label:M.status,tone:Ea(M.status)}),s.jsx(Ke,{label:M.id.slice(0,8),tone:"default"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[dn(M)&&s.jsx(Ht,{label:"View node",onClick:()=>G(dn(M)||"")}),(()=>{const R=Oa(M);if(!R)return null;const q=A.find(ce=>ce.session.sessionId===R)??null;return s.jsxs(s.Fragment,{children:[q&&s.jsx(Ht,{label:"View session",onClick:()=>E(q.nodeId,q.session.sessionId)}),s.jsx(Ht,{label:"Open chat",tone:"info",onClick:()=>P(R)})]})})()]}),s.jsx(qe,{label:"Message",value:M.message}),s.jsx(qe,{label:"Routing",value:Ba(M)}),s.jsx(qe,{label:"Created",value:ps(M.createdAt)??"unknown"}),s.jsx(qe,{label:"Updated",value:ps(M.updatedAt)??"unknown"}),s.jsx(qe,{label:"Requeues",value:M.requeueCount??0}),s.jsx(qe,{label:"Auto-launch",value:M.autoLaunch?`${M.autoLaunch.status}${M.autoLaunch.providerType?` · ${M.autoLaunch.providerType}`:""}`:"none"}),(()=>{var Ne,je,O;const R=M.assignedSessionId||M.targetSessionId||((Ne=M.autoLaunch)==null?void 0:Ne.sessionId)||null,q=M.assignedNodeId||M.targetNodeId||((je=M.autoLaunch)==null?void 0:je.nodeId)||null,ce=Wl(q?(O=g.get(q))==null?void 0:O.daemonId:null,R);return ce?s.jsx("a",{href:ce,className:l.isDark?"inline-flex w-fit items-center rounded-full border border-sky-400/30 bg-sky-500/10 px-3 py-1 text-xs font-medium text-sky-100 transition hover:bg-sky-500/20":"inline-flex w-fit items-center rounded-full border border-sky-300 bg-sky-50 px-3 py-1 text-xs font-medium text-sky-700 transition hover:bg-sky-100",children:"Open linked dashboard chat"}):null})(),M.cancelReason&&s.jsx(qe,{label:"Cancel reason",value:M.cancelReason}),M.requeueReason&&s.jsx(qe,{label:"Requeue reason",value:M.requeueReason})]}):(u==null?void 0:u.kind)==="session"&&j?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(Ke,{label:j.session.state||j.session.lifecycle||"unknown",tone:cn(j.session.state||j.session.lifecycle)}),j.session.providerType&&s.jsx(Ke,{label:j.session.providerType,tone:"info"}),j.session.isCached&&s.jsx(Ke,{label:"cached",tone:"default"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ht,{label:"View node",onClick:()=>G(j.nodeId)}),s.jsx(Ht,{label:"Open chat",tone:"info",onClick:()=>P(j.session.sessionId)})]}),s.jsx(qe,{label:"Session id",value:j.session.sessionId}),s.jsx(qe,{label:"Node",value:j.machineLabel}),s.jsx(qe,{label:"Workspace",value:j.workspace}),s.jsx(qe,{label:"Branch",value:j.branch??"unknown"}),s.jsx(qe,{label:"Node health",value:j.nodeHealth}),s.jsx(qe,{label:"Lifecycle",value:j.session.lifecycle??"unknown"}),j.session.surfaceKind&&s.jsx(qe,{label:"Surface",value:j.session.surfaceKind}),j.session.recoveryState&&s.jsx(qe,{label:"Recovery",value:j.session.recoveryState}),j.session.lastActivityAt&&s.jsx(qe,{label:"Last activity",value:ps(j.session.lastActivityAt)??j.session.lastActivityAt}),(()=>{var q;const R=Wl((q=g.get(j.nodeId))==null?void 0:q.daemonId,j.session.sessionId);return R?s.jsx("a",{href:R,className:l.isDark?"inline-flex w-fit items-center rounded-full border border-sky-400/30 bg-sky-500/10 px-3 py-1 text-xs font-medium text-sky-100 transition hover:bg-sky-500/20":"inline-flex w-fit items-center rounded-full border border-sky-300 bg-sky-50 px-3 py-1 text-xs font-medium text-sky-700 transition hover:bg-sky-100",children:"Open dashboard chat"}):null})(),s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/10 bg-slate-950/40 p-3":"rounded-xl border border-slate-200 bg-slate-50 p-3",children:[s.jsx("div",{className:`mb-2 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Git context"}),s.jsxs("div",{className:`flex flex-col gap-2 text-xs ${l.textSecondary}`,children:[s.jsx("div",{children:F||"HEAD subject not present in cached mesh_status."}),(y==null?void 0:y.loading)&&s.jsx("div",{className:"text-slate-500",children:"Loading recent commits…"}),(y==null?void 0:y.error)&&s.jsxs("div",{className:"text-amber-200",children:["Recent history unavailable: ",y.error]}),((y==null?void 0:y.entries)??[]).slice(0,5).map(R=>s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-2.5 py-2":"rounded-lg border border-slate-200 bg-white px-2.5 py-2",children:[s.jsxs("div",{className:`font-medium ${l.textPrimary}`,children:[Cr(R.commit)," · ",R.message]}),s.jsxs("div",{className:"mt-1 text-[11px] text-slate-500",children:[R.authorName||"unknown author",Rs(R.committedAt)?` · ${Rs(R.committedAt)}`:""]})]},R.commit))]})]})]}):w?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/10 bg-slate-950/40 p-3":"rounded-xl border border-slate-200 bg-slate-50 p-3",children:[s.jsxs("div",{className:"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 ${l.textPrimary}`,children:w.label}),s.jsx("div",{className:`mt-1 break-all text-xs ${l.textMuted}`,children:(D==null?void 0:D.workspace)??w.workspace})]}),s.jsx("button",{type:"button",onClick:()=>{m(null),h(null)},className:l.isDark?"rounded-full border border-white/10 bg-white/[0.03] px-2 py-1 text-xs text-slate-300 transition hover:bg-white/[0.06] hover:text-white":"rounded-full border border-slate-200 bg-white px-2 py-1 text-xs text-slate-600 transition hover:bg-slate-50 hover:text-slate-900",children:"Close"})]}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[w.branch&&s.jsx(Ke,{label:w.branch,tone:"default"}),((fe=w.branchConvergence)==null?void 0:fe.status)&&s.jsx(Ke,{label:w.branchConvergence.status,tone:w.branchConvergence.needsConvergence?"warn":"good"}),w.snapshotWarnings.length>0&&s.jsx(Ke,{label:`snapshot ${w.snapshotCompleteness}`,tone:"warn"})]}),s.jsxs("div",{className:"mt-3 flex flex-col gap-0.5",children:[s.jsx(qe,{label:"Graph branch",value:w.branch??"unknown"}),s.jsx(qe,{label:"Graph upstream",value:w.upstream??"none"}),s.jsx(qe,{label:"Convergence",value:C0((we=w.branchConvergence)==null?void 0:we.status)??"not classified"})]}),w.snapshotWarnings.length>0&&s.jsxs("div",{className:l.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:"Peer snapshot warning"}),s.jsx("div",{className:"mt-1",children:w.snapshotWarnings[0]})]}),((be=w.branchConvergence)==null?void 0:be.nextStep)&&s.jsxs("div",{className:l.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:"Convergence follow-up"}),s.jsx("div",{className:"mt-1",children:w.branchConvergence.nextStep})]})]}),D&&s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/10 bg-slate-950/40 p-3":"rounded-xl border border-slate-200 bg-slate-50 p-3",children:[s.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[s.jsx(Ke,{label:D.health,tone:Ol(D.health)}),D.machineStatus&&s.jsx(Ke,{label:D.machineStatus,tone:D.machineStatus==="online"?"good":"warn"}),s.jsx(Ke,{label:`launchReady ${$a(D.launchReady)}`,tone:D.launchReady?"good":"warn"}),s.jsx(Ke,{label:Hl(D),tone:Fl(D.connection)}),D.worktreeBranch&&s.jsx(Ke,{label:D.worktreeBranch,tone:"info"})]}),s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsx(qe,{label:"Repo root",value:D.repoRoot??D.workspace}),s.jsx(qe,{label:"Provider(s)",value:_0(D)}),s.jsx(qe,{label:"Provider priority",value:(D.providerPriority??[]).join(", ")||"not configured"}),s.jsx(qe,{label:"Drift",value:Kl(D)}),s.jsx(qe,{label:"HEAD",value:F??(D.gitProbePending?"Pending live git probe":"Not available")}),s.jsx(qe,{label:"Daemon",value:D.daemonId??"unknown"}),s.jsx(qe,{label:"Machine",value:D.machineId??D.machineLabel}),s.jsx(qe,{label:"Launch ready",value:$a(D.launchReady)}),s.jsx(qe,{label:"Mesh connection",value:Hl(D)}),s.jsx(qe,{label:"Transport",value:((Ce=D.connection)==null?void 0:Ce.transport)??"unknown"}),s.jsx(qe,{label:"Connection source",value:((ee=D.connection)==null?void 0:ee.source)??"unknown"}),s.jsx(qe,{label:"Last seen",value:Ul(D.lastSeenAt,!!D.gitProbePending)}),s.jsx(qe,{label:"Updated",value:Ul(D.updatedAt,!!D.gitProbePending)}),((me=D.connection)==null?void 0:me.lastConnectedAt)&&s.jsx(qe,{label:"Last connected",value:ps(D.connection.lastConnectedAt)??D.connection.lastConnectedAt}),((ie=D.connection)==null?void 0:ie.lastCommandAt)&&s.jsx(qe,{label:"Last mesh command",value:ps(D.connection.lastCommandAt)??D.connection.lastCommandAt}),((pe=D.connection)==null?void 0:pe.reason)&&s.jsx(qe,{label:"Connection reason",value:D.connection.reason}),s.jsx(qe,{label:"Sessions",value:D.activeSessions.length}),D.error&&s.jsx(qe,{label:"Error",value:D.error})]}),W.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Active sessions"}),s.jsx("div",{className:"flex flex-col gap-2",children:W.map(R=>{const q=R.session.state||R.session.lifecycle||"unknown";return s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",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:`truncate font-medium ${l.textPrimary}`,children:R.session.title||R.session.sessionId}),s.jsxs("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:[R.session.providerType||"unknown provider"," · ",q]})]}),s.jsx(Ke,{label:q,tone:cn(q)})]}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[s.jsx(Ht,{label:"View session",onClick:()=>E(R.nodeId,R.session.sessionId)}),s.jsx(Ht,{label:"Open chat",tone:"info",onClick:()=>P(R.session.sessionId)})]})]},`${R.nodeId}:${R.session.sessionId}`)})})]}),H.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Related queue items"}),s.jsx("div",{className:"flex flex-col gap-2",children:H.map(R=>{const q=Oa(R),ce=q?A.find(Ne=>Ne.session.sessionId===q)??null:null;return s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",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:`truncate font-medium ${l.textPrimary}`,children:R.message}),s.jsx("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:Ba(R)})]}),s.jsx(Ke,{label:R.status,tone:Ea(R.status)})]}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[s.jsx(Ht,{label:"View queue detail",onClick:()=>h({kind:"queue",taskId:R.id})}),ce&&s.jsx(Ht,{label:"View session",onClick:()=>E(ce.nodeId,ce.session.sessionId)}),q&&s.jsx(Ht,{label:"Open chat",tone:"info",onClick:()=>P(q)})]})]},R.id)})})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Recent commits"}),s.jsxs("div",{className:"flex flex-col gap-2",children:[(y==null?void 0:y.loading)&&s.jsx("div",{className:(l.isDark,"text-xs text-slate-500"),children:"Loading recent commits…"}),(y==null?void 0:y.error)&&s.jsxs("div",{className:"text-xs text-amber-200",children:["Recent history unavailable: ",y.error]}),!(y!=null&&y.loading)&&!(y!=null&&y.error)&&((y==null?void 0:y.entries)??[]).length===0&&s.jsx("div",{className:(l.isDark,"text-xs text-slate-500"),children:"Recent commit history not available from the current mesh snapshot yet."}),((y==null?void 0:y.entries)??[]).slice(0,5).map(R=>s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",children:[s.jsxs("div",{className:`font-medium ${l.textPrimary}`,children:[Cr(R.commit)," · ",R.message]}),s.jsxs("div",{className:"mt-1 text-[11px] text-slate-500",children:[R.authorName||"unknown author",Rs(R.committedAt)?` · ${Rs(R.committedAt)}`:""]})]},R.commit))]})]}),(((B=(le=D.git)==null?void 0:le.submodules)==null?void 0:B.length)??0)>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Submodules"}),s.jsx("div",{className:"flex flex-col gap-2",children:(((z=D.git)==null?void 0:z.submodules)??[]).map(R=>s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"font-medium",children:R.path}),R.dirty&&s.jsx(Ke,{label:"dirty",tone:"warn"}),(R.outOfSync||R.error)&&s.jsx(Ke,{label:"drift",tone:"danger"})]}),s.jsx("div",{className:"mt-1 break-all text-[11px] text-slate-400",children:R.repoPath}),s.jsx("div",{className:"mt-1 text-[11px] text-slate-500",children:"Select the submodule node in the graph for its own HEAD and recent history."}),R.error&&s.jsx("div",{className:"mt-1 text-[11px] text-rose-200",children:R.error})]},`${D.nodeId}:${R.path}`))})]})]}),!D&&s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/10 bg-slate-950/40 p-3":"rounded-xl border border-slate-200 bg-slate-50 p-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Git context"}),s.jsx("div",{className:"text-xs text-slate-300",children:F??"No daemon-owned node status is attached to this graph node."}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${l.textMuted}`,children:"Recent commits"}),s.jsxs("div",{className:"flex flex-col gap-2",children:[(y==null?void 0:y.loading)&&s.jsx("div",{className:(l.isDark,"text-xs text-slate-500"),children:"Loading recent commits…"}),(y==null?void 0:y.error)&&s.jsxs("div",{className:"text-xs text-amber-200",children:["Recent history unavailable: ",y.error]}),!(y!=null&&y.loading)&&!(y!=null&&y.error)&&((y==null?void 0:y.entries)??[]).length===0&&s.jsx("div",{className:(l.isDark,"text-xs text-slate-500"),children:"Recent commit history not available for this detached graph node yet."}),((y==null?void 0:y.entries)??[]).slice(0,5).map(R=>s.jsxs("div",{className:l.isDark?"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",children:[s.jsxs("div",{className:`font-medium ${l.textPrimary}`,children:[Cr(R.commit)," · ",R.message]}),s.jsxs("div",{className:"mt-1 text-[11px] text-slate-500",children:[R.authorName||"unknown author",Rs(R.committedAt)?` · ${Rs(R.committedAt)}`:""]})]},R.commit))]})]})]})]}):s.jsx("div",{className:`text-xs ${l.textMuted}`,children:"Select a node, session, or queue item."})})}),s.jsxs(hr,{title:"Queue",subtitle:"Active work plus recent history from mesh_status.",children:[s.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:["active","history","all"].map(R=>s.jsx("button",{type:"button",onClick:()=>S(R),className:`rounded-full border px-3 py-1 text-xs transition ${x===R?l.isDark?"border-sky-400/30 bg-sky-500/10 text-sky-100":"border-sky-300 bg-sky-50 text-sky-700":l.isDark?"border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/[0.06]":"border-slate-200 bg-white text-slate-600 hover:bg-slate-50"}`,children:R},R))}),s.jsxs("div",{className:"mb-3 grid grid-cols-2 gap-2 text-xs sm:grid-cols-4 xl:grid-cols-2",children:[s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300":"rounded-xl border border-slate-200 bg-white px-3 py-2 text-slate-600",children:["Active ",s.jsx("span",{className:`ml-1 ${l.textPrimary}`,children:(C==null?void 0:C.active)??0})]}),s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300":"rounded-xl border border-slate-200 bg-white px-3 py-2 text-slate-600",children:["Pending ",s.jsx("span",{className:`ml-1 ${l.textPrimary}`,children:T.pending})]}),s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300":"rounded-xl border border-slate-200 bg-white px-3 py-2 text-slate-600",children:["Assigned ",s.jsx("span",{className:`ml-1 ${l.textPrimary}`,children:T.assigned})]}),s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300":"rounded-xl border border-slate-200 bg-white px-3 py-2 text-slate-600",children:["History ",s.jsx("span",{className:`ml-1 ${l.textPrimary}`,children:(C==null?void 0:C.historical)??0})]})]}),s.jsx("div",{className:"max-h-[24vh] overflow-y-auto pr-1",children:N.length===0?s.jsx("div",{className:`text-xs ${l.textMuted}`,children:"No queue items for this filter."}):s.jsx("div",{className:"flex flex-col gap-2",children:N.map(R=>{const q=Oa(R),ce=q?A.find(je=>je.session.sessionId===q)??null:null,Ne=dn(R);return s.jsxs("button",{type:"button",onClick:()=>h({kind:"queue",taskId:R.id}),className:`rounded-xl border px-3 py-2 text-left transition ${(u==null?void 0:u.kind)==="queue"&&u.taskId===R.id?l.isDark?"border-sky-400/30 bg-sky-500/10":"border-sky-300 bg-sky-50":l.isDark?"border-white/10 bg-white/[0.03] hover:bg-white/[0.06]":"border-slate-200 bg-white hover:bg-slate-50"}`,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:`truncate text-xs font-medium ${l.textPrimary}`,children:R.message}),s.jsx("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:Ba(R)})]}),s.jsx(Ke,{label:R.status,tone:Ea(R.status)})]}),(Ne||ce||q)&&s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[Ne&&s.jsx("button",{type:"button",onClick:je=>{je.stopPropagation(),G(Ne)},className:l.isDark?"text-[11px] text-slate-300 underline underline-offset-2 transition hover:text-white":"text-[11px] text-slate-600 underline underline-offset-2 transition hover:text-slate-900",children:"View node"}),ce&&s.jsx("button",{type:"button",onClick:je=>{je.stopPropagation(),E(ce.nodeId,ce.session.sessionId)},className:l.isDark?"text-[11px] text-slate-300 underline underline-offset-2 transition hover:text-white":"text-[11px] text-slate-600 underline underline-offset-2 transition hover:text-slate-900",children:"View session"}),q&&s.jsx("button",{type:"button",onClick:je=>{je.stopPropagation(),P(q)},className:l.isDark?"text-[11px] text-sky-200 underline underline-offset-2 transition hover:text-white":"text-[11px] text-sky-700 underline underline-offset-2 transition hover:text-sky-900",children:"Open chat"})]})]},R.id)})})})]}),s.jsx(hr,{title:"Sessions",subtitle:"Node-level active session roster.",children:s.jsx("div",{className:"max-h-[22vh] overflow-y-auto pr-1",children:A.length===0?s.jsx("div",{className:`text-xs ${l.textMuted}`,children:"No active session metadata in this mesh snapshot."}):s.jsx("div",{className:"flex flex-col gap-2",children:A.map(R=>{const q=R.session.state||R.session.lifecycle||"unknown";return s.jsx("button",{type:"button",onClick:()=>{m(R.nodeId),h({kind:"session",nodeId:R.nodeId,sessionId:R.session.sessionId})},className:`rounded-xl border px-3 py-2 text-left transition ${(u==null?void 0:u.kind)==="session"&&u.nodeId===R.nodeId&&u.sessionId===R.session.sessionId?l.isDark?"border-sky-400/30 bg-sky-500/10":"border-sky-300 bg-sky-50":l.isDark?"border-white/10 bg-white/[0.03] hover:bg-white/[0.06]":"border-slate-200 bg-white hover:bg-slate-50"}`,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:`truncate text-xs font-medium ${l.textPrimary}`,children:R.machineLabel}),s.jsxs("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:[R.session.title||R.session.providerType||"unknown provider"," · ",R.branch||"no branch"]})]}),s.jsxs("div",{className:"flex flex-col items-end gap-1",children:[s.jsx(Ke,{label:q,tone:cn(q)}),s.jsx("button",{type:"button",onClick:ce=>{ce.stopPropagation(),P(R.session.sessionId)},className:l.isDark?"text-[11px] text-sky-200 underline underline-offset-2 transition hover:text-white":"text-[11px] text-sky-700 underline underline-offset-2 transition hover:text-sky-900",children:"Open chat"})]})]})},`${R.nodeId}:${R.session.sessionId}`)})})})}),s.jsx(hr,{title:"Nodes",subtitle:"Health, branch, drift, and provider view per node.",children:s.jsx("div",{className:"max-h-[22vh] overflow-y-auto pr-1",children:s.jsx("div",{className:"flex flex-col gap-2",children:t.nodes.map(R=>s.jsx("button",{type:"button",onClick:()=>{m(R.nodeId),h({kind:"node",nodeId:R.nodeId})},className:`rounded-xl border px-3 py-2 text-left transition ${(u==null?void 0:u.kind)==="node"&&u.nodeId===R.nodeId?l.isDark?"border-sky-400/30 bg-sky-500/10":"border-sky-300 bg-sky-50":l.isDark?"border-white/10 bg-white/[0.03] hover:bg-white/[0.06]":"border-slate-200 bg-white hover:bg-slate-50"}`,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:`truncate text-xs font-medium ${l.textPrimary}`,children:R.machineLabel}),s.jsx("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:Kl(R)}),s.jsx("div",{className:(l.isDark,"mt-1 truncate text-[11px] text-slate-500"),children:(R.providers??[]).join(", ")||"no provider metadata"}),s.jsxs("div",{className:"mt-1 flex flex-wrap gap-1",children:[s.jsx(Ke,{label:`launchReady ${$a(R.launchReady)}`,tone:R.launchReady?"good":"warn"}),s.jsx(Ke,{label:_u(R.connection),tone:Fl(R.connection)})]})]}),s.jsxs("div",{className:"flex flex-col items-end gap-1",children:[s.jsx(Ke,{label:R.health,tone:Ol(R.health)}),R.machineStatus&&s.jsx(Ke,{label:R.machineStatus,tone:R.machineStatus==="online"?"good":"warn"}),R.activeSessions.length>0&&s.jsx(Ke,{label:`${R.activeSessions.length} sessions`,tone:"info"})]})]})},R.nodeId))})})}),s.jsx(hr,{title:"Recent mesh events",subtitle:"Read-only ledger tail from mesh_status.",children:s.jsx("div",{className:"max-h-[18vh] overflow-y-auto pr-1",children:(((de=t.ledger)==null?void 0:de.entries)??[]).length===0?s.jsx("div",{className:`text-xs ${l.textMuted}`,children:"No recent ledger entries."}):s.jsx("div",{className:"flex flex-col gap-2",children:(((re=t.ledger)==null?void 0:re.entries)??[]).map(R=>s.jsxs("div",{className:l.isDark?"rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2 text-xs text-slate-200":"rounded-xl border border-slate-200 bg-white px-3 py-2 text-xs text-slate-700",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("span",{className:`font-medium ${l.textPrimary}`,children:R.kind}),s.jsx("span",{className:(l.isDark,"text-[11px] text-slate-500"),children:ps(R.timestamp)??R.timestamp})]}),s.jsx("div",{className:`mt-1 truncate text-[11px] ${l.textMuted}`,children:R.nodeId||R.sessionId||R.providerType||"mesh-wide event"})]},R.id))})})})]})]})})}const zl=[1500,3e3,5e3,8e3,12e3];function L0(e){var t,r,n,a,o,l;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||(l=e.git)!=null&&l.repoRoot)}function R0(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>{var r;return L0(t)?!1:t.gitProbePending||((r=t.connection)==null?void 0:r.state)==="connecting"?!0:t.machineStatus==="online"||t.launchReady===!0})}function P0(e){return!Number.isInteger(e)||e<0?zl[0]:zl[e]??null}function kt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Re(...e){for(const t of e){if(typeof t!="string")continue;const r=t.trim();if(r)return r}}function $t(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function Dt(...e){for(const t of e)if(typeof t=="boolean")return t}function Fa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function D0(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 E0(e,t){if(!Array.isArray(e))return;const r=e.map(n=>{const a=kt(n),o=Re(a.path),l=Re(a.commit),c=Re(a.repoPath,a.repo_root)??D0(t,o);return!o||!l||!c?null:{path:o,commit:l,repoPath:c,dirty:Dt(a.dirty)??!1,outOfSync:Dt(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:$t(a.lastCheckedAt,a.last_checked_at)??Date.now(),...Re(a.error)?{error:Re(a.error)}:{}}}).filter(n=>n!==null);return r.length>0?r:void 0}function ko(e,t,r){const n=Dt(e.isGitRepo);if(!Object.keys(e).length||n===void 0)return;const a=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(h=>typeof h=="string"):[],o=$t(e.conflicts)??a.length,l=Dt(e.hasConflicts)??o>0,c=Re(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,d=E0(e.submodules,c),m=Re(e.upstreamStatus,e.upstream_status),u=Re(e.error);return{workspace:Re(e.workspace,t.workspace)||"",repoRoot:c??null,isGitRepo:n,branch:Re(e.branch)??null,headCommit:Re(e.headCommit)??null,headMessage:Re(e.headMessage)??null,upstream:Re(e.upstream)??null,upstreamStatus:m??"unchecked",ahead:$t(e.ahead)??0,behind:$t(e.behind)??0,staged:$t(e.staged)??0,modified:$t(e.modified)??0,untracked:$t(e.untracked)??0,deleted:$t(e.deleted)??0,renamed:$t(e.renamed)??0,hasConflicts:l,conflictFiles:a,stashCount:$t(e.stashCount,e.stash_count)??0,lastCheckedAt:(r==null?void 0:r.lastCheckedAt)??$t(e.lastCheckedAt,e.last_checked_at)??Date.now(),...d?{submodules:d}:{},...u?{error:u}:{}}}function $0(e){const t=kt(e.lastGit??e.last_git),r=kt(t.result),n=kt(t.status),a=kt(r.status),o=kt(e.lastProbe??e.last_probe),l=kt(o.git),c=kt(l.result),d=kt(l.status),m=kt(c.status),u=Object.keys(n).length?n:Object.keys(a).length?a:Object.keys(d).length?d:Object.keys(m).length?m:{};return ko(u,e,{lastCheckedAt:Date.now()})}function B0(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 O0(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 Vl(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=B0(e);return t.outOfSync?"degraded":t.dirty||O0(e)?"dirty":"online"}function F0(e){const t=Array.isArray(e.activeSessionDetails)?e.activeSessionDetails:Array.isArray(e.active_session_details)?e.active_session_details:null;if(t){const a=t.map(o=>{const l=kt(o),c=Re(l.sessionId,l.session_id,l.id);return c?{sessionId:c,...Re(l.providerType,l.provider)?{providerType:Re(l.providerType,l.provider)}:{},...Re(l.state,l.status)?{state:Re(l.state,l.status)}:{},...Re(l.lifecycle)?{lifecycle:Re(l.lifecycle)}:{},...Re(l.surfaceKind,l.surface_kind)?{surfaceKind:Re(l.surfaceKind,l.surface_kind)}:{},...Re(l.recoveryState,l.recovery_state)?{recoveryState:Re(l.recoveryState,l.recovery_state)}:{},...Re(l.workspace)?{workspace:Re(l.workspace)}:{},...Re(l.title)?{title:Re(l.title)}:{},...Re(l.lastActivityAt,l.last_activity_at)?{lastActivityAt:Re(l.lastActivityAt,l.last_activity_at)}:{},...Dt(l.isCached,l.is_cached)!==void 0?{isCached:Dt(l.isCached,l.is_cached)}:{}}:null}).filter(o=>o!==null);if(a.length>0)return a}const r=kt(e.activeSession??e.active_session),n=Re(r.id,r.sessionId,r.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id);if(n)return[{sessionId:n,...Re(r.providerType,r.provider)?{providerType:Re(r.providerType,r.provider)}:{},...Re(r.state,r.status)?{state:Re(r.state,r.status)}:{}}]}function Gl(e){const t=kt(e.connection);return Object.keys(t).length>0?t:void 0}function W0(e){const t=kt(e),r=Re(t.nodeId,t.id);if(!r)return null;const n=kt(t.cachedStatus),a=$0(t),o=a?void 0:ko(kt(t.git),t),l=a??o,c=l?void 0:ko(kt(n.git),t),d=l??c,m=Re(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),u=a?Vl(d):Re(t.health)||(d?Vl(d):void 0)||Re(n.health)||m||Re(t.status)||"unknown",x=(a?void 0:Re(t.error))??(l?void 0:Re(n.error)),S=F0(t),b=Fa(t.activeSessions),p=(S==null?void 0:S.map(v=>v.sessionId))??[],g=Fa(t.providerPriority);return{nodeId:r,machineLabel:Re(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,r)||r,workspace:Re(t.workspace,d==null?void 0:d.workspace)||"",...Re(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:Re(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)}:{},...Re(t.daemonId,t.daemon_id)?{daemonId:Re(t.daemonId,t.daemon_id)}:{},...Re(t.machineId,t.machine_id)?{machineId:Re(t.machineId,t.machine_id)}:{},...m?{machineStatus:m}:{},...Dt(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:Dt(t.isLocalWorktree,t.is_local_worktree)}:{},...Re(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:Re(t.worktreeBranch,t.worktree_branch)}:{},health:u,...d?{git:d}:{},...Dt(t.gitProbePending,t.git_probe_pending)!==void 0?{gitProbePending:Dt(t.gitProbePending,t.git_probe_pending)}:{},providers:Fa(t.providers),activeSessions:b.length>0?b:p,...S&&S.length>0?{activeSessionDetails:S}:{},...g.length>0?{providerPriority:g}:{},...Dt(t.launchReady)!==void 0?{launchReady:Dt(t.launchReady)}:{},...Re(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)?{lastSeenAt:Re(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)}:{},...Re(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)?{updatedAt:Re(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)}:{},...Gl(t)?{connection:Gl(t)}:{},...x?{error:x}:{}}}function K0(e){const t=Re(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(c=>W0(c)).filter(c=>c!==null):null;if(!t||!n)return null;const a=Re(e.meshName,e.mesh_name,e.name),o=Re(e.repoIdentity,e.repo_identity),l=Re(e.refreshedAt,e.refreshed_at,e.updatedAt,e.updated_at);return!a||!o||!l?null:{...e,meshId:t,meshName:a,repoIdentity:o,refreshedAt:l,nodes:n}}function Ru(e){const t=(e==null?void 0:e.result)??e,r=[e==null?void 0:e.status,t==null?void 0:t.status,t,e];for(const n of r){const a=K0(kt(n));if(a)return a}return null}function H0({activeConv:e,sendDaemonCommand:t,onClose:r}){var N;const n=typeof((N=e.settings)==null?void 0:N.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null,a=e.daemonId??null,o=Gd(),{theme:l}=er(),c=i.useMemo(()=>tr(l),[l]),[d,m]=i.useState(null),[u,h]=i.useState(null),[x,S]=i.useState(!1),[b,p]=i.useState(null),[g,v]=i.useState(null),f=i.useRef(0),C=i.useRef(null),T=i.useCallback(async()=>{if(C.current!=null&&(window.clearTimeout(C.current),C.current=null),!a||!n){f.current=0,p("This coordinator does not expose a live mesh id."),m(null),h(null);return}S(!0),p(null);try{const w=o!=null&&o.loadMeshStatus?await o.loadMeshStatus(a,n):await t(a,"mesh_status",{meshId:n}),D=Ru(w);if(!D){m(null),h(null),p("mesh_status returned an unexpected payload.");return}const M=ku(D);h(D),m(M),v(D.refreshedAt||new Date().toISOString())}catch(w){f.current=0,m(null),h(null),p(w instanceof Error?w.message:"Failed to load live mesh status")}finally{S(!1)}},[a,n,o,t]);i.useEffect(()=>{f.current=0,C.current!=null&&(window.clearTimeout(C.current),C.current=null),T()},[T]),i.useEffect(()=>{if(C.current!=null&&(window.clearTimeout(C.current),C.current=null),x||!u||!R0(u.nodes)){x||(f.current=0);return}const w=P0(f.current);if(w!=null)return C.current=window.setTimeout(()=>{f.current+=1,T()},w),()=>{C.current!=null&&(window.clearTimeout(C.current),C.current=null)}},[T,x,u]),i.useEffect(()=>{const w=D=>{D.key==="Escape"&&r()};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[r]);const k=(d==null?void 0:d.meshName)||(u==null?void 0:u.meshName)||n||"Repo Mesh",A=g?new Date(g).toLocaleTimeString():null,_=i.useMemo(()=>x?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[x]);return s.jsx("div",{className:c.dialogOverlayClass,onClick:r,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:c.dialogShellClass,onClick:w=>w.stopPropagation(),children:[s.jsxs("div",{className:c.dialogHeaderClass,children:[s.jsx("div",{className:"min-w-0 flex-1",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-sky-400/20 bg-sky-500/12 text-sky-200 shadow-[0_12px_30px_rgba(14,165,233,0.18)]",children:s.jsx(as,{size:18})}),s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("h2",{className:c.dialogTitleClass,children:k}),s.jsx("span",{className:c.dialogKickerClass,children:"Mesh observability"})]}),s.jsxs("p",{className:c.dialogSubtitleClass,children:[ut(e),e.workspaceName?` · ${e.workspaceName}`:"",d!=null&&d.repoIdentity?` · ${d.repoIdentity}`:""]})]})]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end",children:[A&&s.jsxs("span",{className:c.dialogRefreshedChipClass,children:["Refreshed ",A]}),s.jsx("button",{type:"button",onClick:()=>{f.current=0,T()},disabled:x,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:x?"Refreshing…":"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:c.dialogCloseButtonClass,"aria-label":"Close mesh graph",children:s.jsx(wt,{size:16})})]})]}),b&&s.jsx("div",{className:c.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:b}),s.jsx("div",{className:c.dialogBodyClass,children:d&&u?s.jsx(Lu,{graph:d,status:u,emptyMessage:_,daemonId:a,sendDaemonCommand:t}):s.jsx("div",{className:c.dialogEmptyClass,children:_})})]})})}function U0(e,t){const{sendCommand:r}=jt(),[n,a]=i.useState(null),[o,l]=i.useState(!1);i.useEffect(()=>{if(!e||!t){a(null);return}l(!0),r(e,"git_remote_url",{workspace:t}).then(d=>{const m=(d==null?void 0:d.result)??d;a(typeof(m==null?void 0:m.remoteUrl)=="string"?m.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>l(!1))},[e,t,r]);const c=z0(n);return{remoteUrl:n,githubUrl:c,loading:o}}function z0(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 Pu=5e3;function V0(e){return`git:${e}`}function G0({workspace:e,includeDiffSummary:t=!1,intervalMs:r=Pu}){return{type:"subscribe",topic:"workspace.git",key:V0(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function mi(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Ms(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 q0(e){const t=mi(e);return(t==null?void 0:t.success)===!1?{status:null,error:Ms(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:Ms(t,"Git status response did not include status")}}function Y0(e){const t=mi(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:Ms(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:Ms(t,"Git diff summary response did not include diffSummary")}}function Wa(e){return e===void 0||typeof e=="boolean"}function X0(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Wa(t.binary)&&Wa(t.truncated)&&Wa(t.staged)}function J0(e){const t=mi(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Ms(t,"Git file diff request failed")}:X0(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:Ms(t,"Git file diff response did not include a valid diff object")}}function Q0({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=Pu}){const{sendCommand:o,sendData:l}=jt(),c=typeof t=="string"?t.trim():"",d=!!(r&&e&&c),[m,u]=i.useState(null),[h,x]=i.useState(null),[S,b]=i.useState(!1),[p,g]=i.useState(null),v=i.useCallback(async()=>{if(!(!d||!e||!c)){b(!0),g(null);try{const C=q0(await o(e,"git_status",{workspace:c}));if(C.error){u(null),x(null),g(C.error);return}if(u(C.status),!n){x(null);return}const T=Y0(await o(e,"git_diff_summary",{workspace:c}));if(T.error){x(null),g(T.error);return}x(T.diffSummary)}catch(C){g(Ms(C,"Git status request failed"))}finally{b(!1)}}},[d,e,n,o,c]),f=i.useMemo(()=>c?G0({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return i.useEffect(()=>{if(!d||!e||!c||!f){u(null),x(null),b(!1),g(null);return}const C=l?Qt.subscribe({sendData:l},e,f,T=>{var k,A;T.workspace===c&&(u(T.status),x(T.diffSummary??null),g(((k=T.status)==null?void 0:k.error)||((A=T.diffSummary)==null?void 0:A.error)||null),b(!1))},{retryIntervalMs:1e3}):null;return v(),()=>{C==null||C()}},[d,e,v,f,l,c]),{status:m,diffSummary:h,loading:S,error:p,refresh:v}}const Z0={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},ev={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 ql(e){return e.split("/").pop()??e}function tv(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function sv({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 l=n===o.path,c=Z0[o.status]??"?",d=ev[o.status]??"text-zinc-400",m=tv(o.path),u=ql(o.path),h=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 ${l?"bg-surface-elevated":""}`,onClick:()=>r==null?void 0:r(o),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${d}`,title:o.status,children:c}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[m&&s.jsxs("span",{className:"text-text-secondary",children:[m,"/"]}),s.jsx("span",{className:"text-text-primary",children:u}),o.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",ql(o.oldPath)]}),h]}),!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 rv(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 nv({diff:e,binary:t,truncated:r,loading:n,error:a,className:o=""}){const l=i.useRef(null);if(i.useEffect(()=>{l.current&&(l.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(`
|
|
65
|
+
`);return s.jsxs("div",{ref:l,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:c.map((d,m)=>rv(d,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 av(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(`
|
|
66
|
+
`)}function Du({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=jt(),{status:a,diffSummary:o,loading:l,error:c,refresh:d}=Q0({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,u]=i.useState(null),[h,x]=i.useState(null),[S,b]=i.useState(""),[p,g]=i.useState(!1),[v,f]=i.useState(!1),[C,T]=i.useState(null),[k,A]=i.useState(null),{githubUrl:_}=U0(e,t),N=i.useCallback(async H=>{if(!((m==null?void 0:m.path)===H.path&&!m.loading)){u({path:H.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const $=await n(e,"git_diff_file",{workspace:t,path:H.path,staged:H.staged}),I=J0($);if(I.error||!I.diff){u({path:H.path,diff:"",binary:!1,truncated:!1,loading:!1,error:I.error??"Failed to load diff"});return}u({path:H.path,diff:I.diff.diff,binary:I.diff.binary??!1,truncated:I.diff.truncated??!1,loading:!1,error:null})}catch($){const I=$ instanceof Error?$.message:"Failed to load diff";u({path:H.path,diff:"",binary:!1,truncated:!1,loading:!1,error:I})}}},[e,n,m,t]),w=i.useCallback(H=>{b(""),g(!1),T(null),A(null),x(H)},[]),D=i.useCallback(()=>{x(null),T(null),f(!1)},[]),M=i.useCallback(async()=>{var H,$,I;if(h){f(!0),T(null);try{let y;h==="checkpoint"?y=await n(e,"git_checkpoint",{workspace:t,message:S,includeUntracked:p}):h==="stash"?y=await n(e,"git_stash_push",{workspace:t,message:S,includeUntracked:p}):h==="stash_pop"?y=await n(e,"git_stash_pop",{workspace:t}):h==="checkout_files"&&m&&(y=await n(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const F=(y==null?void 0:y.result)??y;if((F==null?void 0:F.success)===!1||F!=null&&F.error){T((F==null?void 0:F.error)??"Action failed"),f(!1);return}h==="checkpoint"?A(`Checkpoint created: ${(($=(H=F==null?void 0:F.checkpoint)==null?void 0:H.commit)==null?void 0:$.slice(0,7))??"done"}`):h==="stash"?A(`Stashed as ${((I=F==null?void 0:F.stash)==null?void 0:I.stashRef)??"stash@{0}"}`):h==="stash_pop"?A("Stash restored"):(A("File reverted"),u(null)),x(null),await d()}catch(y){T(y instanceof Error?y.message:"Action failed")}finally{f(!1)}}},[h,n,e,t,S,p,m,d]),j=!!(a!=null&&a.hasConflicts),W=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:H=>{H.target===H.currentTarget&&r()},children:s.jsxs("div",{className:"relative flex h-[80vh] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[s.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??"Git Status"}),s.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),_&&s.jsx("a",{href:`${_}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-sky-400 underline",title:"Open on GitHub",children:"GitHub ↗"})]}),s.jsx("button",{onClick:d,disabled:l,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(wt,{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"}),W===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:[l&&!o&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),o&&s.jsx(sv,{files:o.files,truncated:o.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:N}),!l&&!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(nv,{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:()=>A(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:()=>w("checkpoint"),disabled:j,title:j?"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:()=>w("stash"),disabled:j,title:j?"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:()=>w("stash_pop"),disabled:j||!(a!=null&&a.stashCount),title:j?"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:()=>w("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 H=av((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(H),A("Copied to clipboard"),setTimeout(()=>A(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),h&&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:[h==="checkpoint"&&"Create checkpoint commit",h==="stash"&&"Stash changes",h==="stash_pop"&&"Restore latest stash?",h==="checkout_files"&&`Revert changes to ${(m==null?void 0:m.path)??"file"}?`]}),(h==="checkpoint"||h==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:S,onChange:H=>b(H.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:p,onChange:H=>g(H.target.checked)}),"Include untracked files"]})]}),C&&s.jsx("p",{className:"text-xs text-red-400",children:C}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:D,disabled:v,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:M,disabled:v||(h==="checkpoint"||h==="stash")&&!S.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:v?"Working…":"Confirm"})]})]})})]})})}function ov({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=i.useState(!1),[o,l]=i.useState(!1),[c,d]=i.useState(!1),[m,u]=i.useState(!1),[h,x]=i.useState(!1),[S,b]=i.useState("quickstart"),[p,g]=i.useState("workspace"),v=i.useMemo(()=>!t&&!e,[t,e]),f=i.useCallback(N=>{a(N),N&&l(!1)},[]),C=i.useCallback(N=>{l(N),N&&a(!1)},[]),T=i.useCallback(()=>{b(r===0?"quickstart":"shortcuts"),g("workspace"),d(!0),a(!1),l(!1)},[r]),k=i.useCallback(()=>{d(!1)},[]),A=i.useCallback(()=>{u(!0)},[]),_=i.useCallback(()=>{u(!1)},[]);return i.useEffect(()=>{if(!v){x(!1);return}x(!0);const N=window.setTimeout(()=>{x(!1)},1e4);return()=>window.clearTimeout(N)},[v]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:m,guideNudgeVisible:h,guideTab:S,shortcutSection:p,isDesktopDashboard:v,setGuideTab:b,setShortcutSection:g,handleInboxOpenChange:f,handleHiddenOpenChange:C,handleOpenShortcutHelp:T,closeShortcutHelp:k,openNewSession:A,closeNewSession:_}}function iv(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 lv(e){return e instanceof Error?e.message:String(e||"")}function cv(e){const t=lv(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function dv({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:l,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:m,mobileChatConversations:u,hiddenConversations:h,ides:x,actionLogs:S,sendDaemonCommand:b,setActionLogs:p,setCliViewModeOverrides:g,isStandalone:v,initialDataLoaded:f,userName:C,requestedMobileTabKey:T,onRequestedMobileTabConsumed:k,requestedMachineId:A,onRequestedMachineConsumed:_,requestedMobileSection:N,onRequestedMobileSectionConsumed:w,containerRef:D,isSplitMode:M,numGroups:j,groupSizes:W,groupedConvs:H,clearedTabs:$,focusedGroup:I,focusGroup:y,moveTabToGroup:F,splitTabRelative:P,closeGroup:E,handleResizeStart:G,groupActiveTabIds:J,setGroupActiveTab:ye,groupTabOrders:he,setGroupTabOrder:ne,toggleHiddenTab:ue,visibleConversations:Se,requestedDesktopTabKey:ve,onRequestedDesktopTabConsumed:X,onDesktopActiveTabChange:xe,onRequestScrollToBottom:fe,onHideConversation:we,onShowHiddenConversation:be,onShowAllHiddenConversations:Ce,scrollToBottomRequest:ee,machineEntries:me,layoutProfile:ie,onBrowseMachineDirectory:pe,onSaveMachineWorkspace:le,onLaunchMachineIde:B,onLaunchMachineProvider:z,onListMachineMeshes:de,onLaunchMeshCoordinator:re,onListMachineSavedSessions:R,notifications:q,notificationUnreadCount:ce,liveSessionInboxState:Ne,onMarkNotificationRead:je,onMarkNotificationUnread:O,onDeleteNotification:Ie}){const Le=Nt.useRef(null),{inboxOpen:He,hiddenOpen:ze,shortcutHelpOpen:Xe,newSessionOpen:Je,guideNudgeVisible:rt,guideTab:pt,shortcutSection:xt,isDesktopDashboard:vt,setGuideTab:Te,setShortcutSection:Ve,handleInboxOpenChange:tt,handleHiddenOpenChange:Ge,handleOpenShortcutHelp:ot,closeShortcutHelp:U,openNewSession:V,closeNewSession:Z}=ov({isMobile:t,showMobileChatMode:e,visibleConversationCount:Se.length}),[ae,K]=Nt.useState(null),[Y,se]=Nt.useState(null),oe=Nt.useCallback((L,Q)=>{K({daemonId:L,workspace:Q})},[]),ke=Nt.useCallback(L=>{se(L)},[]),Pe=Nt.useCallback(L=>{var Q;Tr.flushSync(()=>{be(L)}),(Q=Le.current)==null||Q.restoreHiddenTabToSavedLocation(L.tabKey)},[be]),Ee=Nt.useCallback(L=>{var ge;const Q=u.find(Be=>uo(Be,L))||h.find(Be=>uo(Be,L));Q&&(h.some(Be=>Be.tabKey===Q.tabKey)&&Pe(Q),xe(Q.tabKey),(ge=Le.current)==null||ge.activateConversationTab(Q.tabKey),fe(Q.tabKey,"notification-open")),je(L.id),tt(!1)},[Pe,h,u,xe,je,fe]),Ae=Nt.useCallback(()=>{var Q;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Q=Le.current)==null||Q.resetAllPanelsToMain(),Ge(!1))},[Ge]),$e=Nt.useCallback(async L=>{var Oe;if(!r)return;const Q=(Oe=r.modalButtons)==null?void 0:Oe[L];if(!Q)return;const ge=Gs(r);if(!ge)return;const Be=Q.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),_e=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(Be);try{await b(ge,"resolve_action",{button:Q,action:_e?"approve":"reject",buttonIndex:L,...xs(r)})}catch(nt){cv(nt)||console.error("[Shortcut approval] Failed:",nt)}},[r,b]),{isMac:Fe,actionDefinitions:Me,actionShortcuts:Qe,shortcutListening:et,shortcutListeningDraft:bt,setShortcutListening:gt,setShortcutListeningDraft:dt,saveShortcuts:ht}=Ty({enabled:vt&&!Xe,onTrigger:L=>{var Q,ge,Be,_e,Oe,nt,Mt,ft,ss,Fr,Wr,Kr,Hr,Ur,zr,Vr;if(L==="openShortcutHelp"){ot();return}if(L==="openNewSession"){V();return}if(L==="hideCurrentTab"){r&&we(r);return}if(L==="toggleHiddenTabs"){Ge(!ze);return}if(L==="openHistoryForActiveTab"){r&&!st(r)&&o(r);return}if(L==="openRemoteForActiveTab"){r&&!at(r)&&!st(r)&&l(r);return}if(L==="splitActiveTabRight"){(Q=Le.current)==null||Q.splitActiveTabRight();return}if(L==="splitActiveTabDown"){(ge=Le.current)==null||ge.splitActiveTabDown();return}if(L==="floatActiveTab"){(Be=Le.current)==null||Be.floatActiveTab();return}if(L==="popoutActiveTab"){(_e=Le.current)==null||_e.popoutActiveTab();return}if(L==="dockActiveTab"){(Oe=Le.current)==null||Oe.dockActiveTab();return}if(L==="focusLeftPane"){(nt=Le.current)==null||nt.focusLeftPane();return}if(L==="focusRightPane"){(Mt=Le.current)==null||Mt.focusRightPane();return}if(L==="focusUpPane"){(ft=Le.current)==null||ft.focusUpPane();return}if(L==="focusDownPane"){(ss=Le.current)==null||ss.focusDownPane();return}if(L==="moveActiveTabToLeftPane"){(Fr=Le.current)==null||Fr.moveActiveTabToLeftPane();return}if(L==="moveActiveTabToRightPane"){(Wr=Le.current)==null||Wr.moveActiveTabToRightPane();return}if(L==="moveActiveTabToUpPane"){(Kr=Le.current)==null||Kr.moveActiveTabToUpPane();return}if(L==="moveActiveTabToDownPane"){(Hr=Le.current)==null||Hr.moveActiveTabToDownPane();return}if(L==="triggerPrimaryApprovalAction"){$e(0);return}if(L==="triggerSecondaryApprovalAction"){$e(1);return}if(L==="triggerTertiaryApprovalAction"){$e(2);return}if(L==="setActiveTabShortcut"){(Ur=Le.current)==null||Ur.setShortcutForActiveTab();return}if(L==="selectPreviousGroupTab"){(zr=Le.current)==null||zr.activatePreviousTabInGroup();return}if(L==="selectNextGroupTab"){(Vr=Le.current)==null||Vr.activateNextTabInGroup();return}!r||!at(r)||st(r)||L==="toggleCliView"&&m(d==="chat"?"terminal":"chat")}}),Ue=Nt.useCallback(()=>{U(),gt(null),dt([])},[U,gt,dt]),Kt=Nt.useMemo(()=>xt==="all"?Me:Me.filter(L=>iv(L)===xt),[Me,xt]),te=Nt.useCallback(()=>{const L=Object.fromEntries(Me.map(Q=>[Q.id,""]));ht(L)},[Me,ht]),De=Nt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const L=Object.fromEntries(Me.map(Q=>[Q.id,Q.defaultShortcut]));ht(L)},[Me,ht]);return Nt.useEffect(()=>{const L=Q=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Q.metaKey&&Q.key.toLowerCase()==="w":Q.ctrlKey&&Q.key.toLowerCase()==="w")&&(Q.preventDefault(),r&&we&&we(r))};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[r,we]),Nt.useEffect(()=>{if(!Xe||et)return;const L=Q=>{Q.key==="Escape"&&(Q.preventDefault(),Ue())};return window.addEventListener("keydown",L,!0),()=>window.removeEventListener("keydown",L,!0)},[Ue,Xe,et]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(Cx,{activeConv:r,wsStatus:n,isConnected:a,conversations:Se,hiddenConversations:h,onOpenHistory:o,onHideConversation:we,onShowConversation:Pe,onShowAllHidden:Ce,onResetPanelsToMain:Ae,notifications:q,notificationUnreadCount:ce,onOpenNotification:Ee,onMarkNotificationRead:je,onMarkNotificationUnread:O,onDeleteNotification:Ie,inboxOpen:He,onInboxOpenChange:tt,hiddenOpen:ze,onHiddenOpenChange:Ge,onOpenNewSession:t?void 0:V,onOpenDashboardGuide:ot,guideNudgeVisible:rt,actionShortcuts:Qe,onOpenRemote:()=>{!r||at(r)||st(r)||l(r)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:m,onOpenGitDialog:oe,onOpenMeshGraph:ke}),e?s.jsx(xy,{conversations:u,hiddenConversations:h,ides:x,actionLogs:S,sendDaemonCommand:b,setActionLogs:p,setCliViewModeOverrides:g,isStandalone:v,userName:C,requestedActiveTabKey:T,onRequestedActiveTabConsumed:k,requestedMachineId:A,onRequestedMachineConsumed:_,requestedMobileSection:N,onRequestedMobileSectionConsumed:w,onOpenHistory:o,onOpenRemote:l,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:Ce,onHideConversation:we,onOpenMeshGraph:ke,onOpenNewSession:V,liveSessionInboxState:Ne}):t?s.jsx(Sy,{containerRef:D,isSplitMode:M,numGroups:j,groupSizes:W,groupedConvs:H,clearedTabs:$,ides:x,actionLogs:S,sendDaemonCommand:b,setActionLogs:p,isStandalone:v,hasRegisteredMachines:me.length>0,userName:C,focusedGroup:I,focusGroup:y,moveTabToGroup:F,splitTabRelative:P,closeGroup:E,handleResizeStart:G,groupActiveTabIds:J,setGroupActiveTab:ye,groupTabOrders:he,setGroupTabOrder:ne,toggleHiddenTab:ue,onOpenNewSession:V,allowTabShortcuts:!1,liveSessionInboxState:Ne}):s.jsx(Ky,{visibleConversations:Se,clearedTabs:$,ides:x,actionLogs:S,sendDaemonCommand:b,setActionLogs:p,isStandalone:v,hasRegisteredMachines:me.length>0,initialDataLoaded:f,userName:C,toggleHiddenTab:ue,actionShortcuts:Qe,registerActionHandlers:L=>{Le.current=L},onActiveTabChange:xe,requestedActiveTabKey:ve,onRequestedActiveTabConsumed:X,onRequestScrollToBottom:fe,scrollToBottomRequest:ee,onOpenNewSession:V,liveSessionInboxState:Ne,layoutProfile:ie}),Je&&s.jsx(Gy,{machines:me,ides:x,onClose:Z,onBrowseDirectory:pe,onSaveWorkspace:le,onLaunchIde:B,onLaunchProvider:z,onListMeshes:de,onLaunchMeshCoordinator:re,onListSavedSessions:R}),Y&&s.jsx(H0,{activeConv:Y,sendDaemonCommand:b,onClose:()=>se(null)}),ae&&s.jsx(Du,{daemonId:ae.daemonId,workspace:ae.workspace,onClose:()=>K(null)}),Xe&&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:Ue,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:L=>L.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:Ue,"aria-label":"Close dashboard guide",children:s.jsx(wt,{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(L=>s.jsx("button",{type:"button",className:`btn btn-sm ${pt===L.id?"btn-primary":"btn-secondary"}`,onClick:()=>Te(L.id),children:L.label},L.id))}),pt==="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 ",Fe?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),pt==="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."]})]})]})]}),pt==="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(L=>s.jsx("button",{type:"button",className:`btn btn-sm ${xt===L.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ve(L.id),children:L.label},L.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:te,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:Kt.map(L=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${et===L.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:L.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:L.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:L.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:et===L.id?bt.length>0?`${bt.join(" ")} ...`:"Listening...":Qe[L.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{gt(L.id),dt([])},children:et===L.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Q={...Qe};Q[L.id]="",ht(Q)},children:"Disable"})]})]})},L.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Fe?"⌘⇧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 Ka=[{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 uv({onClose:e}){const[t,r]=i.useState(0),n=Ka[t],a=t===Ka.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(wt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Ka.map((o,l)=>s.jsx("div",{style:{width:l===t?24:8,height:8,borderRadius:4,background:l===t?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},l))}),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:`
|
|
67
67
|
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
68
68
|
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
69
|
-
`})]})}function lv({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 l=r===o.tabKey,c=o.status==="waiting_approval",d=o.status==="generating";return s.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${l?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a(o.tabKey),children:[s.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:c?"var(--status-warning)":d?"var(--accent-primary)":"var(--text-muted)",boxShadow:d?"0 0 6px var(--accent-primary)":"none"}}),o.title,c&&s.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},o.tabKey)})]}):null}function cv({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,l]=i.useState(()=>a||"native"),c=i.useMemo(()=>xd(t),[t]),d=i.useMemo(()=>e?ti(e,{machineNames:c,connectionStates:r,defaultConnectionState:"new"}):[],[e,c,r]),m=i.useMemo(()=>d.find(p=>p.streamSource==="native"),[d]),u=i.useMemo(()=>d.filter(p=>p.streamSource==="agent-stream"),[d]),h=i.useMemo(()=>e?Wt(d,e.id):null,[d,e]);i.useEffect(()=>{a&&l(a)},[a]),i.useEffect(()=>{if(a||!h)return;const p=h.streamSource==="native"?"native":h.tabKey;!p||o===p||o==="native"&&l(p)},[o,h,a]),i.useEffect(()=>{var p;o!=="native"&&(u.some(g=>g.tabKey===o)||l(((p=u[0])==null?void 0:p.tabKey)||"native"))},[o,u]),i.useEffect(()=>{o==="native"&&(m||u[0]&&l(u[0].tabKey))},[o,m,u]);const x=i.useMemo(()=>o==="native"&&m?m:u.find(p=>p.tabKey===o)||h||m||u[0],[o,m,h,u]),S=i.useMemo(()=>u.map(p=>({tabKey:p.tabKey,title:cd(p)||n,status:p.status})),[u,n]),b=i.useCallback(p=>{if(p)return d.find(g=>uo(g,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[d]);return{activeChatTab:o,setActiveChatTab:l,activeConv:x,conversations:d,extensionTabs:S,hasExtensions:S.length>0,resolveConversationByTarget:b}}function dv({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:l,isStandalone:c,userName:d,onOpenHistory:m,onConversationChange:u,onClose:h}){const[x,S]=i.useState("split"),[b,p]=i.useState(()=>ls(e)?"native":e.tabKey),g=i.useRef(null),v=i.useMemo(()=>t||r.find(y=>y.id===e.routeId),[e.routeId,t,r]),f=i.useMemo(()=>ct((v==null?void 0:v.type)||""),[v==null?void 0:v.type]),{conversations:T,extensionTabs:I,hasExtensions:k}=cv({ideData:v,allIdes:r,connectionStates:n,ideName:f||"IDE",preferredTabKey:ls(e)?void 0:e.tabKey}),A=i.useMemo(()=>v?Wt(T,v.id):null,[v,T]);i.useEffect(()=>{const y=g.current,F={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(g.current=F,!(y&&y.routeId===F.routeId&&y.tabKey===F.tabKey&&y.streamSource===F.streamSource)){if(ls(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),i.useEffect(()=>{if(b==="native"){if(T.some(y=>y.streamSource==="native"))return;(A==null?void 0:A.streamSource)==="agent-stream"&&p(A.tabKey);return}if(!T.some(y=>y.tabKey===b)){if((A==null?void 0:A.streamSource)==="agent-stream"){p(A.tabKey);return}p("native")}},[T,b,A]);const _=i.useMemo(()=>b==="native"?T.find(y=>y.streamSource==="native")||e:T.find(y=>y.tabKey===b)||e,[e,T,b]),N=Md(_),w=i.useMemo(()=>N.status||N.modalMessage||N.modalButtons?{..._,...N.status?{status:N.status}:{},...N.modalMessage!==void 0?{modalMessage:N.modalMessage}:{},...N.modalButtons!==void 0?{modalButtons:N.modalButtons}:{}}:_,[_,N]),D=Dr(w),M=qn({sendDaemonCommand:o,activeConv:w,setActionLogs:l,isStandalone:c}),{connScreenshot:j,screenshotUsage:W,handleRemoteAction:H}=au({doId:D,targetSessionId:Vc(w),connState:w.connectionState||"new",viewMode:x}),$=i.useMemo(()=>a.filter(y=>y.routeId===w.tabKey),[a,w.tabKey]);i.useEffect(()=>{u==null||u(w)},[w,u]),i.useEffect(()=>{const y=F=>{F.key==="Escape"&&h()};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[h]);const C=i.useCallback(y=>{y.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:h,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:C,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(_t,{size:16})}),s.jsx("span",{className:"truncate",children:Ho(_)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:h,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(y=>{const F=x===y;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${F?"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:()=>S(y),title:y==="split"?"Split view":"Remote only",children:y==="split"?s.jsx(sp,{size:15}):s.jsx(_t,{size:15})},y)})}),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(_),title:"Chat History",children:[s.jsx(_o,{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:h,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${x==="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:[x!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${x==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(lv,{hasExtensions:k,ideName:f||"IDE",activeChatTab:b,extensionTabs:I,onSelectTab:p}),s.jsx(Lc,{activeConv:w,onModalButton:M.handleModalButton}),s.jsx(po,{activeConv:w,ideEntry:v,showMetaChips:!1,handleSendChat:M.handleSendChat,isSendingChat:M.isSendingChat,sendFeedbackMessage:M.sendFeedbackMessage,handleFocusAgent:M.handleFocusAgent,isFocusingAgent:M.isFocusingAgent,actionLogs:$,userName:d})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${x==="split"?"order-1 md:order-2":""}`,children:s.jsx(Ac,{addLog:()=>{},connState:w.connectionState||"new",connScreenshot:j,screenshotUsage:W,transportType:w.transport,onAction:H})})]})]})})}function uv({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=hx(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 mv({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o}){var l;return s.jsxs(s.Fragment,{children:[s.jsx(yx,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(ei,{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(dv,{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&&(at(r.targetConv)||st(r.targetConv))&&s.jsx(uv,{activeConv:r.targetConv,canSaveAndStop:at(r.targetConv)&&!st(r.targetConv)&&!!((l=r.targetConv.resume)!=null&&l.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(fd,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),o.open&&s.jsx(iv,{onClose:o.onClose})]})}function pv({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(Rr,{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(l=>{const c=At(l,{fallbackId:l.id}),d=n[l.id],m=l.version||l.daemonVersion||"unknown",u=l.versionUpdateRequired===!0,x=Hd(l)==="preview"?"Update to preview":u?"Update now":"Upgrade";return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[s.jsx("span",{className:"font-medium text-text-primary",children:c}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",m]}),u&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),d==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:u?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):d==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):d==="error"?s.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(l.id),children:"retry"}):s.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:u?"var(--status-danger)":"var(--status-warning)",background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(l.id),children:x})]},l.id)})]}),!r&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:o,title:"Dismiss",children:s.jsx(wt,{size:16})})]})}function hv(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function fv(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 xv(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>fv(t)).map(t=>t.id)}}function bv(){var yi,vi,wi,ji;const{sendCommand:e}=jt(),t=Er(),r=Td(),n=To(),a=As(),[o,l]=jm(),c=o.get("activeTab"),d=((yi=n.state)==null?void 0:yi.openRemoteForTabKey)||null,m=((vi=n.state)==null?void 0:vi.openMachineId)||null,u=((wi=n.state)==null?void 0:wi.mobileSection)||null,h=ad(),x=h.ides||[],S=h.initialLoaded??!0,{updateRouteChats:b,setToasts:p}=h,[g,v]=i.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),f=h.toasts||[],T=h.wsStatus||"connected",I=h.isConnected??!0,k=h.connectionStates||{},A=h.showReconnected||!1,{layoutProfile:_,groupAssignments:N,updateGroupAssignments:w,focusedGroup:D,updateFocusedGroup:M,focusGroup:j,groupActiveTabIds:W,updateGroupActiveTabIds:H,setGroupActiveTab:$,groupTabOrders:C,updateGroupTabOrders:y,setGroupTabOrder:F,groupSizes:P,updateGroupSizes:E,isMobile:G,hasHydratedStoredLayout:J,hydrateStoredLayout:ye,focusConversationTab:he}=dg(),[ne,ue]=i.useState(()=>ni());i.useEffect(()=>jb(ue),[]);const Se=i.useMemo(()=>hv({isMobile:G,mobileViewMode:ne}),[G,ne]),[ve,X]=i.useState([]),[xe,fe]=i.useState({}),[we,be]=i.useState({});Pr("Dashboard",{ideCount:x.length,toastCount:f.length,focusedGroup:D,groupCount:Object.keys(N).length,actionLogCount:ve.length});const Ce=i.useMemo(()=>x.filter(Ye=>Ye.type==="adhdev-daemon").sort(Fo),[x]),ee=Ce[0],me=!!ee;i.useEffect(()=>{const{metadataDaemonIds:Ye,runtimeDaemonIds:Et}=xv(Ce);for(const sr of Ye)t(sr,{minFreshMs:3e4}).catch(()=>{});for(const sr of Et)r(sr,{minFreshMs:3e4}).catch(()=>{})},[t,r,Ce]);const ie=(ee==null?void 0:ee.terminalBackend)||null,pe=ee?At(ee,{fallbackId:ee.id}):null,le=(ee==null?void 0:ee.id)||null,B=i.useMemo(()=>Eb(x,xe),[x,xe]),{hiddenTabs:z,autoHiddenTabs:de,autoHideTarget:re,hideTarget:R,toggleTarget:q,showTarget:ce,showAllTabs:Ne}=Db(),{conversations:je,visibleConversations:O,visibleTabKeys:Ie,resolveConversationBySessionId:Le,resolveConversationByTarget:He}=Yb({ides:B,connectionStates:k,clearedTabs:we,hiddenTabs:z}),ze=i.useMemo(()=>new Map(je.map(Ye=>[Ye.tabKey,Ye])),[je]),Xe=i.useMemo(()=>Pb(je,z,de),[je,z,de]);i.useEffect(()=>{for(const Ye of Xe)re(Ye)},[Xe,re]),zf(O,Se),i.useEffect(()=>{Object.keys(xe).length!==0&&fe(Ye=>$b(Ye,x))},[x,xe]);const Je=i.useMemo(()=>Qp(x),[x]),{notifications:rt,unreadCount:pt}=Cg({conversations:je,liveSessionInboxState:Je}),{handleMarkDashboardNotificationRead:xt,handleMarkDashboardNotificationUnread:vt,handleDeleteDashboardNotification:Te}=Ig({notifications:rt,sendDaemonCommand:e}),{containerRef:Ve,normalizedGroupAssignments:tt,numGroups:Ge,isSplitMode:ot,groupedConvs:U,moveTabToGroup:V,closeGroup:Z,handleResizeStart:ae,splitTabRelative:K}=bg({groupAssignments:N,updateGroupAssignments:w,updateFocusedGroup:M,updateGroupActiveTabIds:H,updateGroupTabOrders:y,groupSizes:P,updateGroupSizes:E,isMobile:G,visibleConversations:O,visibleTabKeys:Ie}),{activeConv:Y,openDesktopConversation:se,requestScrollToBottom:oe,scrollToBottomRequest:ke,setDesktopActiveTab:Pe}=Wg({isMobile:G,conversations:je,visibleConversations:O,groupActiveTabIds:W,focusedGroup:D,groupedConvs:U,setSearchParams:l});Ug({activeConv:Y,isMobile:G,liveSessionInboxState:Je,sendDaemonCommand:e});const{requestedDesktopTabKey:Ee,requestedMobileTabKey:Ae,consumeRequestedActiveTab:$e}=Xb({isMobile:G,urlActiveTab:c,resolveConversationBySessionId:Le,setSearchParams:l}),{remoteDialogConv:Fe,remoteDialogIdeEntry:Me,remoteDialogActiveConv:Qe,setRemoteDialogActiveConv:et,openRemoteDialog:bt,closeRemoteDialog:gt,cliStopDialogOpen:dt,cliStopTargetConv:ht,requestCliStop:Ue,cancelCliStop:Kt,confirmCliStop:te}=Gg({isMobile:G,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:Ee,conversations:je,ides:x,resolveConversationByTarget:He,activeConv:Y,sendDaemonCommand:e}),{historyModalOpen:De,openHistoryModal:L,closeHistoryModal:Q,historyTargetConv:ge,isSavedSessionHistoryTarget:Be,isHistoryCreatingChat:_e,isHistoryRefreshingHistory:Oe,handleHistorySwitchSession:nt,handleHistoryNewChat:Mt,handleHistoryRefresh:ft,savedHistorySessions:ss,savedHistoryFilters:Fr,setSavedHistoryFilters:Wr,missingWorkspaceResumePath:Kr,isSavedHistoryLoading:Hr,resumingSavedHistorySessionId:Ur,handleRefreshSavedHistory:zr,handleResumeSavedHistorySession:Vr}=zg({activeConv:Y,remoteDialogConv:Fe,remoteDialogActiveConv:Qe,ides:x,sendDaemonCommand:e,updateRouteChats:b,setToasts:p,setClearedTabs:be,setSearchParams:l}),Ou=i.useMemo(()=>O,[O]),Gr=G&&ne==="chat",Fu=i.useMemo(()=>je.filter(Ye=>Xn(z,Ye)),[je,z]),xi=i.useCallback(Ye=>{const Et=new URLSearchParams(o);Et.set("activeTab",Ye),l(Et,{replace:!0})},[o,l]),{trackPendingLaunch:Wu}=$g({ides:x,conversations:je,onOpenSession:xi}),{handleBrowseMachineDirectory:Ku,handleSaveMachineWorkspace:Hu,handleLaunchMachineIde:Uu,handleLaunchMachineProvider:zu,handleListMachineMeshes:Vu,handleLaunchMeshCoordinator:Gu,handleListMachineSavedSessions:qu,setActiveCliViewMode:Yu}=Bg({sendDaemonCommand:e,trackPendingLaunch:Wu,onOpenSession:xi,activeConv:Y,ides:x,setCliViewModeOverrides:fe});Bb({visibleConversations:O,clearedTabs:we,setClearedTabs:be,setActionLogs:X}),Jb({ides:x,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:He});const{isRefreshingHistory:Xu,handleRefreshHistory:Ju}=Kd({sendDaemonCommand:e,activeConv:Y,chats:(ji=x.find(Ye=>Ye.id===(Y==null?void 0:Y.routeId)))==null?void 0:ji.chats,updateRouteChats:b,setToasts:p,setClearedTabs:be});mg({urlActiveTab:G&&!Gr?c:null,conversations:je,resolveConversationBySessionId:Le,normalizedGroupAssignments:tt,hasHydratedStoredLayout:G&&!Gr?J:!0,hydrateStoredLayout:G&&!Gr?ye:()=>{},focusConversationTab:he,setSearchParams:l,historyModalOpen:De,activeConv:Y,isRefreshingHistory:Xu,ides:x,handleRefreshHistory:Ju});const Qu=i.useMemo(()=>!Y||!at(Y)||st(Y)?null:Zs(Y),[Y]),{versionMismatchDaemons:Zu,hasRequiredVersionDaemons:bi,targetVersion:em,versionBannerDismissed:tm,setVersionBannerDismissed:sm,upgradingDaemons:rm,handleBannerUpgrade:nm}=yg({ides:x,sendDaemonCommand:e}),gi=i.useCallback(Ye=>{ce(Ye),se(Ye)},[se,ce]),am=i.useCallback(Ye=>{R(Ye)},[R]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[s.jsx(vx,{terminalBackend:ie,isStandalone:me,machineLabel:pe,machineKey:le}),(!tm||bi)&&s.jsx(pv,{daemons:Zu,targetVersion:em,required:bi,upgradingDaemons:rm,onUpgrade:nm,onDismiss:()=>sm(!0)}),s.jsx(ov,{showMobileChatMode:Gr,isMobile:G,activeConv:Y,wsStatus:T,isConnected:I,onOpenHistory:Ye=>{Ye&&et(Ye),L()},onOpenRemote:bt,onStopCli:Ue,activeCliViewMode:Qu,onSetActiveCliViewMode:Yu,mobileChatConversations:Ou,ides:x,actionLogs:ve,sendDaemonCommand:e,setActionLogs:X,setCliViewModeOverrides:fe,isStandalone:me,initialDataLoaded:S,userName:h.userName,requestedMobileTabKey:Ae,onRequestedMobileTabConsumed:$e,requestedMachineId:m,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:u,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:Ve,isSplitMode:ot,numGroups:Ge,groupSizes:P,groupedConvs:U,clearedTabs:we,focusedGroup:D,focusGroup:j,moveTabToGroup:V,splitTabRelative:K,closeGroup:Z,handleResizeStart:ae,groupActiveTabIds:W,setGroupActiveTab:$,groupTabOrders:C,setGroupTabOrder:F,toggleHiddenTab:Ye=>q(ze.get(Ye)||{tabKey:Ye}),visibleConversations:O,hiddenConversations:Fu,requestedDesktopTabKey:Ee,onRequestedDesktopTabConsumed:$e,onDesktopActiveTabChange:Pe,onRequestScrollToBottom:oe,onHideConversation:am,onShowHiddenConversation:gi,onShowAllHiddenConversations:Ne,scrollToBottomRequest:ke,machineEntries:Ce,layoutProfile:_,onBrowseMachineDirectory:Ku,onSaveMachineWorkspace:Hu,onLaunchMachineIde:Uu,onLaunchMachineProvider:zu,onListMachineMeshes:Vu,onLaunchMeshCoordinator:Gu,onListMachineSavedSessions:qu,notifications:rt,notificationUnreadCount:pt,liveSessionInboxState:Je,onMarkNotificationRead:xt,onMarkNotificationUnread:vt,onDeleteNotification:Te}),s.jsx("style",{children:`
|
|
69
|
+
`})]})}function mv({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 l=r===o.tabKey,c=o.status==="waiting_approval",d=o.status==="generating";return s.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${l?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a(o.tabKey),children:[s.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:c?"var(--status-warning)":d?"var(--accent-primary)":"var(--text-muted)",boxShadow:d?"0 0 6px var(--accent-primary)":"none"}}),o.title,c&&s.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},o.tabKey)})]}):null}function pv({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,l]=i.useState(()=>a||"native"),c=i.useMemo(()=>bd(t),[t]),d=i.useMemo(()=>e?ti(e,{machineNames:c,connectionStates:r,defaultConnectionState:"new"}):[],[e,c,r]),m=i.useMemo(()=>d.find(p=>p.streamSource==="native"),[d]),u=i.useMemo(()=>d.filter(p=>p.streamSource==="agent-stream"),[d]),h=i.useMemo(()=>e?Wt(d,e.id):null,[d,e]);i.useEffect(()=>{a&&l(a)},[a]),i.useEffect(()=>{if(a||!h)return;const p=h.streamSource==="native"?"native":h.tabKey;!p||o===p||o==="native"&&l(p)},[o,h,a]),i.useEffect(()=>{var p;o!=="native"&&(u.some(g=>g.tabKey===o)||l(((p=u[0])==null?void 0:p.tabKey)||"native"))},[o,u]),i.useEffect(()=>{o==="native"&&(m||u[0]&&l(u[0].tabKey))},[o,m,u]);const x=i.useMemo(()=>o==="native"&&m?m:u.find(p=>p.tabKey===o)||h||m||u[0],[o,m,h,u]),S=i.useMemo(()=>u.map(p=>({tabKey:p.tabKey,title:dd(p)||n,status:p.status})),[u,n]),b=i.useCallback(p=>{if(p)return d.find(g=>uo(g,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[d]);return{activeChatTab:o,setActiveChatTab:l,activeConv:x,conversations:d,extensionTabs:S,hasExtensions:S.length>0,resolveConversationByTarget:b}}function hv({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:l,isStandalone:c,userName:d,onOpenHistory:m,onConversationChange:u,onClose:h}){const[x,S]=i.useState("split"),[b,p]=i.useState(()=>ls(e)?"native":e.tabKey),g=i.useRef(null),v=i.useMemo(()=>t||r.find(y=>y.id===e.routeId),[e.routeId,t,r]),f=i.useMemo(()=>ct((v==null?void 0:v.type)||""),[v==null?void 0:v.type]),{conversations:C,extensionTabs:T,hasExtensions:k}=pv({ideData:v,allIdes:r,connectionStates:n,ideName:f||"IDE",preferredTabKey:ls(e)?void 0:e.tabKey}),A=i.useMemo(()=>v?Wt(C,v.id):null,[v,C]);i.useEffect(()=>{const y=g.current,F={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(g.current=F,!(y&&y.routeId===F.routeId&&y.tabKey===F.tabKey&&y.streamSource===F.streamSource)){if(ls(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),i.useEffect(()=>{if(b==="native"){if(C.some(y=>y.streamSource==="native"))return;(A==null?void 0:A.streamSource)==="agent-stream"&&p(A.tabKey);return}if(!C.some(y=>y.tabKey===b)){if((A==null?void 0:A.streamSource)==="agent-stream"){p(A.tabKey);return}p("native")}},[C,b,A]);const _=i.useMemo(()=>b==="native"?C.find(y=>y.streamSource==="native")||e:C.find(y=>y.tabKey===b)||e,[e,C,b]),N=Ad(_),w=i.useMemo(()=>N.status||N.modalMessage||N.modalButtons?{..._,...N.status?{status:N.status}:{},...N.modalMessage!==void 0?{modalMessage:N.modalMessage}:{},...N.modalButtons!==void 0?{modalButtons:N.modalButtons}:{}}:_,[_,N]),D=Dr(w),M=qn({sendDaemonCommand:o,activeConv:w,setActionLogs:l,isStandalone:c}),{connScreenshot:j,screenshotUsage:W,handleRemoteAction:H}=ou({doId:D,targetSessionId:Gc(w),connState:w.connectionState||"new",viewMode:x}),$=i.useMemo(()=>a.filter(y=>y.routeId===w.tabKey),[a,w.tabKey]);i.useEffect(()=>{u==null||u(w)},[w,u]),i.useEffect(()=>{const y=F=>{F.key==="Escape"&&h()};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[h]);const I=i.useCallback(y=>{y.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:h,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:I,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(_t,{size:16})}),s.jsx("span",{className:"truncate",children:Ho(_)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:h,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(y=>{const F=x===y;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${F?"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:()=>S(y),title:y==="split"?"Split view":"Remote only",children:y==="split"?s.jsx(rp,{size:15}):s.jsx(_t,{size:15})},y)})}),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(_),title:"Chat History",children:[s.jsx(_o,{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:h,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${x==="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:[x!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${x==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(mv,{hasExtensions:k,ideName:f||"IDE",activeChatTab:b,extensionTabs:T,onSelectTab:p}),s.jsx(Rc,{activeConv:w,onModalButton:M.handleModalButton}),s.jsx(po,{activeConv:w,ideEntry:v,showMetaChips:!1,handleSendChat:M.handleSendChat,isSendingChat:M.isSendingChat,sendFeedbackMessage:M.sendFeedbackMessage,handleFocusAgent:M.handleFocusAgent,isFocusingAgent:M.isFocusingAgent,actionLogs:$,userName:d})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${x==="split"?"order-1 md:order-2":""}`,children:s.jsx(_c,{addLog:()=>{},connState:w.connectionState||"new",connScreenshot:j,screenshotUsage:W,transportType:w.transport,onAction:H})})]})]})})}function fv({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=fx(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 xv({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o}){var l;return s.jsxs(s.Fragment,{children:[s.jsx(vx,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(ei,{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(hv,{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&&(at(r.targetConv)||st(r.targetConv))&&s.jsx(fv,{activeConv:r.targetConv,canSaveAndStop:at(r.targetConv)&&!st(r.targetConv)&&!!((l=r.targetConv.resume)!=null&&l.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(xd,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),o.open&&s.jsx(uv,{onClose:o.onClose})]})}function bv({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(Rr,{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(l=>{const c=At(l,{fallbackId:l.id}),d=n[l.id],m=l.version||l.daemonVersion||"unknown",u=l.versionUpdateRequired===!0,x=Ud(l)==="preview"?"Update to preview":u?"Update now":"Upgrade";return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[s.jsx("span",{className:"font-medium text-text-primary",children:c}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",m]}),u&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),d==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:u?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):d==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):d==="error"?s.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(l.id),children:"retry"}):s.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:u?"var(--status-danger)":"var(--status-warning)",background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(l.id),children:x})]},l.id)})]}),!r&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:o,title:"Dismiss",children:s.jsx(wt,{size:16})})]})}function gv(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function yv(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 vv(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>yv(t)).map(t=>t.id)}}function wv(){var yi,vi,wi,ji;const{sendCommand:e}=jt(),t=Er(),r=Md(),n=To(),a=As(),[o,l]=km(),c=o.get("activeTab"),d=((yi=n.state)==null?void 0:yi.openRemoteForTabKey)||null,m=((vi=n.state)==null?void 0:vi.openMachineId)||null,u=((wi=n.state)==null?void 0:wi.mobileSection)||null,h=od(),x=h.ides||[],S=h.initialLoaded??!0,{updateRouteChats:b,setToasts:p}=h,[g,v]=i.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),f=h.toasts||[],C=h.wsStatus||"connected",T=h.isConnected??!0,k=h.connectionStates||{},A=h.showReconnected||!1,{layoutProfile:_,groupAssignments:N,updateGroupAssignments:w,focusedGroup:D,updateFocusedGroup:M,focusGroup:j,groupActiveTabIds:W,updateGroupActiveTabIds:H,setGroupActiveTab:$,groupTabOrders:I,updateGroupTabOrders:y,setGroupTabOrder:F,groupSizes:P,updateGroupSizes:E,isMobile:G,hasHydratedStoredLayout:J,hydrateStoredLayout:ye,focusConversationTab:he}=ug(),[ne,ue]=i.useState(()=>ni());i.useEffect(()=>kb(ue),[]);const Se=i.useMemo(()=>gv({isMobile:G,mobileViewMode:ne}),[G,ne]),[ve,X]=i.useState([]),[xe,fe]=i.useState({}),[we,be]=i.useState({});Pr("Dashboard",{ideCount:x.length,toastCount:f.length,focusedGroup:D,groupCount:Object.keys(N).length,actionLogCount:ve.length});const Ce=i.useMemo(()=>x.filter(Ye=>Ye.type==="adhdev-daemon").sort(Fo),[x]),ee=Ce[0],me=!!ee;i.useEffect(()=>{const{metadataDaemonIds:Ye,runtimeDaemonIds:Et}=vv(Ce);for(const sr of Ye)t(sr,{minFreshMs:3e4}).catch(()=>{});for(const sr of Et)r(sr,{minFreshMs:3e4}).catch(()=>{})},[t,r,Ce]);const ie=(ee==null?void 0:ee.terminalBackend)||null,pe=ee?At(ee,{fallbackId:ee.id}):null,le=(ee==null?void 0:ee.id)||null,B=i.useMemo(()=>$b(x,xe),[x,xe]),{hiddenTabs:z,autoHiddenTabs:de,autoHideTarget:re,hideTarget:R,toggleTarget:q,showTarget:ce,showAllTabs:Ne}=Eb(),{conversations:je,visibleConversations:O,visibleTabKeys:Ie,resolveConversationBySessionId:Le,resolveConversationByTarget:He}=Xb({ides:B,connectionStates:k,clearedTabs:we,hiddenTabs:z}),ze=i.useMemo(()=>new Map(je.map(Ye=>[Ye.tabKey,Ye])),[je]),Xe=i.useMemo(()=>Db(je,z,de),[je,z,de]);i.useEffect(()=>{for(const Ye of Xe)re(Ye)},[Xe,re]),Vf(O,Se),i.useEffect(()=>{Object.keys(xe).length!==0&&fe(Ye=>Bb(Ye,x))},[x,xe]);const Je=i.useMemo(()=>Zp(x),[x]),{notifications:rt,unreadCount:pt}=Ig({conversations:je,liveSessionInboxState:Je}),{handleMarkDashboardNotificationRead:xt,handleMarkDashboardNotificationUnread:vt,handleDeleteDashboardNotification:Te}=Tg({notifications:rt,sendDaemonCommand:e}),{containerRef:Ve,normalizedGroupAssignments:tt,numGroups:Ge,isSplitMode:ot,groupedConvs:U,moveTabToGroup:V,closeGroup:Z,handleResizeStart:ae,splitTabRelative:K}=gg({groupAssignments:N,updateGroupAssignments:w,updateFocusedGroup:M,updateGroupActiveTabIds:H,updateGroupTabOrders:y,groupSizes:P,updateGroupSizes:E,isMobile:G,visibleConversations:O,visibleTabKeys:Ie}),{activeConv:Y,openDesktopConversation:se,requestScrollToBottom:oe,scrollToBottomRequest:ke,setDesktopActiveTab:Pe}=Kg({isMobile:G,conversations:je,visibleConversations:O,groupActiveTabIds:W,focusedGroup:D,groupedConvs:U,setSearchParams:l});zg({activeConv:Y,isMobile:G,liveSessionInboxState:Je,sendDaemonCommand:e});const{requestedDesktopTabKey:Ee,requestedMobileTabKey:Ae,consumeRequestedActiveTab:$e}=Jb({isMobile:G,urlActiveTab:c,resolveConversationBySessionId:Le,setSearchParams:l}),{remoteDialogConv:Fe,remoteDialogIdeEntry:Me,remoteDialogActiveConv:Qe,setRemoteDialogActiveConv:et,openRemoteDialog:bt,closeRemoteDialog:gt,cliStopDialogOpen:dt,cliStopTargetConv:ht,requestCliStop:Ue,cancelCliStop:Kt,confirmCliStop:te}=qg({isMobile:G,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:Ee,conversations:je,ides:x,resolveConversationByTarget:He,activeConv:Y,sendDaemonCommand:e}),{historyModalOpen:De,openHistoryModal:L,closeHistoryModal:Q,historyTargetConv:ge,isSavedSessionHistoryTarget:Be,isHistoryCreatingChat:_e,isHistoryRefreshingHistory:Oe,handleHistorySwitchSession:nt,handleHistoryNewChat:Mt,handleHistoryRefresh:ft,savedHistorySessions:ss,savedHistoryFilters:Fr,setSavedHistoryFilters:Wr,missingWorkspaceResumePath:Kr,isSavedHistoryLoading:Hr,resumingSavedHistorySessionId:Ur,handleRefreshSavedHistory:zr,handleResumeSavedHistorySession:Vr}=Vg({activeConv:Y,remoteDialogConv:Fe,remoteDialogActiveConv:Qe,ides:x,sendDaemonCommand:e,updateRouteChats:b,setToasts:p,setClearedTabs:be,setSearchParams:l}),Fu=i.useMemo(()=>O,[O]),Gr=G&&ne==="chat",Wu=i.useMemo(()=>je.filter(Ye=>Xn(z,Ye)),[je,z]),xi=i.useCallback(Ye=>{const Et=new URLSearchParams(o);Et.set("activeTab",Ye),l(Et,{replace:!0})},[o,l]),{trackPendingLaunch:Ku}=Bg({ides:x,conversations:je,onOpenSession:xi}),{handleBrowseMachineDirectory:Hu,handleSaveMachineWorkspace:Uu,handleLaunchMachineIde:zu,handleLaunchMachineProvider:Vu,handleListMachineMeshes:Gu,handleLaunchMeshCoordinator:qu,handleListMachineSavedSessions:Yu,setActiveCliViewMode:Xu}=Og({sendDaemonCommand:e,trackPendingLaunch:Ku,onOpenSession:xi,activeConv:Y,ides:x,setCliViewModeOverrides:fe});Ob({visibleConversations:O,clearedTabs:we,setClearedTabs:be,setActionLogs:X}),Qb({ides:x,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:He});const{isRefreshingHistory:Ju,handleRefreshHistory:Qu}=Hd({sendDaemonCommand:e,activeConv:Y,chats:(ji=x.find(Ye=>Ye.id===(Y==null?void 0:Y.routeId)))==null?void 0:ji.chats,updateRouteChats:b,setToasts:p,setClearedTabs:be});pg({urlActiveTab:G&&!Gr?c:null,conversations:je,resolveConversationBySessionId:Le,normalizedGroupAssignments:tt,hasHydratedStoredLayout:G&&!Gr?J:!0,hydrateStoredLayout:G&&!Gr?ye:()=>{},focusConversationTab:he,setSearchParams:l,historyModalOpen:De,activeConv:Y,isRefreshingHistory:Ju,ides:x,handleRefreshHistory:Qu});const Zu=i.useMemo(()=>!Y||!at(Y)||st(Y)?null:Zs(Y),[Y]),{versionMismatchDaemons:em,hasRequiredVersionDaemons:bi,targetVersion:tm,versionBannerDismissed:sm,setVersionBannerDismissed:rm,upgradingDaemons:nm,handleBannerUpgrade:am}=vg({ides:x,sendDaemonCommand:e}),gi=i.useCallback(Ye=>{ce(Ye),se(Ye)},[se,ce]),om=i.useCallback(Ye=>{R(Ye)},[R]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[s.jsx(wx,{terminalBackend:ie,isStandalone:me,machineLabel:pe,machineKey:le}),(!sm||bi)&&s.jsx(bv,{daemons:em,targetVersion:tm,required:bi,upgradingDaemons:nm,onUpgrade:am,onDismiss:()=>rm(!0)}),s.jsx(dv,{showMobileChatMode:Gr,isMobile:G,activeConv:Y,wsStatus:C,isConnected:T,onOpenHistory:Ye=>{Ye&&et(Ye),L()},onOpenRemote:bt,onStopCli:Ue,activeCliViewMode:Zu,onSetActiveCliViewMode:Xu,mobileChatConversations:Fu,ides:x,actionLogs:ve,sendDaemonCommand:e,setActionLogs:X,setCliViewModeOverrides:fe,isStandalone:me,initialDataLoaded:S,userName:h.userName,requestedMobileTabKey:Ae,onRequestedMobileTabConsumed:$e,requestedMachineId:m,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:u,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:Ve,isSplitMode:ot,numGroups:Ge,groupSizes:P,groupedConvs:U,clearedTabs:we,focusedGroup:D,focusGroup:j,moveTabToGroup:V,splitTabRelative:K,closeGroup:Z,handleResizeStart:ae,groupActiveTabIds:W,setGroupActiveTab:$,groupTabOrders:I,setGroupTabOrder:F,toggleHiddenTab:Ye=>q(ze.get(Ye)||{tabKey:Ye}),visibleConversations:O,hiddenConversations:Wu,requestedDesktopTabKey:Ee,onRequestedDesktopTabConsumed:$e,onDesktopActiveTabChange:Pe,onRequestScrollToBottom:oe,onHideConversation:om,onShowHiddenConversation:gi,onShowAllHiddenConversations:Ne,scrollToBottomRequest:ke,machineEntries:Ce,layoutProfile:_,onBrowseMachineDirectory:Hu,onSaveMachineWorkspace:Uu,onLaunchMachineIde:zu,onLaunchMachineProvider:Vu,onListMachineMeshes:Gu,onLaunchMeshCoordinator:qu,onListMachineSavedSessions:Yu,notifications:rt,notificationUnreadCount:pt,liveSessionInboxState:Je,onMarkNotificationRead:xt,onMarkNotificationUnread:vt,onDeleteNotification:Te}),s.jsx("style",{children:`
|
|
70
70
|
body { overflow: hidden; overscroll-behavior: none; }
|
|
71
|
-
`}),s.jsx(
|
|
71
|
+
`}),s.jsx(xv,{historyModal:{open:De,targetConv:ge,ides:x,isCreatingChat:_e,isRefreshingHistory:Be?!1:Oe,savedSessions:ss,savedHistoryFilters:Fr,missingWorkspaceResumePath:Kr||null,onSavedHistoryFiltersChange:Wr,isSavedSessionsLoading:Hr,isResumingSavedSessionId:Ur,onClose:Q,onNewChat:Mt,onSwitchSession:nt,onRefreshHistory:Be?zr:ft,onResumeSavedSession:Vr},remoteDialog:{conversation:Fe,ideEntry:Me,ides:x,connectionStates:k,actionLogs:ve,sendDaemonCommand:e,setActionLogs:X,isStandalone:me,userName:h.userName,onOpenHistory:Ye=>{Ye&&et(Ye),L()},onConversationChange:et,onClose:gt},cliStopDialog:{open:dt,targetConv:ht,onCancel:Kt,onStopNow:async()=>{await te("hard")},onSaveAndStop:async()=>{await te("save")}},connectionBanner:{wsStatus:C,showReconnected:A,loginUrl:h.connectionLoginUrl,onReconnect:h.retryServerConnection},toastOverlay:{toasts:f,onDismiss:Ye=>p(Et=>Et.filter(sr=>sr.id!==Ye)),onClick:Ye=>{if(Ye.targetKey){const Et=He(Ye.targetKey);Et&&(he(Et.tabKey,tt),gi(Et),oe(Et.tabKey,"toast-open"))}}},onboarding:{open:g,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}v(!1)}}})]})}function jv({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[o,l]=i.useState([]),[c,d]=i.useState(null),[m,u]=i.useState(null),[h,x]=i.useState(!1),[S,b]=i.useState(null),[p,g]=i.useState(!1),[v,f]=i.useState(""),C=i.useRef(null),T=i.useCallback(P=>{C.current=P},[]),k=i.useCallback((P,E,G=!1)=>{l(J=>[...J.slice(-100),{timestamp:Date.now(),level:P,message:E}]),setTimeout(()=>{var J;return(J=a.current)==null?void 0:J.scrollIntoView({behavior:"smooth"})},100),G&&it.showToast(E,P==="error"||P==="warn"?"warning":"success")},[a]),A=i.useCallback(P=>{const E=P instanceof Error?P.message:String(P||"");return E.includes("P2P command timeout")||E.includes("P2P not connected")||E.includes("P2P not available")},[]),_=i.useCallback(async(P,E)=>{var G;if(!e||c)return!1;d(P),k("info",`Launching ${ct(P)}${E!=null&&E.workspace?` in ${E.workspace}`:""}...`);try{const J={ideType:P,enableCdp:!0};(G=E==null?void 0:E.workspace)!=null&&G.trim()?J.workspace=E.workspace.trim():E!=null&&E.useDefaultWorkspace&&(J.useDefaultWorkspace=!0);const ye=await r(e,"launch_ide",J);return k(ye!=null&&ye.success?"info":"error",ye!=null&&ye.success?`${ct(P)} launched`:`Failed: ${ye==null?void 0:ye.error}`,!0),!!(ye!=null&&ye.success)}catch(J){return k("error",`Launch error: ${J.message}`,!0),!1}finally{d(null)}},[e,c,k,r]),N=i.useCallback(async P=>{if(!e)return{success:!1};const{cliType:E,dir:G,workspaceId:J,useDefaultWorkspace:ye,useHome:he,argsStr:ne,model:ue,resumeSessionId:Se}=P;if(!E)return k("warn","Select a CLI or ACP provider first",!0),{success:!1};const ve=ne?ne.split(/\s+/).filter(Boolean):void 0,X=(G==null?void 0:G.trim())||(J?"(saved id)":ye?"(default workspace)":he?"(home)":"");k("info",`Launching ${E}${X?` in ${X}`:""}${ue?` (model: ${ue})`:""}...`),u(E);try{const xe={cliType:E,cliArgs:ve,initialModel:ue||void 0};G!=null&&G.trim()?xe.dir=G.trim():J?xe.workspaceId=J:ye?xe.useDefaultWorkspace=!0:he&&(xe.useHome=!0),Se&&(xe.resumeSessionId=Se);const fe=await r(e,"launch_cli",xe),we=(fe==null?void 0:fe.result)||fe;return fe!=null&&fe.success?(k("info",`${E} launched`,!0),(we==null?void 0:we.launchSource)==="home"?k("info","📂 Running in home directory (explicit choice)"):(we==null?void 0:we.launchSource)==="defaultWorkspace"&&k("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:we==null?void 0:we.sessionId}):(k("error",`Failed: ${(fe==null?void 0:fe.error)||(we==null?void 0:we.error)}`,!0),(fe==null?void 0:fe.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&b({cliType:E,argsStr:ne,model:ue}),{success:!1,sessionId:we==null?void 0:we.sessionId})}catch(xe){return A(xe)?(k("warn",`${E} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(k("error",`Launch error: ${xe.message}`,!0),{success:!1})}finally{u(null)}},[e,k,A,r]),w=i.useCallback(async(P,E,G,J)=>e?P?E.trim()?N({cliType:P,dir:E,argsStr:G,model:J}):(b({cliType:P,argsStr:G,model:J}),{success:!1}):(k("warn","Select a provider",!0),{success:!1}):{success:!1},[e,k,N]),D=i.useCallback(async(P,E,G)=>{if(e&&window.confirm(`Stop ${P}?
|
|
72
72
|
This will terminate the process.`))try{const J=await r(e,"stop_cli",{cliType:P,dir:E,targetSessionId:G});J!=null&&J.success?k("info",`${P} stopped`,!0):k("error",`Stop failed: ${(J==null?void 0:J.error)||"Unknown error"}`,!0)}catch(J){k("error",`Stop failed: ${J.message}`,!0)}},[e,k,r]),M=i.useCallback(async P=>{try{await r(P.daemonId,"restart_ide",{ideType:P.type}),k("info",`${ct(P.type)} restart initiated`,!0)}catch(E){k("error",`Restart failed: ${E.message}`,!0)}},[k,r]),j=i.useCallback(async P=>{if(window.confirm(`Stop ${ct(P.type)}?
|
|
73
|
-
This will disconnect CDP and optionally kill the process.`))try{const E=await r(P.daemonId,"stop_ide",{ideType:P.type,killProcess:!0});E!=null&&E.success?k("info",`${ct(P.type)} stopped`,!0):k("error",`Stop failed: ${(E==null?void 0:E.error)||"Unknown error"}`,!0)}catch(E){k("error",`Stop failed: ${E.message}`,!0)}},[k,r]),W=i.useCallback(async()=>{if(e)try{const P=await r(e,"detect_ides",{});k("info",`Found ${((P==null?void 0:P.result)||[]).length} IDE(s)`,!0)}catch(P){k("error",`Detection failed: ${P.message}`,!0)}},[e,k,r]),H=i.useCallback(async P=>{if(!e||!P.trim())return!1;x(!0);try{const E=await r(e,"workspace_add",{path:P.trim()});return E!=null&&E.success?(k("info",`Workspace added: ${P.trim()}`),!0):(k("error",(E==null?void 0:E.error)||"workspace_add failed"),!1)}catch(E){return k("error",E.message),!1}finally{x(!1)}},[e,k,r]),$=i.useCallback(async P=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){x(!0);try{const E=await r(e,"workspace_remove",{id:P});E!=null&&E.success?k("info","Workspace removed",!0):k("error",(E==null?void 0:E.error)||"workspace_remove failed",!0)}catch(E){k("error",E.message,!0)}finally{x(!1)}}},[e,k,r]),
|
|
73
|
+
This will disconnect CDP and optionally kill the process.`))try{const E=await r(P.daemonId,"stop_ide",{ideType:P.type,killProcess:!0});E!=null&&E.success?k("info",`${ct(P.type)} stopped`,!0):k("error",`Stop failed: ${(E==null?void 0:E.error)||"Unknown error"}`,!0)}catch(E){k("error",`Stop failed: ${E.message}`,!0)}},[k,r]),W=i.useCallback(async()=>{if(e)try{const P=await r(e,"detect_ides",{});k("info",`Found ${((P==null?void 0:P.result)||[]).length} IDE(s)`,!0)}catch(P){k("error",`Detection failed: ${P.message}`,!0)}},[e,k,r]),H=i.useCallback(async P=>{if(!e||!P.trim())return!1;x(!0);try{const E=await r(e,"workspace_add",{path:P.trim()});return E!=null&&E.success?(k("info",`Workspace added: ${P.trim()}`),!0):(k("error",(E==null?void 0:E.error)||"workspace_add failed"),!1)}catch(E){return k("error",E.message),!1}finally{x(!1)}},[e,k,r]),$=i.useCallback(async P=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){x(!0);try{const E=await r(e,"workspace_remove",{id:P});E!=null&&E.success?k("info","Workspace removed",!0):k("error",(E==null?void 0:E.error)||"workspace_remove failed",!0)}catch(E){k("error",E.message,!0)}finally{x(!1)}}},[e,k,r]),I=i.useCallback(async P=>{var E;if(e){x(!0);try{const G=await r(e,"workspace_set_default",P===null?{clear:!0}:{id:P});if(G!=null&&G.success){k("info",P?"Default workspace updated":"Default workspace cleared",!0);const J=typeof G.defaultWorkspacePath=="string"?G.defaultWorkspacePath:"";J&&((E=C.current)==null||E.call(C,J))}else k("error",(G==null?void 0:G.error)||"workspace_set_default failed",!0)}catch(G){k("error",G.message,!0)}finally{x(!1)}}},[e,k,r]),y=i.useCallback(async P=>{var G;if(!e||!P.trim())return;const E=P.trim();x(!0);try{const J=await r(e,"workspace_set_default",{path:E});J!=null&&J.success?(k("info","Default workspace set from history"),(G=C.current)==null||G.call(C,E)):k("error",(J==null?void 0:J.error)||"Could not set default (path missing on disk?)")}catch(J){k("error",J.message)}finally{x(!1)}},[e,k,r]),F=i.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:v}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:v})}catch(P){k("warn",`Live nickname updated, but account sync failed: ${P.message}`)}k("info",`Nickname set to "${v||"(cleared)"}"`),g(!1)}catch(P){k("error",`Failed: ${P.message}`)}},[e,v,t,k,n,r]);return{logs:o,launchingIde:c,launchingAgentType:m,workspaceBusy:h,launchPick:S,setLaunchPick:b,editingNickname:p,setEditingNickname:g,nicknameInput:v,setNicknameInput:f,addLog:k,handleLaunchIde:_,runLaunchCliCore:N,handleLaunchCli:w,handleStopCli:D,handleRestartIde:M,handleStopIde:j,handleDetectIdes:W,handleWorkspaceAdd:H,handleWorkspaceRemove:$,handleWorkspaceSetDefault:I,handleWorkspaceResumePath:y,handleSaveNickname:F,setOnDefaultWorkspaceChanged:T}}function kv({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:l}){var M;const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:m,handleWorkspaceSetDefault:u}=o,[h,x]=i.useState(!1),[S,b]=i.useState(""),[p,g]=i.useState([]),[v,f]=i.useState(!1),[C,T]=i.useState(""),k=i.useCallback(async j=>{f(!0),T("");try{const W=await Zn(l,e,j);b(W.path),g(W.directories)}catch(W){T(W instanceof Error?W.message:"Could not load folder")}finally{f(!1)}},[e,l]),A=i.useCallback(()=>{x(!0);const j=[...r.map(H=>H.workspace),...n.map(H=>H.workspace),...a.map(H=>H.workspace)],W=Qn(t.platform,Jn(j,t.defaultWorkspacePath,(t.workspaces||[]).map(H=>H.path)));k(W)},[a,n,r,k,t.defaultWorkspacePath,t.platform,t.workspaces]),_=typeof t.uptime=="number"||typeof t.freeMem=="number"||typeof t.availableMem=="number"||Array.isArray(t.loadavg)&&t.loadavg.length>0,N=t.availableMem??t.freeMem??t.totalMem,w=_&&t.totalMem>0?Math.min(100,Math.max(0,Math.round((t.totalMem-N)/t.totalMem*100))):0,D=((M=t.loadavg)==null?void 0:M[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(Yr,{icon:s.jsx(jc,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?ah(t.uptime):"Waiting…"}),s.jsx(Yr,{icon:s.jsx(_t,{size:16}),label:"IDEs",value:`${r.length}`}),s.jsx(Yr,{icon:s.jsx(Ro,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(Yr,{icon:s.jsx(ap,{size:16}),label:"ACPs",value:`${a.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(Bi,{value:_?Math.min(Math.round(D/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:_?`${D.toFixed(2)} avg / ${t.cpus} cores`:"Polled from machine page"}),s.jsx(Bi,{value:w,max:100,label:"Memory",color:"#3b82f6",detail:_?`${da(t.totalMem-N)} / ${da(t.totalMem)}${t.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${da(t.totalMem)} total`})]})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-3",children:[s.jsx(Ns,{size:14})," Workspaces"]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[s.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),s.jsxs("select",{className:"text-xs bg-bg-primary border border-border-subtle rounded-lg px-2 py-1 max-w-[min(100%,420px)]",disabled:c,value:t.defaultWorkspaceId||"",onChange:j=>void u(j.target.value===""?null:j.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),(t.workspaces||[]).map(j=>s.jsx("option",{value:j.id,children:j.label||j.path},j.id))]}),t.defaultWorkspacePath&&s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:t.defaultWorkspacePath,children:t.defaultWorkspacePath})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded transition-colors text-xs",disabled:c,onClick:A,children:"Select workspace…"}),s.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(t.workspaces||[]).length>0&&s.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(t.workspaces||[]).map(j=>s.jsxs("li",{className:"flex items-start gap-2 text-[11px] text-text-muted rounded-lg border border-border-subtle bg-bg-primary px-2.5 py-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[j.id===t.defaultWorkspaceId&&s.jsx("span",{className:"text-[10px]",children:"⭐"}),s.jsx("span",{className:"font-medium text-text-primary truncate",children:Vn(j.path,j.label)})]}),s.jsx("div",{className:"font-mono truncate text-[10px]",title:j.path,children:j.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void m(j.id),children:"Remove"})]},j.id))})]}),h&&s.jsx(ea,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:S,directories:p,busy:v,error:C,confirmLabel:"Add workspace",onClose:()=>x(!1),onNavigate:j=>{k(j)},onConfirm:j=>{(async()=>{if(!j)return;await d(j)&&x(!1)})()}})]})}function Sv(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 Nv(e,t,r){const n=[];for(const[a,o]of Object.entries(e.settings)){const l=r!=null&&r.filterSchema?r.filterSchema(o):o;if(l.length===0)continue;const c=t.find(d=>d.type===a);n.push({type:a,displayName:(c==null?void 0:c.displayName)||a,icon:(c==null?void 0:c.icon)||"",category:(c==null?void 0:c.category)||"unknown",schema:l,values:e.values[a]||{}})}return n}function Ha(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 Yl(e){if(!e||typeof e!="object")return null;if(Ha(e))return e;const t=e,r=t.result;return Ha(r)?r:Ha(t.sourceConfig)?t.sourceConfig:null}function Cv(e){const t=e.trim();return t||null}const Xl=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Iv=[{value:"codex-cli",label:"Codex CLI",desc:"OpenAI o3/gpt-5.4",color:"#22c55e"},{value:"claude-cli",label:"Claude Code",desc:"Anthropic Claude",color:"#a855f7"},{value:"gemini-cli",label:"Gemini CLI",desc:"Google Gemini",color:"#3b82f6"}];function Tv({machineId:e,provider:t,sendDaemonCommand:r,onClose:n}){const[a,o]=i.useState("config"),[l,c]=i.useState("codex-cli"),[d,m]=i.useState([]),[u,h]=i.useState(""),[x,S]=i.useState([]),[b,p]=i.useState(""),g=i.useRef(null),v=i.useRef(null),f=N=>{m(w=>w.includes(N)?w.filter(D=>D!==N):[...w,N])},C=()=>m([...Xl]),T=()=>m([]);i.useEffect(()=>{var N;(N=g.current)==null||N.scrollIntoView({behavior:"smooth"})},[x]),i.useEffect(()=>()=>{v.current&&clearInterval(v.current)},[]);const k=i.useCallback(()=>{v.current&&clearInterval(v.current),v.current=setInterval(async()=>{try{const N=await r(e,"provider_auto_fix_status",{providerType:t.type});(N==null?void 0:N.running)===!1&&a==="running"&&(o("done"),S(w=>[...w,`
|
|
74
74
|
✅ Auto-fix completed!`]),v.current&&clearInterval(v.current))}catch{}},3e3)},[e,t.type,r,a]),A=async()=>{if(d.length!==0){o("running"),S(["🚀 Starting auto-fix...",`Agent: ${l}`,`Scripts: ${d.join(", ")}`,u?`💬 Comment: ${u}`:"",""]),p("");try{const N=await r(e,"provider_auto_fix",{providerType:t.type,functions:d,agent:l,...u?{comment:u}:{}});N!=null&&N.success&&(N!=null&&N.started||N!=null&&N.running)?(S(w=>[...w,"✅ Agent started. Monitoring progress..."]),k()):(o("error"),p((N==null?void 0:N.error)||"Failed to start auto-fix"))}catch(N){o("error"),p((N==null?void 0:N.message)||"Connection failed")}}},_=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:t.type}),S(N=>[...N,`
|
|
75
|
-
⚠️ Auto-fix cancelled.`]),o("done"),v.current&&clearInterval(v.current)}catch{}};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-[560px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[85vh] overflow-hidden rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:N=>N.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:t.icon||"🔧"}),s.jsxs("div",{children:[s.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",t.displayName]}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),s.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),s.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),s.jsx("div",{className:"flex gap-2",children:kv.map(N=>s.jsxs("button",{onClick:()=>c(N.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:l===N.value?N.color+"66":"var(--border-subtle)",background:l===N.value?N.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:l===N.value?N.color:"var(--text-primary)"},children:N.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:N.desc})]},N.value))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:T,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),s.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),s.jsx("button",{onClick:I,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Yl.map(N=>s.jsxs("button",{onClick:()=>f(N),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:d.includes(N)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:d.includes(N)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:d.includes(N)?"#a78bfa":"var(--text-secondary)"},children:[d.includes(N)?"☑ ":"☐ ",N]},N))})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",s.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),s.jsx("textarea",{value:u,onChange:N=>h(N.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(a==="running"||a==="done"||a==="error")&&s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[x.map((N,w)=>s.jsx("div",{className:N.startsWith("✅")?"text-green-400":"",style:N.startsWith("❌")||N.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:N},w)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:g})]}),b&&s.jsx("div",{className:"mt-2 px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:b})]})]}),s.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[s.jsxs("div",{className:"text-[10px] text-text-muted",children:[a==="config"&&d.length>0&&`${d.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),s.jsxs("div",{className:"flex gap-2",children:[a==="config"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:A,disabled:d.length===0,className:"machine-btn",style:{background:d.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:d.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:d.length>0?"#a78bfa":void 0,opacity:d.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&s.jsx("button",{onClick:_,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(a==="done"||a==="error")&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{o("config"),S([]),p("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Nv({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var k;const o=t.filter(A=>A.category==="ide"),[l,c]=i.useState(((k=o[0])==null?void 0:k.type)||""),[d,m]=i.useState(""),[u,h]=i.useState(""),[x,S]=i.useState(!1),[b,p]=i.useState(""),[g,v]=i.useState(!1),f=A=>{const _=A.toLowerCase().replace(/[^a-z0-9-]/g,"");m(_),(!u||u===T(d))&&h(T(_))},T=A=>A.split("-").map(_=>_.charAt(0).toUpperCase()+_.slice(1)).join(" "),I=async()=>{if(!(!d||!u||!l)){S(!0),p("");try{const A=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:l});A!=null&&A.success||A!=null&&A.created?(v(!0),a==null||a(d)):p((A==null?void 0:A.error)||"Failed to create provider")}catch(A){p((A==null?void 0:A.message)||"Connection failed")}S(!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:A=>A.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:g?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:d})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",d,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",d]})," or use Auto-Fix to implement scripts."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:o.map(A=>s.jsxs("button",{onClick:()=>c(A.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:l===A.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:l===A.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:A.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:l===A.type?"#a78bfa":"var(--text-secondary)"},children:A.displayName})]},A.type))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),s.jsx("input",{value:d,onChange:A=>f(A.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",d||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),s.jsx("input",{value:u,onChange:A=>h(A.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"})]}),b&&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:b})]})}),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:g?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:I,disabled:!d||!u||x,className:"machine-btn",style:{background:d&&u?"rgba(34,197,94,0.12)":void 0,borderColor:d&&u?"rgba(34,197,94,0.3)":void 0,color:d&&u?"#86efac":void 0,opacity:!d||!u||x?.4:1},children:x?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Xl(e){return e==="cli"||e==="acp"}function Cv(e){switch(e){case"detected":return"Detected";case"not_detected":return"Not detected";case"enabled_unchecked":return"Enabled, not checked";case"disabled":return"Disabled";default:return"Disabled"}}function Iv(e){switch(e){case"detected":return"bg-green-500/[0.10] border-green-500/25 text-green-400";case"not_detected":return"bg-red-500/[0.10] border-red-500/25 text-red-400";case"enabled_unchecked":return"bg-yellow-500/[0.10] border-yellow-500/25 text-yellow-400";case"disabled":default:return"bg-white/[0.04] border-white/[0.10] text-text-muted"}}function Jl(e){if(!e)return"No result yet";const t=e.stage||"check",r=e.ok?"OK":"Failed",n=e.message||e.path||e.command||"";return n?`${t}: ${r} — ${n}`:`${t}: ${r}`}function Tv({machineId:e,providers:t,sendDaemonCommand:r}){var H;const[n,a]=i.useState([]),[o,l]=i.useState(!1),[c,d]=i.useState(null),[m,u]=i.useState("all"),[h,x]=i.useState(null),[S,b]=i.useState(!1),[p,g]=i.useState(null),[v,f]=i.useState("normal"),[T,I]=i.useState(""),[k,A]=i.useState(!1),_=i.useCallback(async()=>{if(e)try{const $=await r(e,"get_provider_source_config",{}),C=ql($);C&&(g(C),f(C.sourceMode),I(C.explicitProviderDir||""))}catch{}},[e,r]),N=i.useCallback(async()=>{if(e){l(!0);try{const $=await r(e,"get_provider_settings",{}),C=vv($);if(C){const y=wv(C,t,{filterSchema:F=>F.filter(P=>P.key!=="enabled")});y.sort((F,P)=>F.category.localeCompare(P.category)||F.displayName.localeCompare(P.displayName)),a(y)}}catch{}l(!1)}},[e,t,r]);i.useEffect(()=>{n.length===0&&N(),p||_()},[]);const w=async($,C,y)=>{d(`${$}.${C}`),a(F=>F.map(P=>P.type===$?{...P,values:{...P.values,[C]:y}}:P));try{const F=await r(e,"set_provider_setting",{providerType:$,key:C,value:y});F!=null&&F.success||N()}catch{N()}d(null)},D=async($,C)=>{await w($,"enabled",C),await N()},M=async $=>{d(`${$}.detect`);try{await r(e,"detect_provider",{providerType:$})}finally{await N(),d(null)}},j=async $=>{await w($,"executablePath",""),await w($,"executableArgs",""),await N()},W=async()=>{A(!0);try{const $=await r(e,"set_provider_source_config",{providerSourceMode:v,providerDir:jv(T)}),C=ql($);C?(g(C),f(C.sourceMode),I(C.explicitProviderDir||"")):await _(),await N()}catch{await _()}A(!1)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex justify-between items-center mb-4",children:[s.jsxs("div",{className:"flex gap-1 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map($=>s.jsx("button",{onClick:()=>u($),className:`machine-btn text-[10px] px-2 py-0.5 ${m===$?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:$.toUpperCase()},$))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>b(!0),className:"machine-btn text-[10px] bg-green-500/[0.06] border-green-500/20 text-green-400 hover:bg-green-500/[0.12]",children:"✨ Create Provider"}),s.jsx("button",{onClick:N,disabled:o,className:"machine-btn",children:o?"⏳ Loading...":"↻ Refresh"})]})]}),s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-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-[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:"Affects provider resolution, fix/verify flows, and new launches. Running CLI sessions refresh provider scripts/config; process binary changes still apply on next launch."})]}),s.jsx("button",{onClick:_,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),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:$=>f($.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:T,onChange:$=>I($.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void W(),disabled:k,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:k?"Applying…":"Apply + Reload"})]}),s.jsxs("div",{className:"mt-3 grid gap-1 text-[11px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Effective user root:"})," ",(p==null?void 0:p.userDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(p==null?void 0:p.upstreamDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((H=p==null?void 0:p.providerRoots)==null?void 0:H.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter($=>$.category===m).length>1&&(()=>{const $=n.filter(P=>P.category===m),C=new Map;for(const P of $)for(const E of P.schema){if(E.type!=="boolean")continue;const G=C.get(E.key),J=!!(P.values[E.key]??E.default);G?(G.onCount+=J?1:0,G.total+=1):C.set(E.key,{label:E.label||E.key,onCount:J?1:0,total:1})}const y=[...C.entries()].filter(([,P])=>P.total===$.length);if(y.length===0)return null;const F=async(P,E)=>{for(const G of $)await w(G.type,P,E)};return s.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[s.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",m.toUpperCase()," providers (",$.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:y.map(([P,E])=>{const G=E.onCount===E.total,J=E.onCount===0;return s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:"text-text-secondary font-medium",children:E.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",E.onCount,"/",E.total,")"]}),s.jsx("button",{onClick:()=>void F(P,!0),disabled:G,className:`machine-btn text-[9px] px-1.5 py-px ${G?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),s.jsx("button",{onClick:()=>void F(P,!1),disabled:J,className:`machine-btn text-[9px] px-1.5 py-px ${J?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},P)})})]})})(),o&&n.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):s.jsx("div",{className:"flex flex-col gap-2",children:n.filter($=>m==="all"||$.category===m).map($=>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 gap-2 mb-2.5",children:[s.jsx("span",{className:"text-lg",children:$.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:$.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:$.category==="acp"?"rgba(139,92,246,0.08)":$.category==="cli"?"rgba(59,130,246,0.08)":$.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:$.category==="acp"?"#a78bfa":$.category==="cli"?"#60a5fa":$.category==="ide"?"#86efac":"var(--status-warning)"},children:$.category}),Xl($.category)&&(()=>{const C=t.find(P=>P.type===$.type),y=(C==null?void 0:C.enabled)===!0||$.values.enabled===!0,F=(C==null?void 0:C.machineStatus)||(y?"enabled_unchecked":"disabled");return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${Iv(F)}`,children:Cv(F)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void D($.type,!y),disabled:c===`${$.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${y?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:y?"Disable":"Enable"}),s.jsx("button",{onClick:()=>void M($.type),disabled:!y||c===`${$.type}.detect`,title:y?"Run detection for the configured executable":"Enable this provider before detection",className:`machine-btn text-[9px] px-2 py-0.5 text-blue-400 border-blue-500/25 ${y?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),s.jsx("button",{onClick:()=>void j($.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),$.category==="ide"&&s.jsx("button",{onClick:()=>x(t.find(C=>C.type===$.type)||{type:$.type,name:$.displayName,displayName:$.displayName,icon:$.icon,category:$.category}),className:"ml-auto machine-btn text-[9px] px-2 py-0.5 bg-violet-500/[0.06] border-violet-500/20 text-violet-400 hover:bg-violet-500/[0.12]",children:"🔧 Auto-Fix"})]}),Xl($.category)&&(()=>{const C=t.find(y=>y.type===$.type);return s.jsxs("div",{className:"mb-2.5 grid gap-1 rounded-lg border border-white/[0.06] bg-bg-primary/40 px-3 py-2 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Detection:"})," ",Jl(C==null?void 0:C.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",Jl(C==null?void 0:C.lastVerification)]}),s.jsx("div",{className:"text-[9px] text-text-muted",children:"Supported catalog entry only becomes launchable after Enable + Detect succeeds. Custom executable path/args below are machine-local overrides."})]})})(),s.jsx("div",{className:"flex flex-col gap-2",children:$.schema.map(C=>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-xs font-medium text-text-primary",children:[C.label||C.key,c===`${$.type}.${C.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),C.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:C.description})]}),s.jsx("div",{className:"shrink-0",children:C.type==="boolean"?s.jsx("button",{onClick:()=>w($.type,C.key,!($.values[C.key]??C.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:$.values[C.key]??C.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:$.values[C.key]??C.default?21:3}})}):C.type==="number"?s.jsx("input",{type:"number",value:Number($.values[C.key]??C.default??0)||0,min:C.min,max:C.max,onChange:y=>{const F=parseInt(y.target.value)||0;C.min!==void 0&&F<C.min||C.max!==void 0&&F>C.max||w($.type,C.key,F)},className:"machine-input w-20 text-center text-[11px]"}):C.type==="select"&&C.options?s.jsx("select",{value:String($.values[C.key]??C.default??""),onChange:y=>w($.type,C.key,y.target.value),className:"machine-input text-[11px]",children:C.options.map(y=>s.jsx("option",{value:y,children:y},y))}):s.jsx("input",{type:"text",value:String($.values[C.key]??C.default??""),onBlur:y=>w($.type,C.key,y.target.value),className:"machine-input w-[120px] text-[11px]"})})]},C.key))})]},$.type))}),h&&s.jsx(Sv,{machineId:e,provider:h,sendDaemonCommand:r,onClose:()=>x(null)}),S&&s.jsx(Nv,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>b(!1),onCreated:()=>{b(!1),N()}})]})}const Mv=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Av({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function _v(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function Lv(e){return e.trim().toLowerCase()}function sa(e,t){const r=Lv(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function pi(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Js(e,t=220){const r=pi(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function Rv(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 Pv(e,t){return e.filter(r=>sa([r.level,r.message],t))}function Ql(e){return`${e.timestamp}:${e.level}:${e.message}`}function Dv(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const l of e.entries)n.set(Ql(l),l);for(const l of t.entries)n.set(Ql(l),l);const a=Array.from(n.values()).sort((l,c)=>l.timestamp-c.timestamp).slice(-r),o=a.reduce((l,c)=>Math.max(l,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 Ev(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 $v(e,t){return e.split(`
|
|
76
|
-
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>sa([r],t))}function
|
|
75
|
+
⚠️ Auto-fix cancelled.`]),o("done"),v.current&&clearInterval(v.current)}catch{}};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-[560px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[85vh] overflow-hidden rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:N=>N.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:t.icon||"🔧"}),s.jsxs("div",{children:[s.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",t.displayName]}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),s.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),s.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),s.jsx("div",{className:"flex gap-2",children:Iv.map(N=>s.jsxs("button",{onClick:()=>c(N.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:l===N.value?N.color+"66":"var(--border-subtle)",background:l===N.value?N.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:l===N.value?N.color:"var(--text-primary)"},children:N.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:N.desc})]},N.value))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:C,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),s.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),s.jsx("button",{onClick:T,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Xl.map(N=>s.jsxs("button",{onClick:()=>f(N),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:d.includes(N)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:d.includes(N)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:d.includes(N)?"#a78bfa":"var(--text-secondary)"},children:[d.includes(N)?"☑ ":"☐ ",N]},N))})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",s.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),s.jsx("textarea",{value:u,onChange:N=>h(N.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(a==="running"||a==="done"||a==="error")&&s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[x.map((N,w)=>s.jsx("div",{className:N.startsWith("✅")?"text-green-400":"",style:N.startsWith("❌")||N.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:N},w)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:g})]}),b&&s.jsx("div",{className:"mt-2 px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:b})]})]}),s.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[s.jsxs("div",{className:"text-[10px] text-text-muted",children:[a==="config"&&d.length>0&&`${d.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),s.jsxs("div",{className:"flex gap-2",children:[a==="config"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:A,disabled:d.length===0,className:"machine-btn",style:{background:d.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:d.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:d.length>0?"#a78bfa":void 0,opacity:d.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&s.jsx("button",{onClick:_,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(a==="done"||a==="error")&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{o("config"),S([]),p("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Mv({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var k;const o=t.filter(A=>A.category==="ide"),[l,c]=i.useState(((k=o[0])==null?void 0:k.type)||""),[d,m]=i.useState(""),[u,h]=i.useState(""),[x,S]=i.useState(!1),[b,p]=i.useState(""),[g,v]=i.useState(!1),f=A=>{const _=A.toLowerCase().replace(/[^a-z0-9-]/g,"");m(_),(!u||u===C(d))&&h(C(_))},C=A=>A.split("-").map(_=>_.charAt(0).toUpperCase()+_.slice(1)).join(" "),T=async()=>{if(!(!d||!u||!l)){S(!0),p("");try{const A=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:l});A!=null&&A.success||A!=null&&A.created?(v(!0),a==null||a(d)):p((A==null?void 0:A.error)||"Failed to create provider")}catch(A){p((A==null?void 0:A.message)||"Connection failed")}S(!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:A=>A.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:g?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:d})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",d,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",d]})," or use Auto-Fix to implement scripts."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:o.map(A=>s.jsxs("button",{onClick:()=>c(A.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:l===A.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:l===A.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:A.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:l===A.type?"#a78bfa":"var(--text-secondary)"},children:A.displayName})]},A.type))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),s.jsx("input",{value:d,onChange:A=>f(A.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",d||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),s.jsx("input",{value:u,onChange:A=>h(A.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"})]}),b&&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:b})]})}),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:g?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:T,disabled:!d||!u||x,className:"machine-btn",style:{background:d&&u?"rgba(34,197,94,0.12)":void 0,borderColor:d&&u?"rgba(34,197,94,0.3)":void 0,color:d&&u?"#86efac":void 0,opacity:!d||!u||x?.4:1},children:x?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Jl(e){return e==="cli"||e==="acp"}function Av(e){switch(e){case"detected":return"Detected";case"not_detected":return"Not detected";case"enabled_unchecked":return"Enabled, not checked";case"disabled":return"Disabled";default:return"Disabled"}}function _v(e){switch(e){case"detected":return"bg-green-500/[0.10] border-green-500/25 text-green-400";case"not_detected":return"bg-red-500/[0.10] border-red-500/25 text-red-400";case"enabled_unchecked":return"bg-yellow-500/[0.10] border-yellow-500/25 text-yellow-400";case"disabled":default:return"bg-white/[0.04] border-white/[0.10] text-text-muted"}}function Ql(e){if(!e)return"No result yet";const t=e.stage||"check",r=e.ok?"OK":"Failed",n=e.message||e.path||e.command||"";return n?`${t}: ${r} — ${n}`:`${t}: ${r}`}function Lv({machineId:e,providers:t,sendDaemonCommand:r}){var H;const[n,a]=i.useState([]),[o,l]=i.useState(!1),[c,d]=i.useState(null),[m,u]=i.useState("all"),[h,x]=i.useState(null),[S,b]=i.useState(!1),[p,g]=i.useState(null),[v,f]=i.useState("normal"),[C,T]=i.useState(""),[k,A]=i.useState(!1),_=i.useCallback(async()=>{if(e)try{const $=await r(e,"get_provider_source_config",{}),I=Yl($);I&&(g(I),f(I.sourceMode),T(I.explicitProviderDir||""))}catch{}},[e,r]),N=i.useCallback(async()=>{if(e){l(!0);try{const $=await r(e,"get_provider_settings",{}),I=Sv($);if(I){const y=Nv(I,t,{filterSchema:F=>F.filter(P=>P.key!=="enabled")});y.sort((F,P)=>F.category.localeCompare(P.category)||F.displayName.localeCompare(P.displayName)),a(y)}}catch{}l(!1)}},[e,t,r]);i.useEffect(()=>{n.length===0&&N(),p||_()},[]);const w=async($,I,y)=>{d(`${$}.${I}`),a(F=>F.map(P=>P.type===$?{...P,values:{...P.values,[I]:y}}:P));try{const F=await r(e,"set_provider_setting",{providerType:$,key:I,value:y});F!=null&&F.success||N()}catch{N()}d(null)},D=async($,I)=>{await w($,"enabled",I),await N()},M=async $=>{d(`${$}.detect`);try{await r(e,"detect_provider",{providerType:$})}finally{await N(),d(null)}},j=async $=>{await w($,"executablePath",""),await w($,"executableArgs",""),await N()},W=async()=>{A(!0);try{const $=await r(e,"set_provider_source_config",{providerSourceMode:v,providerDir:Cv(C)}),I=Yl($);I?(g(I),f(I.sourceMode),T(I.explicitProviderDir||"")):await _(),await N()}catch{await _()}A(!1)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex justify-between items-center mb-4",children:[s.jsxs("div",{className:"flex gap-1 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map($=>s.jsx("button",{onClick:()=>u($),className:`machine-btn text-[10px] px-2 py-0.5 ${m===$?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:$.toUpperCase()},$))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>b(!0),className:"machine-btn text-[10px] bg-green-500/[0.06] border-green-500/20 text-green-400 hover:bg-green-500/[0.12]",children:"✨ Create Provider"}),s.jsx("button",{onClick:N,disabled:o,className:"machine-btn",children:o?"⏳ Loading...":"↻ Refresh"})]})]}),s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-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-[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:"Affects provider resolution, fix/verify flows, and new launches. Running CLI sessions refresh provider scripts/config; process binary changes still apply on next launch."})]}),s.jsx("button",{onClick:_,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),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:$=>f($.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:C,onChange:$=>T($.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void W(),disabled:k,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:k?"Applying…":"Apply + Reload"})]}),s.jsxs("div",{className:"mt-3 grid gap-1 text-[11px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Effective user root:"})," ",(p==null?void 0:p.userDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(p==null?void 0:p.upstreamDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((H=p==null?void 0:p.providerRoots)==null?void 0:H.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter($=>$.category===m).length>1&&(()=>{const $=n.filter(P=>P.category===m),I=new Map;for(const P of $)for(const E of P.schema){if(E.type!=="boolean")continue;const G=I.get(E.key),J=!!(P.values[E.key]??E.default);G?(G.onCount+=J?1:0,G.total+=1):I.set(E.key,{label:E.label||E.key,onCount:J?1:0,total:1})}const y=[...I.entries()].filter(([,P])=>P.total===$.length);if(y.length===0)return null;const F=async(P,E)=>{for(const G of $)await w(G.type,P,E)};return s.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[s.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",m.toUpperCase()," providers (",$.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:y.map(([P,E])=>{const G=E.onCount===E.total,J=E.onCount===0;return s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:"text-text-secondary font-medium",children:E.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",E.onCount,"/",E.total,")"]}),s.jsx("button",{onClick:()=>void F(P,!0),disabled:G,className:`machine-btn text-[9px] px-1.5 py-px ${G?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),s.jsx("button",{onClick:()=>void F(P,!1),disabled:J,className:`machine-btn text-[9px] px-1.5 py-px ${J?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},P)})})]})})(),o&&n.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):s.jsx("div",{className:"flex flex-col gap-2",children:n.filter($=>m==="all"||$.category===m).map($=>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 gap-2 mb-2.5",children:[s.jsx("span",{className:"text-lg",children:$.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:$.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:$.category==="acp"?"rgba(139,92,246,0.08)":$.category==="cli"?"rgba(59,130,246,0.08)":$.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:$.category==="acp"?"#a78bfa":$.category==="cli"?"#60a5fa":$.category==="ide"?"#86efac":"var(--status-warning)"},children:$.category}),Jl($.category)&&(()=>{const I=t.find(P=>P.type===$.type),y=(I==null?void 0:I.enabled)===!0||$.values.enabled===!0,F=(I==null?void 0:I.machineStatus)||(y?"enabled_unchecked":"disabled");return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${_v(F)}`,children:Av(F)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void D($.type,!y),disabled:c===`${$.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${y?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:y?"Disable":"Enable"}),s.jsx("button",{onClick:()=>void M($.type),disabled:!y||c===`${$.type}.detect`,title:y?"Run detection for the configured executable":"Enable this provider before detection",className:`machine-btn text-[9px] px-2 py-0.5 text-blue-400 border-blue-500/25 ${y?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),s.jsx("button",{onClick:()=>void j($.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),$.category==="ide"&&s.jsx("button",{onClick:()=>x(t.find(I=>I.type===$.type)||{type:$.type,name:$.displayName,displayName:$.displayName,icon:$.icon,category:$.category}),className:"ml-auto machine-btn text-[9px] px-2 py-0.5 bg-violet-500/[0.06] border-violet-500/20 text-violet-400 hover:bg-violet-500/[0.12]",children:"🔧 Auto-Fix"})]}),Jl($.category)&&(()=>{const I=t.find(y=>y.type===$.type);return s.jsxs("div",{className:"mb-2.5 grid gap-1 rounded-lg border border-white/[0.06] bg-bg-primary/40 px-3 py-2 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Detection:"})," ",Ql(I==null?void 0:I.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",Ql(I==null?void 0:I.lastVerification)]}),s.jsx("div",{className:"text-[9px] text-text-muted",children:"Supported catalog entry only becomes launchable after Enable + Detect succeeds. Custom executable path/args below are machine-local overrides."})]})})(),s.jsx("div",{className:"flex flex-col gap-2",children:$.schema.map(I=>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-xs font-medium text-text-primary",children:[I.label||I.key,c===`${$.type}.${I.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),I.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:I.description})]}),s.jsx("div",{className:"shrink-0",children:I.type==="boolean"?s.jsx("button",{onClick:()=>w($.type,I.key,!($.values[I.key]??I.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:$.values[I.key]??I.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:$.values[I.key]??I.default?21:3}})}):I.type==="number"?s.jsx("input",{type:"number",value:Number($.values[I.key]??I.default??0)||0,min:I.min,max:I.max,onChange:y=>{const F=parseInt(y.target.value)||0;I.min!==void 0&&F<I.min||I.max!==void 0&&F>I.max||w($.type,I.key,F)},className:"machine-input w-20 text-center text-[11px]"}):I.type==="select"&&I.options?s.jsx("select",{value:String($.values[I.key]??I.default??""),onChange:y=>w($.type,I.key,y.target.value),className:"machine-input text-[11px]",children:I.options.map(y=>s.jsx("option",{value:y,children:y},y))}):s.jsx("input",{type:"text",value:String($.values[I.key]??I.default??""),onBlur:y=>w($.type,I.key,y.target.value),className:"machine-input w-[120px] text-[11px]"})})]},I.key))})]},$.type))}),h&&s.jsx(Tv,{machineId:e,provider:h,sendDaemonCommand:r,onClose:()=>x(null)}),S&&s.jsx(Mv,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>b(!1),onCreated:()=>{b(!1),N()}})]})}const Rv=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Pv({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function Dv(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function Ev(e){return e.trim().toLowerCase()}function sa(e,t){const r=Ev(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function pi(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Js(e,t=220){const r=pi(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function $v(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 Bv(e,t){return e.filter(r=>sa([r.level,r.message],t))}function Zl(e){return`${e.timestamp}:${e.level}:${e.message}`}function Ov(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const l of e.entries)n.set(Zl(l),l);for(const l of t.entries)n.set(Zl(l),l);const a=Array.from(n.values()).sort((l,c)=>l.timestamp-c.timestamp).slice(-r),o=a.reduce((l,c)=>Math.max(l,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 Fv(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 Wv(e,t){return e.split(`
|
|
76
|
+
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>sa([r],t))}function Kv(e,t){return e.filter(r=>sa([r.level,r.category,r.stage,r.interactionId,pi(r.payload)],t))}function Hv(e,t){return e.filter(r=>sa([r.kind,r.topic,r.interactionId,pi(r.payload)],t))}function ec(e){return e==="warn"||e==="error"}function Uv({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=>ec(a.level)).length+r.filter(a=>ec(a.level)).length}}function zv({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(`
|
|
77
77
|
`)):t.length>0&&a.push(["[daemon logs]",...t].join(`
|
|
78
78
|
`)),r.length>0&&a.push(["[trace]",...r.map(o=>`${new Date(o.ts).toISOString()} ${o.level.toUpperCase()} ${o.category}.${o.stage} ${Js(o.payload,500)}`.trim())].join(`
|
|
79
79
|
`)),n.length>0&&a.push(["[browser events]",...n.map(o=>`${new Date(o.ts).toISOString()} ${o.kind}${o.topic?` topic=${o.topic}`:""} ${Js(o.payload,500)}`.trim())].join(`
|
|
80
80
|
`)),a.join(`
|
|
81
81
|
|
|
82
|
-
`)}function
|
|
82
|
+
`)}function Vv({machineId:e,sendDaemonCommand:t}){const[r,n]=i.useState([]),[a,o]=i.useState("empty"),[l,c]=i.useState(""),[d,m]=i.useState([]),[u,h]=i.useState([]),[x,S]=i.useState(null),[b,p]=i.useState(!0),[g,v]=i.useState("info"),[f,C]=i.useState("all"),[T,k]=i.useState(!0),[A,_]=i.useState(!0),[N,w]=i.useState(""),[D,M]=i.useState(""),[j,W]=i.useState(0),H=i.useRef(0),$=i.useRef(0),I=i.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),y=i.useRef([]),F=i.useCallback(()=>{const ne={entries:[],kind:"empty",rawText:"",lastTs:0};I.current=ne,H.current=0,n([]),c(""),o("empty"),k(!0)},[]),P=i.useCallback(()=>{y.current=[],$.current=0,m([]),_(!0)},[]),E=i.useCallback(ne=>{ne!==g&&(F(),v(ne))},[g,F]),G=i.useCallback(ne=>{C(ue=>ue===ne?ue:ne)},[]),J=i.useCallback(()=>{F(),P(),h([]),S(null),w(""),M(""),Hs.clear()},[F,P]),ye=i.useCallback(()=>{W(ne=>ne+1)},[]),he=i.useCallback(async()=>{if(!e)return;const ne=H.current,ue=$.current,[Se,ve]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:g,since:ne}),t(e,"get_debug_trace",Pv({count:120,since:ue,category:f}))]);if(Se.status==="fulfilled"){const X=Se.value,xe=(X==null?void 0:X.result)||X,fe=$v(xe),we=Ov(I.current,fe,300);I.current=we,H.current=we.lastTs,k(!1),w((X==null?void 0:X.success)===!1?String((X==null?void 0:X.error)||"Could not load daemon logs"):""),o(we.kind),c(we.rawText),n(we.entries)}else k(!1),w(Se.reason instanceof Error?Se.reason.message:"Could not load daemon logs");if(ve.status==="fulfilled"){const X=ve.value,xe=(X==null?void 0:X.result)||X;if((X==null?void 0:X.success)===!1)M(String((X==null?void 0:X.error)||"Could not load daemon trace"));else if(Array.isArray(xe==null?void 0:xe.trace)){const fe=xe.trace,we=Fv(y.current,fe,120),be=fe.reduce((Ce,ee)=>Math.max(Ce,Number(ee.ts||0)),ue);y.current=we,be>ue&&($.current=be),M(""),m(we)}else M("");_(!1)}else _(!1),M(ve.reason instanceof Error?ve.reason.message:"Could not load daemon trace");h(Hs.list({limit:120})),S(Date.now())},[g,e,t,f]);return i.useEffect(()=>{P()},[P,f]),i.useEffect(()=>{if(!e||(he(),!b))return;const ne=setInterval(()=>{he()},3e3);return()=>clearInterval(ne)},[b,he,e,j]),{daemonLogs:r,daemonLogKind:a,daemonRawText:l,debugTrace:d,webEvents:u,lastUpdatedAt:x,autoRefresh:b,logLevel:g,traceCategory:f,daemonLoading:T,traceLoading:A,daemonFetchError:N,traceFetchError:D,setAutoRefresh:p,setLogLevel:E,setTraceCategory:G,refresh:ye,clear:J}}function Gv({daemonLoading:e,traceLoading:t,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:o,daemonRawLineCount:l,traceCount:c,webEventCount:d}){return[{id:"daemon_logs",label:"Daemon logs",status:r?"error":e?"loading":o>0||l>0?"ok":"empty",detail:r||(a==="text"?`${l} raw file-fallback line(s)`:`${o} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:n?"error":t?"loading":c>0?"ok":"empty",detail:n||`${c} trace event(s)`},{id:"browser_events",label:"Browser debug events",status:d>0?"ok":"empty",detail:d>0?`${d} local browser event(s)`:"No browser events captured"}]}function tc(e){return e==="warn"||e==="error"}function qv(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 Yv(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 sc(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function Xv(e){const t=Js(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function Jv(e){const t=Js(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function Qv({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.forEach((o,l)=>{a.push({id:`daemon-log-${o.timestamp}-${l}`,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:Jv(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:Xv(o),category:o.category,stage:o.stage,interactionId:o.interactionId,payload:o.payload})}),t.forEach((o,l)=>{a.push({id:`raw-file-${l}`,source:"raw_file",ts:Yv(o,l),severity:qv(o),message:o,raw:o})}),a.sort((o,l)=>o.ts!==l.ts?o.ts-l.ts:sc(o.source)-sc(l.source))}function Zv(e){return`${e.source}:${e.severity}:${e.message}`}function ew(e){const t=e.filter(n=>tc(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!tc(n.severity))continue;const a=Zv(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 tw(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function rc(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${tw(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function sw({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
|
|
83
83
|
`)),a.push(["[source status]",...r.map(l=>`${l.label}: ${l.status} - ${l.detail}`)].join(`
|
|
84
|
-
`)),t.latestIssue&&a.push(["[latest issue]",
|
|
84
|
+
`)),t.latestIssue&&a.push(["[latest issue]",rc(t.latestIssue)].join(`
|
|
85
85
|
`)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.repeatedPatterns.map(l=>`${l.count}x ${l.severity.toUpperCase()} ${l.source} ${l.message}`)].join(`
|
|
86
|
-
`));const o=e.slice(-n);return a.push(["[timeline]",...o.length>0?o.map(
|
|
86
|
+
`));const o=e.slice(-n);return a.push(["[timeline]",...o.length>0?o.map(rc):["No diagnostic events captured."]].join(`
|
|
87
87
|
`)),a.join(`
|
|
88
88
|
|
|
89
|
-
`)}function Zv(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function ew(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function tw({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:l,searchQuery:c,daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:h}){const x=_v(n,o),S=Pv(e,c),b=$v(t,c),p=Bv(x,c),g=Ov(a,c),v=Zv(S,l),f=l==="all"?b:[],T=ew(p,l),I=l==="issues"?[]:g,k=Fv({daemonLogs:S,daemonRawLines:b,trace:p,webEvents:g}),A=qv({daemonLogs:v,daemonRawLines:f,trace:T,webEvents:I}),_=Xv(A),N=Hv({daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:h,daemonLogKind:r,daemonLogsCount:S.length,daemonRawLineCount:b.length,traceCount:p.length,webEventCount:g.length});return{filteredDaemonLogs:S,filteredDaemonRawLines:b,filteredTraceEntries:p,filteredWebEvents:g,visibleDaemonLogs:v,visibleDaemonRawLines:f,visibleTraceEntries:T,visibleWebEvents:I,quickFilterCounts:k,diagnosticEvents:A,diagnosticsSummary:_,sourceStates:N}}function sw(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Du(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function So(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 Ua(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 hi(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function rw({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${So(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Du(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:hi(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 nw({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:l,onCopyVisible:c,onToggleAutoRefresh:d,onRefresh:m,onClear:u}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(h=>s.jsx("button",{type:"button",onClick:()=>a(h.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===h.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:h.label},h.id))}),s.jsx("input",{value:r,onChange:h=>o(h.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:l,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:d,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:m,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function aw({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:Mv.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 ow({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:l,traceFetchError:c}){var u,h;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((h=e.latestIssue)==null?void 0:h.severity)==="warn"?"warning":"good",m=l||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 ${Ua(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 ${Ua(d)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[hi(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:Du(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 ${Ua(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:l||c?"Needs attention":o?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",sw(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(x=>s.jsxs("div",{children:[x.label,": ",x.status]},x.id))})]})]})}function iw({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()," · ",hi(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function lw({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:l,visibleWebEvents:c,quickFilter:d,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(u=>({...u,timeline:!u.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(u=>s.jsx(rw,{event:u},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,daemon:!u.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${o.length} visible raw line(s) from file fallback`:`${a.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&a.length===0&&o.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&o.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:d==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&a.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&o.map((u,h)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${h}`)),e.daemonLogKind!=="text"&&a.map((u,h)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${So(u.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(u.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:u.level==="error"?"ERR":u.level==="warn"?"WRN":u.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:u.message})]},`log-${h}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,trace:!u.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[l.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&&l.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&l.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&l.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."}),l.map(u=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${So(u.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.level.toUpperCase()}),s.jsxs("span",{children:[u.category,".",u.stage]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Js(u.payload,360)||"No payload"})]},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,web:!u.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[c.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:m.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),c.map(u=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.kind}),u.topic&&s.jsxs("span",{children:["topic=",u.topic]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Js(u.payload,360)||"No payload"})]},u.id))]})]})]})}function cw({machineId:e,sendDaemonCommand:t}){const r=Kv({machineId:e,sendDaemonCommand:t}),[n,a]=i.useState("info"),[o,l]=i.useState(""),[c,d]=i.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=i.useRef(null),u=i.useRef(!1),h=i.useMemo(()=>tw({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]);i.useEffect(()=>{if(r.autoRefresh&&h.diagnosticEvents.length>0){const b=u.current?"smooth":"instant";setTimeout(()=>{var p;(p=m.current)==null||p.scrollIntoView({behavior:b}),u.current=!0},50)}},[h.diagnosticEvents.length,r.autoRefresh]);const x=i.useCallback(async()=>{var p;const b=Wv({daemonLogs:h.visibleDaemonLogs,daemonRawLines:h.visibleDaemonRawLines,trace:h.visibleTraceEntries,webEvents:h.visibleWebEvents});if(!b.trim()){it.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(b)),it.showToast("Copied visible logs to clipboard.","success")}catch(g){it.showToast(g instanceof Error?g.message:"Could not copy visible logs","warning")}},[h.visibleDaemonLogs,h.visibleDaemonRawLines,h.visibleTraceEntries,h.visibleWebEvents]),S=i.useCallback(async()=>{var p;const b=Qv({events:h.diagnosticEvents,summary:h.diagnosticsSummary,sources:h.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(b)),it.showToast("Copied diagnostic bundle to clipboard.","success")}catch(g){it.showToast(g instanceof Error?g.message:"Could not copy diagnostic bundle","warning")}},[h.diagnosticEvents,h.diagnosticsSummary,h.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(nw,{quickFilter:n,quickFilterCounts:h.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:l,onCopyDiagnostics:()=>{S()},onCopyVisible:()=>{x()},onToggleAutoRefresh:()=>r.setAutoRefresh(b=>!b),onRefresh:r.refresh,onClear:r.clear}),s.jsx(aw,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(ow,{diagnosticsSummary:h.diagnosticsSummary,diagnosticEventsCount:h.diagnosticEvents.length,sourceStates:h.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(iw,{patterns:h.diagnosticsSummary.repeatedPatterns}),s.jsx(lw,{streams:r,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:h.diagnosticEvents,visibleDaemonLogs:h.visibleDaemonLogs,visibleDaemonRawLines:h.visibleDaemonRawLines,visibleTraceEntries:h.visibleTraceEntries,visibleWebEvents:h.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:m})]})}function dw(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 Eu(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 uw(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const l=String((o==null?void 0:o.lifecycle)||"").trim(),c=Eu((o==null?void 0:o.meta)||void 0),d=((a=o==null?void 0:o.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(l)?t.push(o):(l==="stopped"||l==="failed")&&(d||c)?r.push(o):n.push(o)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function mw(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function za(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 Va(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Ga(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function rc(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 pw(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function hw(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 fw(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 xw({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=i.useState(""),[o,l]=i.useState(null),[c,d]=i.useState(!1),m=Mb(e,{enabled:!!e,includeSessions:!0,limit:qi,intervalMs:Nf}),u=m.diagnostics,h=m.loading,x=m.applyDiagnostics,S=i.useMemo(()=>dw({diagnostics:u,loading:h,refreshing:c,error:n}),[u,h,c,n]),b=i.useMemo(()=>new Map(t.map(M=>[M.sessionId||M.id,M])),[t]),p=i.useCallback(async()=>{if(e){d(!0);try{const M=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:qi}),j=Va(M);if(!(j!=null&&j.success))throw new Error((j==null?void 0:j.error)||"Could not load hosted runtime diagnostics");x(j.diagnostics||j.result||null),a("")}catch(M){const j=M instanceof Error?M.message:"Could not load hosted runtime diagnostics";a(j)}finally{d(!1)}}},[x,e,r]);i.useEffect(()=>{!e||u||h||c||p()},[u,h,e,p,c]);const g=i.useCallback(async(M,j)=>{const W=`${M}:${j.sessionId}`;if(!(M==="session_host_stop_session"&&!window.confirm(`Stop ${j.displayName}?
|
|
90
|
-
This will terminate the hosted runtime.`))){l(W);try{const H=await r(e,M,{sessionId:j.sessionId}),$=Va(H);if(!($!=null&&$.success))throw new Error(($==null?void 0:$.error)||"Session host action failed");const
|
|
91
|
-
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){l("session_host_prune_duplicate_sessions");try{const j=await r(e,"session_host_prune_duplicate_sessions",{}),W=Va(j);if(!(W!=null&&W.success))throw new Error((W==null?void 0:W.error)||"Duplicate prune failed");const H=W.result||{},$=Array.isArray(H.prunedSessionIds)?H.prunedSessionIds.length:0,C=typeof H.duplicateGroupCount=="number"?H.duplicateGroupCount:0;it.showToast(`Pruned ${$} duplicate runtime(s) across ${C} group(s)`,"success"),await p()}catch(j){const W=j instanceof Error?j.message:"Duplicate prune failed";it.showToast(W,"warning"),a(W)}finally{l(j=>j==="session_host_prune_duplicate_sessions"?null:j)}}},[e,p,r]),f=i.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((M,j)=>(j.lastActivityAt||0)-(M.lastActivityAt||0)),[u==null?void 0:u.sessions]),T=i.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:uw(f),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,f]),I=T.liveRuntimes,k=T.recoverySnapshots,A=T.inactiveRecords,_=i.useMemo(()=>fw(I),[I]),N=i.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),w=i.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(M=>M.level==="warn"||M.level==="error")||null,[u==null?void 0:u.recentLogs]),D=(M,j)=>{var G;const W=o===`session_host_resume_session:${M.sessionId}`,H=o===`session_host_restart_session:${M.sessionId}`,$=o===`session_host_stop_session:${M.sessionId}`,C=Eu(M.meta),y=b.get(M.sessionId),F=M.attachedClients.length===1?"1 client":`${M.attachedClients.length} clients`,P=j==="recovery"?"Recover":"Resume",E=mw(j);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:M.displayName||(y==null?void 0:y.cliName)||M.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${hw(M.lifecycle)}`,children:M.lifecycle}),C&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:C})]}),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:M.workspaceLabel||(y==null?void 0:y.runtimeWorkspaceLabel)||M.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:M.runtimeKey}),M.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",M.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((G=M.writeOwner)==null?void 0:G.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:pw(M.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(bc,{size:11})," ",F]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",rc(M.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",E]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[j==="recovery"&&(M.lifecycle==="interrupted"||M.lifecycle==="failed"||M.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{g("session_host_resume_session",M)},children:W?`${P}ing…`:P}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{g("session_host_restart_session",M)},children:H?"Restarting…":"Restart"}),j==="live"&&(M.lifecycle==="running"||M.lifecycle==="starting"||M.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:()=>{g("session_host_stop_session",M)},children:$?"Stopping…":"Stop"})]})]})},M.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:Ax()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[_>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{v()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${_})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${S.toneClass}`,children:S.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:h||c,children:[s.jsx(Rr,{size:13}),h||c?"Refreshing…":"Refresh"]})]})]}),n&&!u&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(Ar,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children: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:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:rc(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Ga(u.hostStartedAt)})]})]}),w&&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(Ar,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:w.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Ga(w.timestamp),w.sessionId?` · ${w.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(Ro,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:za("live")}),I.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:I.map(M=>D(M,"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:za("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(M=>D(M,"recovery"))})]}),A.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:za("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:A.map(M=>D(M,"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"}),N.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:N.map(M=>{var W;const j=f.find(H=>H.sessionId===M.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:(j==null?void 0:j.displayName)||((W=b.get(M.sessionId))==null?void 0:W.cliName)||M.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[M.action,M.lifecycle?` · ${M.lifecycle}`:"",M.detail?` · ${M.detail}`:"",M.error?` · ${M.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${M.success===!1?"text-red-300":"text-text-secondary"}`,children:Ga(M.timestamp)})]},`${M.sessionId}:${M.timestamp}:${M.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function bw({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 qa({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 Ya({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 gw({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:l}){const c=n.slice(0,6),d=r.slice(0,4),m="0.9.81",u=Hd(e),h=$s(e,m),x=Sr(e,h),S=u==="preview"?"Update to preview":"Update daemon";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(qa,{icon:s.jsx(es,{size:13}),children:"Current Chats"}),s.jsx(Ya,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(b=>{const p=yo(b);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:()=>l(b),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:ut(b)}),p>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Un(p)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Is(b)})]},b.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(qa,{icon:s.jsx(wc,{size:13}),children:"Recent Launches"}),s.jsx(Ya,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(b=>{const{metaText:p,updatedLabel:g}=tu(b);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(b),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:b.label}),g&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:g})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:p})]},b.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(qa,{icon:s.jsx(Ar,{size:13}),children:"Daemon Update"}),s.jsx(Ya,{className:"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:x?"Daemon update required":"Version mismatch detected"}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[x?"This machine is on an incompatible daemon version. Update it before starting more sessions.":u==="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.",h&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",h,u?` (${u})`:""]})]}),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(Rr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:S})]})]})})]})]})}function yw(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function vw({machine:e,selectedWorkspace:t,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:o,onCustomPathChange:l,onOpenBrowseDialog:c}){return s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[s.jsx("select",{value:t,onChange:d=>{const m=d.target.value;if(o(m),m==="__custom__"&&a){c();return}m!=="__custom__"&&l("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(e.workspaces||[]).length>0?s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(e.workspaces||[]).map(d=>s.jsxs("option",{value:d.id,children:[d.id===e.defaultWorkspaceId?"⭐ ":"",Vn(d.path,d.label)]},d.id)),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]})}),t==="__custom__"&&(a?s.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:c,children:"Select workspace…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:n,onChange:d=>l(d.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:t==="__custom__"?r?s.jsx("span",{className:"font-mono truncate block",title:r,children:r}):a?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":r?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:t===e.defaultWorkspaceId?"Default workspace":"Selected workspace"}),s.jsx("span",{className:"font-mono truncate block",title:r,children:r})]}):"No workspace selected. This launches in the home directory."})]})}const ww={ide:{label:"IDE",plural:"IDEs",accent:"border-blue-500/[0.12]"},cli:{label:"CLI",plural:"CLIs",accent:"border-violet-500/[0.12]"},acp:{label:"ACP Agent",plural:"ACP agents",accent:"border-emerald-500/[0.12]"}};function un(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Xa({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:o,actions:l,sendDaemonCommand:c,initialWorkspaceId:d,initialWorkspacePath:m,onOpenGitDialog:u}){const h=As(),{handleLaunchIde:x,handleStopCli:S,handleRestartIde:b,handleStopIde:p,handleDetectIdes:g,launchingIde:v,launchingAgentType:f,addLog:T}=l,[I,k]=i.useState(null),A=i.useCallback(L=>{L&&h(Zt(L))},[h]),_=ww[e],N=e==="ide",w=e==="acp",D=i.useMemo(()=>n.filter(L=>Ts(L,e)),[e,n]),M=i.useMemo(()=>new Map(D.map(L=>[L.type,L.displayName||L.type])),[D]),[j,W]=i.useState(""),[H,$]=i.useState(""),[C,y]=i.useState([]),[F,P]=i.useState(""),[E,G]=i.useState(""),[J,ye]=i.useState([]),[he,ne]=i.useState(!1),[ue,Se]=i.useState(!1),[ve,X]=i.useState(""),[xe,fe]=i.useState(!1),[we,be]=i.useState(()=>Ct()),[Ce,ee]=i.useState(null),[me,ie]=i.useState(m?"__custom__":d||t.defaultWorkspaceId||""),[pe,le]=i.useState(m||""),[B,z]=i.useState([]),[de,re]=i.useState(!1),[R,q]=i.useState(""),[ce,Ne]=i.useState([]),[je,O]=i.useState(!1),[Ie,Le]=i.useState(""),He=i.useRef(null),[ze,Xe]=i.useState(null),Je=i.useRef("__home__"),[rt,pt]=i.useState("__home__"),[xt,vt]=i.useState(!1),Te=i.useRef(0),Ve=B.filter(L=>!a.some(Q=>Q.type===L&&yt(Q.status)!=="stopped")),tt=i.useRef({});i.useEffect(()=>{t.defaultWorkspaceId&&!me&&ie(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),i.useEffect(()=>{if(m){ie("__custom__"),le(m);return}d&&(ie(d),le(""))},[d,m]),i.useEffect(()=>{N||j&&(D.some(L=>L.type===j)||(W(""),G("")))},[D,N,j]);const Ge=(()=>{if(me==="__custom__")return pe.trim();if(!me)return"";const L=(t.workspaces||[]).find(Q=>Q.id===me);return(L==null?void 0:L.path)||""})(),ot=i.useCallback(L=>{const Q=tt.current[L];Q&&(clearTimeout(Q),delete tt.current[L]),z(ge=>ge.includes(L)?ge.filter(Be=>Be!==L):ge)},[]),U=i.useRef(new Set),V=i.useCallback(async L=>{if(c){O(!0),Le("");try{const Q=await Zn(c,r,L);q(Q.path),le(Q.path),Ne(Q.directories)}catch(Q){Le(Q instanceof Error?Q.message:"Could not load folder")}finally{O(!1)}}},[r,c]),Z=i.useCallback(()=>{if(!c)return;ie("__custom__"),re(!0);const L=a.map(ge=>ge.workspace),Q=Qn(t.platform,Jn(pe.trim(),Ge,m,L,t.defaultWorkspacePath,(t.workspaces||[]).map(ge=>ge.path)));V(Q)},[pe,m,V,t.defaultWorkspacePath,t.platform,t.workspaces,a,Ge,c]),ae=i.useCallback(L=>{const Q=String(L.workspace||"").trim();if(!Q)return;const ge=(t.workspaces||[]).find(Be=>un(Be.path)===un(Q));if(ge){ie(ge.id),le("");return}ie("__custom__"),le(Q)},[t.workspaces]),K=i.useCallback(L=>{const Q=String(L.workspace||"").trim();if(!Q)return{workspaceId:null,workspacePath:"",useHome:!0};const ge=(t.workspaces||[]).find(Be=>un(Be.path)===un(Q));return ge?{workspaceId:ge.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:Q,useHome:!1}},[t.workspaces]),Y=i.useCallback(async L=>{if(!c||!L||e!=="cli"){ye([]),ne(!1),Se(!1),X("");return}const Q=Te.current+1;Te.current=Q,ne(!0),X("");try{const ge=await c(r,"list_saved_sessions",{providerType:L,kind:"cli",limit:30});if(Te.current!==Q)return;const Be=(ge==null?void 0:ge.result)??ge;ye(Array.isArray(Be==null?void 0:Be.sessions)?Be.sessions:[])}catch(ge){if(Te.current!==Q)return;ye([]),X(ge instanceof Error?ge.message:"Could not load saved sessions")}finally{Te.current===Q&&(ne(!1),Se(!0))}},[e,r,c]),se=i.useMemo(()=>{if(e!=="cli"||!j)return null;const L=M.get(j)||j;return{routeId:r,daemonId:r,providerSessionId:E||void 0,transport:"pty",mode:"chat",agentName:L,agentType:j,status:"idle",title:L,messages:[],ideType:j,workspaceName:Ge,workspacePath:Ge,displayPrimary:L,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${j}`}},[e,r,M,Ge,E,j]),oe=i.useCallback(L=>{if(e==="ide"||!L){y([]);return}y(jo(r,L))},[e,r]),ke=i.useCallback((L,Q)=>{e==="ide"||!L||(Hy(r,L,Q),y(jo(r,L)))},[e,r]);i.useEffect(()=>{Te.current+=1,G(""),oe(j),Se(!1),ye([]),X(""),ne(!1)},[e,oe,Y,j]);const Pe=i.useMemo(()=>J.find(L=>L.providerSessionId===E)||null,[J,E]);i.useEffect(()=>{if(!E)return;const L=J.find(Q=>Q.providerSessionId===E);L!=null&&L.canResume||G("")},[J,E]);const Ee=i.useCallback((L,Q)=>{He.current=Q,Je.current=L.selectedWorkspaceKey||"__home__",pt(L.selectedWorkspaceKey||"__home__"),Xe(L)},[]),Ae=i.useCallback(()=>{He.current&&(vt(!0),He.current().finally(()=>{He.current=null,vt(!1),Xe(null)}))},[]),$e=i.useCallback(L=>{if(!L)return;z(ge=>ge.includes(L)?ge:[...ge,L]);const Q=tt.current[L];Q&&clearTimeout(Q),tt.current[L]=setTimeout(()=>{z(ge=>ge.includes(L)?ge.filter(Be=>Be!==L):ge),delete tt.current[L]},2e4)},[]);i.useEffect(()=>{for(const Q of a)yt(Q.status)!=="stopped"&&(B.includes(Q.type)&&!U.current.has(Q.type)&&(U.current.add(Q.type),T("info",`${M.get(Q.type)||Q.type} launched`,!0)),ot(Q.type));const L=new Set(a.filter(Q=>yt(Q.status)!=="stopped").map(Q=>Q.type));U.current.forEach(Q=>{!B.includes(Q)&&!L.has(Q)&&U.current.delete(Q)})},[T,ot,a,B,M]),i.useEffect(()=>()=>{Object.values(tt.current).forEach(clearTimeout),tt.current={}},[]);const[Fe,Me]=i.useState({}),[Qe,et]=i.useState(null);i.useEffect(()=>{if(!N||!r||!c)return;(async()=>{try{const Q=await c(r,"get_ide_extensions",{}),ge=(Q==null?void 0:Q.result)||Q;ge!=null&&ge.success&&(ge!=null&&ge.ideExtensions)&&Me(ge.ideExtensions)}catch{}})()},[N,r,c]);const bt=L=>N?ct(L.type):e==="cli"?L.cliName:L.acpName,gt=N?t.detectedIdes||[]:[],dt=i.useCallback(async L=>{const Q=(L==null?void 0:L.type)||j,ge=(L==null?void 0:L.workspacePath)??Ge;if(N){await x(Q,ge?{workspace:ge}:void 0)&&$e(Q);return}const Be=await l.runLaunchCliCore({cliType:Q,dir:L!=null&&L.workspaceId?void 0:ge||void 0,workspaceId:(L==null?void 0:L.workspaceId)||void 0,useHome:(L==null?void 0:L.useHome)||!(L!=null&&L.workspaceId)&&!ge,argsStr:(L==null?void 0:L.argsStr)??(H||void 0),model:(L==null?void 0:L.model)??(w&&F||void 0),resumeSessionId:(L==null?void 0:L.resumeSessionId)||!w&&e==="cli"&&Q===j&&E||void 0});if(Be.success||Be.pending){const _e=(L==null?void 0:L.argsStr)??H;!N&&(_e!=null&&_e.trim())&&(fu(r,Q,_e),oe(Q)),$e(Q),Be.success&&Be.sessionId&&A(Be.sessionId)}},[l,x,w,N,H,F,oe,$e,r,A,Ge,E,j]),ht=pd(N?"ide":w?"acp":"cli",!N&&!w&&!!E),Ue=hd(N?"ide":w?"acp":"cli",!N&&!w&&!!E),Kt=()=>{var _e;const L=N?ct(j):M.get(j)||j,Q=!N&&!w&&!!E,{options:ge,selectedKey:Be}=ks({machine:t,currentWorkspaceId:me&&me!=="__custom__"?me:null,currentWorkspacePath:Ge});Ee({title:Q?Qo(L):gs("start-fresh",L),description:Q?Zo():ys("start-fresh"),confirmLabel:ht,busyLabel:Ue,workspaceOptions:ge,selectedWorkspaceKey:Be,details:[{label:"Mode",value:_.label},{label:"Provider",value:L},...!N&&e==="cli"&&E?[{label:"Resume",value:((_e=J.find(Oe=>Oe.providerSessionId===E))==null?void 0:_e.title)||E}]:[],...!N&&H.trim()?[{label:"Arguments",value:H.trim()}]:[],...w&&F.trim()?[{label:"Model",value:F.trim()}]:[]]},async()=>{const Oe=ge.find(nt=>nt.key===Je.current);Oe!=null&&Oe.workspaceId?(ie(Oe.workspaceId),le("")):Oe!=null&&Oe.workspacePath?(ie("__custom__"),le(Oe.workspacePath)):(ie(""),le("")),await dt({workspaceId:(Oe==null?void 0:Oe.workspaceId)??null,workspacePath:(Oe==null?void 0:Oe.workspacePath)??"",useHome:!(Oe!=null&&Oe.workspaceId)&&!(Oe!=null&&Oe.workspacePath)})})},te=L=>{N?p(L):S(L.type,L.workspace,L.id)},De=i.useCallback(async(L,Q,ge=!1)=>{if(L.mode===Q){ge&&L.sessionId&&A(L.sessionId);return}if(!c||!L.sessionId){ge&&L.sessionId&&A(L.sessionId);return}try{await c(r,"set_cli_view_mode",{targetSessionId:L.sessionId,cliType:L.type,mode:Q}),ge&&A(L.sessionId)}catch(Be){const _e=Pd(Be);Rd(Be)?console.warn(_e?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Be instanceof Error?Be.message:String(Be)):console.error("Failed to switch CLI view mode:",Be)}},[r,A,c]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${_.accent} relative overflow-hidden`,children:[s.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",_.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:N?gt.length>0?gt.map(L=>{const Q=a.find(nt=>(nt.type||"").toLowerCase()===(L.type||"").toLowerCase()&&yt(nt.status)!=="stopped"),ge=L.running||!!Q,Be=!!Q&&Q.cdpConnected,_e=B.includes(L.type||L.id||""),Oe=j===(L.type||"");return s.jsxs("button",{onClick:()=>{if(Be&&Q){const nt=Q.sessionId;nt?h(Zt(nt),{state:{openRemoteForTabKey:nt}}):h("/dashboard",{state:{openRemoteForTabKey:Q.id}});return}_e||W(nt=>nt===(L.type||"")?"":L.type||"")},disabled:!!v||_e,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Be?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Oe?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:v&&v!==L.type?.4:1},children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:o(L.type)}),ge&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Be?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:L.name||ct(L.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Be?"text-green-400":_e?"text-orange-400":Oe?"text-accent-primary":"text-text-muted"}`,children:Be?"Open Session":_e?"Starting...":Oe?"Configure":"Select"})]})]},L.type)}):s.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",s.jsxs("button",{onClick:g,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[s.jsx(Zm,{size:14})," Scan System"]})]}):D.length>0?D.map(L=>{const Q=j===L.type,ge=B.includes(L.type),_e=!!a.find(Oe=>Oe.type===L.type&&yt(Oe.status)!=="stopped");return s.jsxs("button",{onClick:()=>W(Oe=>Oe===L.type?"":L.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Q?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:L.icon}),_e&&s.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:L.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ge?"text-orange-400":Q?"text-accent-primary":"text-text-muted"}`,children:ge?"Starting...":Q?"Configure":"Select"})]})]},L.type)}):s.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),j&&(N?gt.find(L=>L.type===j):D.find(L=>L.type===j))&&s.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[s.jsx("span",{children:"Launch Settings"}),s.jsx("span",{className:"text-accent-primary font-bold",children:N?ct(j):M.get(j)||j})]}),s.jsx(vw,{machine:t,selectedWorkspace:me,resolvedWorkspacePath:Ge,customPath:pe,canBrowse:!!c,onWorkspaceChange:ie,onCustomPathChange:le,onOpenBrowseDialog:Z}),!N&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&e==="cli"&&s.jsx(bu,{busy:!!f||!!v||B.includes(j),savedSessionsLoading:he,savedSessionsError:ve,savedSessionsLoaded:ue,savedSessionsCount:J.length,selectedSession:Pe,onRefresh:()=>void Y(j),onOpenHistory:()=>{j&&(fe(!0),xu({hasLoadedInitialResults:ue,isLoading:he})&&Y(j))},onClearSelection:()=>G("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[w&&s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),s.jsx("input",{type:"text",placeholder:"Leave empty for default",value:F,onChange:L=>P(L.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),s.jsx("input",{type:"text",placeholder:"Optional flags...",value:H,onChange:L=>$(L.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),C.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:C.map(L=>s.jsxs("div",{className:"inline-flex max-w-full items-stretch overflow-hidden rounded-md border border-[#ffffff1a] bg-bg-tertiary text-xs text-text-secondary transition-colors hover:border-accent-primary/40 hover:text-text-primary",title:L,children:[s.jsx("button",{type:"button",className:"min-w-0 max-w-[220px] truncate px-2.5 py-1.5 text-left",onClick:()=>$(L),children:L}),s.jsx("button",{type:"button",className:"flex items-center justify-center border-l border-[#ffffff1a] px-1.5 text-text-muted transition-colors hover:bg-status-error/10 hover:text-status-error focus:outline-none focus:ring-1 focus:ring-status-error/50",onClick:()=>ke(j,L),"aria-label":`Remove startup arguments: ${L}`,title:"Remove startup arguments",children:s.jsx(wt,{size:12})})]},L))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:Kt,disabled:!!f||!!v||B.includes(j),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:f===j||v===j?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+B.filter(L=>!a.some(Q=>Q.type===L&&yt(Q.status)!=="stopped")).length,")"]}),a.length===0&&Ve.length===0?s.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",_.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ve.map(L=>s.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:o(L)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:N?ct(L):M.get(L)||L}),s.jsx("div",{className:"text-[11px] text-text-muted",children:f===L?"Launching process...":"Waiting for process and session to register..."})]})]}),s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${L}`)),a.map(L=>{const Q=N?L:null,ge=!N&&!w?L:null,Be=yt(L.status);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 justify-between items-center mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:o(L.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[bt(L),(Q==null?void 0:Q.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",Q.version]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted flex min-w-0 flex-wrap items-center gap-2",children:[s.jsx("span",{className:"truncate",children:L.workspace||"—"}),u&&L.git&&L.workspace?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:_e=>{_e.stopPropagation(),u(L.daemonId??r,L.workspace)},children:s.jsx(qs,{git:L.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(qs,{git:L.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(ge==null?void 0:ge.mode)&&s.jsx("span",{className:ge.mode==="chat"?"text-violet-400":"text-text-secondary",children:ge.mode==="chat"?"Chat view":"Terminal view"})]}),ge&&(ge.runtimeKey||ge.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ge.runtimeKey&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),s.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",ge.runtimeKey]}),s.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var _e;(_e=navigator.clipboard)==null||_e.writeText(`adhdev attach ${ge.runtimeKey}`),k(ge.runtimeKey||null),window.setTimeout(()=>{k(Oe=>Oe===ge.runtimeKey?null:Oe)},1200)},children:I===ge.runtimeKey?"Copied":"Copy"})]}),ge.runtimeWriteOwner&&s.jsx("span",{style:{color:ge.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ge.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:yw(ge.runtimeWriteOwner)})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Be==="stopped"?"bg-red-500/[0.08] text-red-500":Be==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Be}),N&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const _e=L.sessionId;if(_e){h(Zt(_e),{state:{openRemoteForTabKey:_e}});return}h("/dashboard",{state:{openRemoteForTabKey:L.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:s.jsx(_t,{size:13})}),s.jsx("button",{onClick:()=>{const _e=L.workspace||"",{options:Oe,selectedKey:nt}=ks({machine:t,currentWorkspacePath:_e});Ee({title:gs("restart-ide",ct(L.type)),description:ys("restart-ide"),confirmLabel:Ys("restart-ide"),busyLabel:Xs("restart-ide"),workspaceOptions:Oe,selectedWorkspaceKey:nt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:ct(L.type)}]},async()=>{const Mt=Oe.find(ss=>ss.key===Je.current),ft=(Mt==null?void 0:Mt.workspacePath)??"";if(ft&&ft!==_e){await dt({type:L.type,workspacePath:ft});return}await b(L)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:s.jsx(Rr,{size:14})})]}),w&&s.jsx("button",{onClick:()=>{const _e=L.sessionId;_e&&A(_e)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!L.sessionId,children:s.jsx(es,{size:14})}),ge&&Be!=="stopped"&&s.jsxs(s.Fragment,{children:[ge.mode&&s.jsx(Yo,{mode:ge.mode,onChange:_e=>void De(ge,_e,!1),compact:!0}),s.jsx("button",{onClick:()=>{const _e=L.sessionId;_e&&A(_e)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!L.sessionId,children:ge.mode==="chat"?s.jsx(es,{size:14}):s.jsx(_t,{size:13})})]}),Be==="stopped"?s.jsx("button",{onClick:()=>{const _e=L.workspace||"",Oe=N?ct(L.type):bt(L),{options:nt,selectedKey:Mt}=ks({machine:t,currentWorkspacePath:_e});Ee({title:gs("restart-stopped",Oe),description:ys("restart-stopped"),confirmLabel:Ys("restart-stopped"),busyLabel:Xs("restart-stopped"),workspaceOptions:nt,selectedWorkspaceKey:Mt,details:[{label:"Mode",value:_.label},{label:"Provider",value:Oe}]},async()=>{const ft=nt.find(ss=>ss.key===Je.current);await dt({type:L.type,workspaceId:(ft==null?void 0:ft.workspaceId)??null,workspacePath:(ft==null?void 0:ft.workspacePath)??"",useHome:!(ft!=null&&ft.workspaceId)&&!(ft!=null&&ft.workspacePath)})})},disabled:B.includes(L.type),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-green-500/20 text-green-400 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",title:"Restart",children:B.includes(L.type)?"⏳":s.jsx(Po,{size:14})}):s.jsx("button",{onClick:()=>te(L),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:s.jsx(wt,{size:14})})]})]}),Q&&Q.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:Q.aiAgents.map(_e=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Mn(_e.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[_e.name," · ",yt(_e.status)]},_e.id))}),Q&&(Fe[Q.type]||[]).length>0&&c&&s.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[s.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:(Fe[Q.type]||[]).map(_e=>s.jsxs("button",{disabled:Qe===`${Q.type}.${_e.type}`,onClick:async()=>{const Oe=`${Q.type}.${_e.type}`;et(Oe);try{await c(r,"set_ide_extension",{ideType:Q.type,extensionType:_e.type,enabled:!_e.enabled}),Me(nt=>({...nt,[Q.type]:(nt[Q.type]||[]).map(Mt=>Mt.type===_e.type?{...Mt,enabled:!Mt.enabled}:Mt)}))}catch(nt){console.error("Extension toggle failed:",nt)}finally{et(null)}},className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-medium border transition-colors duration-150 cursor-pointer ${_e.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${_e.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),_e.name,s.jsx("span",{className:"text-[9px] font-normal",children:_e.enabled?"ON":"OFF"})]},_e.type))})]})]},L.id)})]}),de&&c&&s.jsx(ea,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:R,directories:ce,busy:je,error:Ie,confirmLabel:"Use this folder",onClose:()=>re(!1),onNavigate:L=>{V(L)},onConfirm:L=>{le(L),ie("__custom__"),re(!1)}}),ze&&s.jsx(li,{title:ze.title,description:ze.description,details:ze.details,workspaceOptions:ze.workspaceOptions,selectedWorkspaceKey:rt,onWorkspaceChange:L=>{Je.current=L,pt(L)},confirmLabel:ze.confirmLabel,busyLabel:ze.busyLabel,busy:xt,onConfirm:Ae,onCancel:()=>{He.current=null,Xe(null)}}),xe&&se&&s.jsx(ei,{activeConv:se,ides:[],isCreatingChat:!1,isRefreshingHistory:he,savedSessions:J,isSavedSessionsLoading:he,isResumingSavedSessionId:Ce,savedHistoryFilters:we,missingWorkspaceResumePath:Ge||null,onSavedHistoryFiltersChange:be,onClose:()=>fe(!1),onNewChat:()=>{G(""),fe(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Y(j)},onResumeSavedSession:L=>{if(!L.canResume||Ce)return;const Q=K(L);G(L.providerSessionId),ae(L),ee(L.providerSessionId),fe(!1),dt({type:L.providerType,workspaceId:Q.workspaceId,workspacePath:Q.workspacePath,useHome:Q.useHome,resumeSessionId:L.providerSessionId}).finally(()=>{ee(ge=>ge===L.providerSessionId?null:ge)})}})]})}const nc=[{id:"ide",label:"IDE",helper:"Open a graphical workspace and attach CDP"},{id:"cli",label:"CLI",helper:"Launch a terminal-first workspace on this machine"},{id:"acp",label:"ACP",helper:"Launch an ACP-backed workspace on this machine"}];function jw({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:o,actions:l,getIcon:c,initialCategory:d="ide",initialWorkspaceId:m,initialWorkspacePath:u,sendDaemonCommand:h,onOpenGitDialog:x}){var g;const[S,b]=i.useState(d);i.useEffect(()=>{b(d)},[d]);const p=i.useMemo(()=>({ide:n.length,cli:a.length,acp:o.length}),[n.length,a.length,o.length]);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:"Workspace Launcher"}),s.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[s.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:nc.map(v=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${S===v.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>b(v.id),children:[s.jsx("span",{children:v.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${S===v.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:p[v.id]})]},v.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(g=nc.find(v=>v.id===S))==null?void 0:g.helper})]}),S==="ide"&&s.jsx(Xa,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:c,actions:l,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),S==="cli"&&s.jsx(Xa,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:c,actions:l,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),S==="acp"&&s.jsx(Xa,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:o,getIcon:c,actions:l,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x})]})}function kw({onNicknameSynced:e}={}){var le,B,z,de,re,R,q,ce,Ne,je;const{id:t}=km(),r=As(),n=To(),{sendCommand:a}=jt(),o=Er(),l=Td(),c=ad(),d=c.ides||[],m=c.initialLoaded??!0,u=d.find(O=>O.id===t&&O.type==="adhdev-daemon"),h=d.some(O=>O.type==="adhdev-daemon"),x=t?(le=c.connectionRetryStatuses)==null?void 0:le[t]:void 0,S=!!(x!=null&&x.blocked),[b,p]=i.useState("workspace"),[g,v]=i.useState(null),f=i.useCallback((O,Ie)=>{v({daemonId:O,workspace:Ie})},[]),[T,I]=i.useState("ide"),k=i.useRef(null),[A,_]=i.useState(null),N=i.useRef("__home__"),[w,D]=i.useState("__home__"),[M,j]=i.useState(!1),W=i.useRef(null);i.useEffect(()=>{!t||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||o(t,{minFreshMs:3e4}).catch(()=>{})},[o,u,t]),i.useEffect(()=>{if(!t||!u||b!=="overview")return;const O=u.machine;(typeof(O==null?void 0:O.cpus)!="number"||typeof(O==null?void 0:O.totalMem)!="number"||typeof(O==null?void 0:O.arch)!="string"||typeof(O==null?void 0:O.release)!="string")&&l(t,{minFreshMs:3e4}).catch(()=>{})},[b,l,u,t]),Tb(t&&b==="overview"?[t]:[],{enabled:b==="overview",intervalMs:wf});const H=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},$=gv({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:W});i.useEffect(()=>it.onToast(Ie=>{c.setToasts(He=>{if(He.some(Je=>Je.message===Ie.message&&Ie.timestamp-Je.timestamp<3e3))return He;const Xe={id:Ie.id,message:Ie.message,type:Ie.type,timestamp:Ie.timestamp,targetKey:Ie.targetKey,actions:Ie.actions};return[...He.slice(-4),Xe]});const Le=Ie.duration||5e3;setTimeout(()=>c.setToasts(He=>He.filter(ze=>ze.id!==Ie.id)),Le)}),[c]);const C=(u==null?void 0:u.availableProviders)||[],y={};for(const O of C)y[O.type]=O.icon;const F=O=>y[O]||"",P=u?{id:u.id,hostname:Rc(u,{fallbackId:u.id}),platform:((B=u.machine)==null?void 0:B.platform)||"unknown",arch:((z=u.machine)==null?void 0:z.arch)||"",cpus:((de=u.machine)==null?void 0:de.cpus)||0,totalMem:((re=u.machine)==null?void 0:re.totalMem)||0,freeMem:(R=u.machine)==null?void 0:R.freeMem,availableMem:(q=u.machine)==null?void 0:q.availableMem,loadavg:(ce=u.machine)==null?void 0:ce.loadavg,uptime:(Ne=u.machine)==null?void 0:Ne.uptime,release:((je=u.machine)==null?void 0:je.release)||"",cdpConnected:!!u.cdpConnected,machineNickname:u.machineNickname||null,p2p:u.p2p?{screenshotActive:!1,...u.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:u.detectedIdes||[],workspaces:u.workspaces||[],defaultWorkspaceId:u.defaultWorkspaceId??u.activeWorkspaceId??null,defaultWorkspacePath:u.defaultWorkspacePath??u.activeWorkspacePath??null}:null,E=d.filter(O=>O.daemonId===t&&O.type!=="adhdev-daemon").filter(O=>!_r(O)&&!Fs(O)).map(O=>({id:O.id,sessionId:O.sessionId,type:O.type,version:O.version||"",instanceId:O.instanceId||"",status:O.status,workspace:O.workspace||null,terminals:O.terminals||0,aiAgents:mh(O.aiAgents||(O.agents||[]).map(Ie=>({id:Ie.name,name:Ie.name,status:Ie.status,version:Ie.version}))),activeChat:O.activeChat||null,chats:O.chats||[],childSessions:O.childSessions||[],cdpConnected:O.cdpConnected||!1,daemonId:t,lastMessageAt:O.lastMessageAt})),G=d.filter(O=>O.daemonId===t&&_r(O)).map(O=>({id:O.id,sessionId:O.sessionId,type:O.type,cliName:O.cliName||O.type,status:O.status,workspace:O.workspace||"",activeChat:O.activeChat||null,providerSessionId:O.providerSessionId,mode:O.mode,runtimeKey:O.runtimeKey,runtimeDisplayName:O.runtimeDisplayName,runtimeWorkspaceLabel:O.runtimeWorkspaceLabel,runtimeWriteOwner:O.runtimeWriteOwner||null,runtimeAttachedClients:O.runtimeAttachedClients||[],daemonId:t,lastMessageAt:O.lastMessageAt})),J=d.filter(O=>O.daemonId===t&&Fs(O)).map(O=>({id:O.id,sessionId:O.sessionId,type:O.type,acpName:O.cliName||O.type,status:O.status,workspace:O.workspace||"",activeChat:O.activeChat||null,providerSessionId:O.providerSessionId,daemonId:t,lastMessageAt:O.lastMessageAt})),ye=u?At(u,{fallbackId:t}):"",he="workspace",ne=n.state,ue=ne==null?void 0:ne.initialMachineTab,Se=ne==null?void 0:ne.initialWorkspaceCategory,ve=ne==null?void 0:ne.initialWorkspaceId,X=ne==null?void 0:ne.initialWorkspacePath,xe=ue==="ides"||ue==="clis"||ue==="acps"?"workspace":ue||he,fe=ue==="ides"?"ide":ue==="clis"?"cli":ue==="acps"?"acp":Se,we=[...E.map(O=>{var Ie;return{id:`ide:${O.type}:${O.workspace||""}`,label:((Ie=O.activeChat)==null?void 0:Ie.title)||O.type,kind:"ide",providerType:O.type,subtitle:O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:O.lastMessageAt||0}}),...G.map(O=>{var Ie;return{id:`cli:${O.type}:${O.workspace||""}`,label:((Ie=O.activeChat)==null?void 0:Ie.title)||O.cliName,kind:"cli",providerType:O.type,providerSessionId:O.providerSessionId,subtitle:O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:O.lastMessageAt||0}}),...J.map(O=>{var Ie;return{id:`acp:${O.type}:${O.workspace||""}`,label:((Ie=O.activeChat)==null?void 0:Ie.title)||O.acpName,kind:"acp",providerType:O.type,providerSessionId:O.providerSessionId,subtitle:Cs(O.summaryMetadata)||O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:O.lastMessageAt||0}})].sort((O,Ie)=>(Ie.lastLaunchedAt||0)-(O.lastLaunchedAt||0)),be=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(O=>({id:O.id,label:O.title||O.providerName||O.providerType,kind:O.kind,providerType:O.providerType,providerSessionId:O.providerSessionId,subtitle:Cs(O.summaryMetadata)||O.workspace||void 0,workspace:O.workspace,summaryMetadata:O.summaryMetadata,lastLaunchedAt:O.lastLaunchedAt})):we,Ce=i.useMemo(()=>{var Ie;const O=((Ie=c.connectionStates)==null?void 0:Ie[t||""])||void 0;return d.filter(Le=>Le.daemonId===t&&Le.type!=="adhdev-daemon").flatMap(Le=>ti(Le,{connectionStates:t&&O?{[t]:O}:void 0,defaultConnectionState:O})).filter(Le=>!(Le.transport==="pty"&&Le.mode==="terminal")).sort((Le,He)=>yo(He)-yo(Le))},[d,c.connectionStates,t]),ee=i.useCallback(O=>{const Ie=qd(O);Ie&&r(Zt(Ie))},[r]),me=i.useCallback(()=>{k.current&&(j(!0),k.current().finally(()=>{k.current=null,j(!1),_(null)}))},[]),ie=i.useCallback(O=>{if(!P)return;const{options:Ie,selectedKey:Le}=ks({machine:P,currentWorkspacePath:O.workspace}),He=async()=>{I(O.kind),p("workspace")};k.current=async()=>{const ze=Ie.find(rt=>rt.key===N.current),Xe=(ze==null?void 0:ze.workspacePath)??null,Je=(ze==null?void 0:ze.workspaceId)??null;if(O.kind==="ide"&&O.providerType){await $.handleLaunchIde(O.providerType,Xe?{workspace:Xe}:void 0);return}if((O.kind==="cli"||O.kind==="acp")&&O.providerType){await $.runLaunchCliCore({cliType:O.providerType,dir:Je?void 0:Xe||"",workspaceId:Je||void 0,model:O.kind==="acp"&&Dc(O.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:O.providerSessionId});return}await He()},N.current=Le,D(Le),_({title:O.kind==="ide"?gs("restart-ide",O.label):O.providerSessionId?Qo(O.label):gs("start-fresh",O.label),description:O.kind==="ide"?ys("restart-ide"):O.providerSessionId?Zo():ys("start-fresh"),confirmLabel:O.kind==="ide"?Ys("restart-ide"):O.providerSessionId?Pn(!0):Ys("start-fresh"),busyLabel:O.kind==="ide"?Xs("restart-ide"):O.providerSessionId?Xo(!0):Xs("start-fresh"),workspaceOptions:Ie,details:[{label:"Mode",value:O.kind.toUpperCase()},...O.providerType?[{label:"Provider",value:O.providerType}]:[]]})},[$,P]);if(i.useEffect(()=>{p(xe)},[he,xe,t]),i.useEffect(()=>{fe&&I(fe)},[fe,t]),!P)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:H,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 pe=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_t,{size:14})," Workspace"]}),count:E.length+G.length+J.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(Kn,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(tp,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Jm,{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:H,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[$.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:$.nicknameInput,onChange:O=>$.setNicknameInput(O.target.value),onKeyDown:O=>{O.key==="Enter"&&$.handleSaveNickname(),O.key==="Escape"&&$.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:$.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>$.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{$.setEditingNickname(!0),$.setNicknameInput(P.machineNickname||"")},title:"Click to set nickname",children:ye}),S?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:[P.platform," · ",P.arch]}),s.jsxs("span",{children:[P.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),P.p2p.available&&s.jsxs("span",{children:["P2P ",P.p2p.state==="connected"?"connected":P.p2p.state]}),P.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:P.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:pe.map(O=>s.jsxs("button",{onClick:()=>p(O.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${b===O.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[O.label,O.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${b===O.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:O.count})]},O.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:[b==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(gw,{machineEntry:u,providers:C,recentLaunches:be,currentConversations:Ce,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",Ud(u))}catch{}},onOpenRecent:ie,onOpenConversation:ee}),s.jsx(jw,{machine:P,machineId:t,providers:C,ideSessions:E,cliSessions:G,acpSessions:J,actions:$,getIcon:F,initialCategory:T,initialWorkspaceId:ve,initialWorkspacePath:X,sendDaemonCommand:a,onOpenGitDialog:f})]}),b==="providers"&&s.jsx(Tv,{machineId:t,providers:C,sendDaemonCommand:a}),b==="overview"&&s.jsx(yv,{machineId:t,machine:P,ideSessions:E,cliSessions:G,acpSessions:J,actions:$,sendDaemonCommand:a}),b==="session-host"&&s.jsx(xw,{machineId:t,cliSessions:G,sendDaemonCommand:a}),b==="logs"&&s.jsx(cw,{machineId:t,sendDaemonCommand:a})]})})}),$.launchPick&&P&&s.jsx(bw,{machine:P,launchPick:$.launchPick,actions:$}),A&&s.jsx(li,{title:A.title,description:A.description,details:A.details,workspaceOptions:A.workspaceOptions,selectedWorkspaceKey:w,onWorkspaceChange:O=>{N.current=O,D(O)},confirmLabel:A.confirmLabel,busyLabel:A.busyLabel,busy:M,onConfirm:me,onCancel:()=>{k.current=null,_(null)}}),g&&s.jsx(Pu,{daemonId:g.daemonId,workspace:g.workspace,onClose:()=>v(null)}),s.jsx(fd,{toasts:c.toasts||[],onDismiss:O=>c.setToasts(Ie=>Ie.filter(Le=>Le.id!==O)),onClickToast:O=>{O.targetKey&&r(Zt(O.targetKey))}}),s.jsx("style",{children:`
|
|
89
|
+
`)}function rw(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function nw(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function aw({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:l,searchQuery:c,daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:h}){const x=Dv(n,o),S=Bv(e,c),b=Wv(t,c),p=Kv(x,c),g=Hv(a,c),v=rw(S,l),f=l==="all"?b:[],C=nw(p,l),T=l==="issues"?[]:g,k=Uv({daemonLogs:S,daemonRawLines:b,trace:p,webEvents:g}),A=Qv({daemonLogs:v,daemonRawLines:f,trace:C,webEvents:T}),_=ew(A),N=Gv({daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:h,daemonLogKind:r,daemonLogsCount:S.length,daemonRawLineCount:b.length,traceCount:p.length,webEventCount:g.length});return{filteredDaemonLogs:S,filteredDaemonRawLines:b,filteredTraceEntries:p,filteredWebEvents:g,visibleDaemonLogs:v,visibleDaemonRawLines:f,visibleTraceEntries:C,visibleWebEvents:T,quickFilterCounts:k,diagnosticEvents:A,diagnosticsSummary:_,sourceStates:N}}function ow(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Eu(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function So(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 Ua(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 hi(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function iw({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${So(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Eu(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:hi(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 lw({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:l,onCopyVisible:c,onToggleAutoRefresh:d,onRefresh:m,onClear:u}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(h=>s.jsx("button",{type:"button",onClick:()=>a(h.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===h.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:h.label},h.id))}),s.jsx("input",{value:r,onChange:h=>o(h.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:l,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:d,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:m,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function cw({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:Rv.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 dw({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:l,traceFetchError:c}){var u,h;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((h=e.latestIssue)==null?void 0:h.severity)==="warn"?"warning":"good",m=l||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 ${Ua(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 ${Ua(d)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[hi(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:Eu(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 ${Ua(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:l||c?"Needs attention":o?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",ow(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(x=>s.jsxs("div",{children:[x.label,": ",x.status]},x.id))})]})]})}function uw({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()," · ",hi(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function mw({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:l,visibleWebEvents:c,quickFilter:d,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(u=>({...u,timeline:!u.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(u=>s.jsx(iw,{event:u},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,daemon:!u.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${o.length} visible raw line(s) from file fallback`:`${a.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&a.length===0&&o.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&o.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:d==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&a.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&o.map((u,h)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${h}`)),e.daemonLogKind!=="text"&&a.map((u,h)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${So(u.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(u.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:u.level==="error"?"ERR":u.level==="warn"?"WRN":u.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:u.message})]},`log-${h}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,trace:!u.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[l.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&&l.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&l.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&l.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."}),l.map(u=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${So(u.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.level.toUpperCase()}),s.jsxs("span",{children:[u.category,".",u.stage]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Js(u.payload,360)||"No payload"})]},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,web:!u.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[c.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:m.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),c.map(u=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.kind}),u.topic&&s.jsxs("span",{children:["topic=",u.topic]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Js(u.payload,360)||"No payload"})]},u.id))]})]})]})}function pw({machineId:e,sendDaemonCommand:t}){const r=Vv({machineId:e,sendDaemonCommand:t}),[n,a]=i.useState("info"),[o,l]=i.useState(""),[c,d]=i.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=i.useRef(null),u=i.useRef(!1),h=i.useMemo(()=>aw({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]);i.useEffect(()=>{if(r.autoRefresh&&h.diagnosticEvents.length>0){const b=u.current?"smooth":"instant";setTimeout(()=>{var p;(p=m.current)==null||p.scrollIntoView({behavior:b}),u.current=!0},50)}},[h.diagnosticEvents.length,r.autoRefresh]);const x=i.useCallback(async()=>{var p;const b=zv({daemonLogs:h.visibleDaemonLogs,daemonRawLines:h.visibleDaemonRawLines,trace:h.visibleTraceEntries,webEvents:h.visibleWebEvents});if(!b.trim()){it.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(b)),it.showToast("Copied visible logs to clipboard.","success")}catch(g){it.showToast(g instanceof Error?g.message:"Could not copy visible logs","warning")}},[h.visibleDaemonLogs,h.visibleDaemonRawLines,h.visibleTraceEntries,h.visibleWebEvents]),S=i.useCallback(async()=>{var p;const b=sw({events:h.diagnosticEvents,summary:h.diagnosticsSummary,sources:h.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(b)),it.showToast("Copied diagnostic bundle to clipboard.","success")}catch(g){it.showToast(g instanceof Error?g.message:"Could not copy diagnostic bundle","warning")}},[h.diagnosticEvents,h.diagnosticsSummary,h.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(lw,{quickFilter:n,quickFilterCounts:h.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:l,onCopyDiagnostics:()=>{S()},onCopyVisible:()=>{x()},onToggleAutoRefresh:()=>r.setAutoRefresh(b=>!b),onRefresh:r.refresh,onClear:r.clear}),s.jsx(cw,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(dw,{diagnosticsSummary:h.diagnosticsSummary,diagnosticEventsCount:h.diagnosticEvents.length,sourceStates:h.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(uw,{patterns:h.diagnosticsSummary.repeatedPatterns}),s.jsx(mw,{streams:r,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:h.diagnosticEvents,visibleDaemonLogs:h.visibleDaemonLogs,visibleDaemonRawLines:h.visibleDaemonRawLines,visibleTraceEntries:h.visibleTraceEntries,visibleWebEvents:h.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:m})]})}function hw(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 $u(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 fw(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const l=String((o==null?void 0:o.lifecycle)||"").trim(),c=$u((o==null?void 0:o.meta)||void 0),d=((a=o==null?void 0:o.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(l)?t.push(o):(l==="stopped"||l==="failed")&&(d||c)?r.push(o):n.push(o)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function xw(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function za(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 Va(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Ga(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function nc(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 bw(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function gw(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 yw(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 vw({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=i.useState(""),[o,l]=i.useState(null),[c,d]=i.useState(!1),m=Ab(e,{enabled:!!e,includeSessions:!0,limit:qi,intervalMs:Cf}),u=m.diagnostics,h=m.loading,x=m.applyDiagnostics,S=i.useMemo(()=>hw({diagnostics:u,loading:h,refreshing:c,error:n}),[u,h,c,n]),b=i.useMemo(()=>new Map(t.map(M=>[M.sessionId||M.id,M])),[t]),p=i.useCallback(async()=>{if(e){d(!0);try{const M=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:qi}),j=Va(M);if(!(j!=null&&j.success))throw new Error((j==null?void 0:j.error)||"Could not load hosted runtime diagnostics");x(j.diagnostics||j.result||null),a("")}catch(M){const j=M instanceof Error?M.message:"Could not load hosted runtime diagnostics";a(j)}finally{d(!1)}}},[x,e,r]);i.useEffect(()=>{!e||u||h||c||p()},[u,h,e,p,c]);const g=i.useCallback(async(M,j)=>{const W=`${M}:${j.sessionId}`;if(!(M==="session_host_stop_session"&&!window.confirm(`Stop ${j.displayName}?
|
|
90
|
+
This will terminate the hosted runtime.`))){l(W);try{const H=await r(e,M,{sessionId:j.sessionId}),$=Va(H);if(!($!=null&&$.success))throw new Error(($==null?void 0:$.error)||"Session host action failed");const I=M==="session_host_resume_session"?"resumed":M==="session_host_restart_session"?"restarted":"stopped";it.showToast(`Session host ${I}: ${j.displayName}`,"success"),await p()}catch(H){const $=H instanceof Error?H.message:"Session host action failed";it.showToast($,"warning"),a($)}finally{l(H=>H===W?null:H)}}},[e,p,r]),v=i.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
91
|
+
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){l("session_host_prune_duplicate_sessions");try{const j=await r(e,"session_host_prune_duplicate_sessions",{}),W=Va(j);if(!(W!=null&&W.success))throw new Error((W==null?void 0:W.error)||"Duplicate prune failed");const H=W.result||{},$=Array.isArray(H.prunedSessionIds)?H.prunedSessionIds.length:0,I=typeof H.duplicateGroupCount=="number"?H.duplicateGroupCount:0;it.showToast(`Pruned ${$} duplicate runtime(s) across ${I} group(s)`,"success"),await p()}catch(j){const W=j instanceof Error?j.message:"Duplicate prune failed";it.showToast(W,"warning"),a(W)}finally{l(j=>j==="session_host_prune_duplicate_sessions"?null:j)}}},[e,p,r]),f=i.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((M,j)=>(j.lastActivityAt||0)-(M.lastActivityAt||0)),[u==null?void 0:u.sessions]),C=i.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:fw(f),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,f]),T=C.liveRuntimes,k=C.recoverySnapshots,A=C.inactiveRecords,_=i.useMemo(()=>yw(T),[T]),N=i.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),w=i.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(M=>M.level==="warn"||M.level==="error")||null,[u==null?void 0:u.recentLogs]),D=(M,j)=>{var G;const W=o===`session_host_resume_session:${M.sessionId}`,H=o===`session_host_restart_session:${M.sessionId}`,$=o===`session_host_stop_session:${M.sessionId}`,I=$u(M.meta),y=b.get(M.sessionId),F=M.attachedClients.length===1?"1 client":`${M.attachedClients.length} clients`,P=j==="recovery"?"Recover":"Resume",E=xw(j);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:M.displayName||(y==null?void 0:y.cliName)||M.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${gw(M.lifecycle)}`,children:M.lifecycle}),I&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:I})]}),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:M.workspaceLabel||(y==null?void 0:y.runtimeWorkspaceLabel)||M.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:M.runtimeKey}),M.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",M.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((G=M.writeOwner)==null?void 0:G.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:bw(M.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(gc,{size:11})," ",F]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",nc(M.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",E]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[j==="recovery"&&(M.lifecycle==="interrupted"||M.lifecycle==="failed"||M.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{g("session_host_resume_session",M)},children:W?`${P}ing…`:P}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{g("session_host_restart_session",M)},children:H?"Restarting…":"Restart"}),j==="live"&&(M.lifecycle==="running"||M.lifecycle==="starting"||M.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:()=>{g("session_host_stop_session",M)},children:$?"Stopping…":"Stop"})]})]})},M.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:_x()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[_>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{v()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${_})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${S.toneClass}`,children:S.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:h||c,children:[s.jsx(Rr,{size:13}),h||c?"Refreshing…":"Refresh"]})]})]}),n&&!u&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(Ar,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children: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:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:nc(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Ga(u.hostStartedAt)})]})]}),w&&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(Ar,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:w.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Ga(w.timestamp),w.sessionId?` · ${w.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(Ro,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:za("live")}),T.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:T.map(M=>D(M,"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:za("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(M=>D(M,"recovery"))})]}),A.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:za("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:A.map(M=>D(M,"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"}),N.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:N.map(M=>{var W;const j=f.find(H=>H.sessionId===M.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:(j==null?void 0:j.displayName)||((W=b.get(M.sessionId))==null?void 0:W.cliName)||M.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[M.action,M.lifecycle?` · ${M.lifecycle}`:"",M.detail?` · ${M.detail}`:"",M.error?` · ${M.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${M.success===!1?"text-red-300":"text-text-secondary"}`,children:Ga(M.timestamp)})]},`${M.sessionId}:${M.timestamp}:${M.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function ww({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 qa({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 Ya({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 jw({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:l}){const c=n.slice(0,6),d=r.slice(0,4),m="0.9.81",u=Ud(e),h=$s(e,m),x=Sr(e,h),S=u==="preview"?"Update to preview":"Update daemon";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(qa,{icon:s.jsx(es,{size:13}),children:"Current Chats"}),s.jsx(Ya,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(b=>{const p=yo(b);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:()=>l(b),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:ut(b)}),p>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Un(p)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Is(b)})]},b.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(qa,{icon:s.jsx(jc,{size:13}),children:"Recent Launches"}),s.jsx(Ya,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(b=>{const{metaText:p,updatedLabel:g}=su(b);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(b),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:b.label}),g&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:g})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:p})]},b.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(qa,{icon:s.jsx(Ar,{size:13}),children:"Daemon Update"}),s.jsx(Ya,{className:"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:x?"Daemon update required":"Version mismatch detected"}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[x?"This machine is on an incompatible daemon version. Update it before starting more sessions.":u==="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.",h&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",h,u?` (${u})`:""]})]}),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(Rr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:S})]})]})})]})]})}function kw(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function Sw({machine:e,selectedWorkspace:t,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:o,onCustomPathChange:l,onOpenBrowseDialog:c}){return s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[s.jsx("select",{value:t,onChange:d=>{const m=d.target.value;if(o(m),m==="__custom__"&&a){c();return}m!=="__custom__"&&l("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(e.workspaces||[]).length>0?s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(e.workspaces||[]).map(d=>s.jsxs("option",{value:d.id,children:[d.id===e.defaultWorkspaceId?"⭐ ":"",Vn(d.path,d.label)]},d.id)),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]})}),t==="__custom__"&&(a?s.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:c,children:"Select workspace…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:n,onChange:d=>l(d.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:t==="__custom__"?r?s.jsx("span",{className:"font-mono truncate block",title:r,children:r}):a?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":r?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:t===e.defaultWorkspaceId?"Default workspace":"Selected workspace"}),s.jsx("span",{className:"font-mono truncate block",title:r,children:r})]}):"No workspace selected. This launches in the home directory."})]})}const Nw={ide:{label:"IDE",plural:"IDEs",accent:"border-blue-500/[0.12]"},cli:{label:"CLI",plural:"CLIs",accent:"border-violet-500/[0.12]"},acp:{label:"ACP Agent",plural:"ACP agents",accent:"border-emerald-500/[0.12]"}};function un(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Xa({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:o,actions:l,sendDaemonCommand:c,initialWorkspaceId:d,initialWorkspacePath:m,onOpenGitDialog:u}){const h=As(),{handleLaunchIde:x,handleStopCli:S,handleRestartIde:b,handleStopIde:p,handleDetectIdes:g,launchingIde:v,launchingAgentType:f,addLog:C}=l,[T,k]=i.useState(null),A=i.useCallback(L=>{L&&h(Zt(L))},[h]),_=Nw[e],N=e==="ide",w=e==="acp",D=i.useMemo(()=>n.filter(L=>Ts(L,e)),[e,n]),M=i.useMemo(()=>new Map(D.map(L=>[L.type,L.displayName||L.type])),[D]),[j,W]=i.useState(""),[H,$]=i.useState(""),[I,y]=i.useState([]),[F,P]=i.useState(""),[E,G]=i.useState(""),[J,ye]=i.useState([]),[he,ne]=i.useState(!1),[ue,Se]=i.useState(!1),[ve,X]=i.useState(""),[xe,fe]=i.useState(!1),[we,be]=i.useState(()=>Ct()),[Ce,ee]=i.useState(null),[me,ie]=i.useState(m?"__custom__":d||t.defaultWorkspaceId||""),[pe,le]=i.useState(m||""),[B,z]=i.useState([]),[de,re]=i.useState(!1),[R,q]=i.useState(""),[ce,Ne]=i.useState([]),[je,O]=i.useState(!1),[Ie,Le]=i.useState(""),He=i.useRef(null),[ze,Xe]=i.useState(null),Je=i.useRef("__home__"),[rt,pt]=i.useState("__home__"),[xt,vt]=i.useState(!1),Te=i.useRef(0),Ve=B.filter(L=>!a.some(Q=>Q.type===L&&yt(Q.status)!=="stopped")),tt=i.useRef({});i.useEffect(()=>{t.defaultWorkspaceId&&!me&&ie(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),i.useEffect(()=>{if(m){ie("__custom__"),le(m);return}d&&(ie(d),le(""))},[d,m]),i.useEffect(()=>{N||j&&(D.some(L=>L.type===j)||(W(""),G("")))},[D,N,j]);const Ge=(()=>{if(me==="__custom__")return pe.trim();if(!me)return"";const L=(t.workspaces||[]).find(Q=>Q.id===me);return(L==null?void 0:L.path)||""})(),ot=i.useCallback(L=>{const Q=tt.current[L];Q&&(clearTimeout(Q),delete tt.current[L]),z(ge=>ge.includes(L)?ge.filter(Be=>Be!==L):ge)},[]),U=i.useRef(new Set),V=i.useCallback(async L=>{if(c){O(!0),Le("");try{const Q=await Zn(c,r,L);q(Q.path),le(Q.path),Ne(Q.directories)}catch(Q){Le(Q instanceof Error?Q.message:"Could not load folder")}finally{O(!1)}}},[r,c]),Z=i.useCallback(()=>{if(!c)return;ie("__custom__"),re(!0);const L=a.map(ge=>ge.workspace),Q=Qn(t.platform,Jn(pe.trim(),Ge,m,L,t.defaultWorkspacePath,(t.workspaces||[]).map(ge=>ge.path)));V(Q)},[pe,m,V,t.defaultWorkspacePath,t.platform,t.workspaces,a,Ge,c]),ae=i.useCallback(L=>{const Q=String(L.workspace||"").trim();if(!Q)return;const ge=(t.workspaces||[]).find(Be=>un(Be.path)===un(Q));if(ge){ie(ge.id),le("");return}ie("__custom__"),le(Q)},[t.workspaces]),K=i.useCallback(L=>{const Q=String(L.workspace||"").trim();if(!Q)return{workspaceId:null,workspacePath:"",useHome:!0};const ge=(t.workspaces||[]).find(Be=>un(Be.path)===un(Q));return ge?{workspaceId:ge.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:Q,useHome:!1}},[t.workspaces]),Y=i.useCallback(async L=>{if(!c||!L||e!=="cli"){ye([]),ne(!1),Se(!1),X("");return}const Q=Te.current+1;Te.current=Q,ne(!0),X("");try{const ge=await c(r,"list_saved_sessions",{providerType:L,kind:"cli",limit:30});if(Te.current!==Q)return;const Be=(ge==null?void 0:ge.result)??ge;ye(Array.isArray(Be==null?void 0:Be.sessions)?Be.sessions:[])}catch(ge){if(Te.current!==Q)return;ye([]),X(ge instanceof Error?ge.message:"Could not load saved sessions")}finally{Te.current===Q&&(ne(!1),Se(!0))}},[e,r,c]),se=i.useMemo(()=>{if(e!=="cli"||!j)return null;const L=M.get(j)||j;return{routeId:r,daemonId:r,providerSessionId:E||void 0,transport:"pty",mode:"chat",agentName:L,agentType:j,status:"idle",title:L,messages:[],ideType:j,workspaceName:Ge,workspacePath:Ge,displayPrimary:L,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${j}`}},[e,r,M,Ge,E,j]),oe=i.useCallback(L=>{if(e==="ide"||!L){y([]);return}y(jo(r,L))},[e,r]),ke=i.useCallback((L,Q)=>{e==="ide"||!L||(Uy(r,L,Q),y(jo(r,L)))},[e,r]);i.useEffect(()=>{Te.current+=1,G(""),oe(j),Se(!1),ye([]),X(""),ne(!1)},[e,oe,Y,j]);const Pe=i.useMemo(()=>J.find(L=>L.providerSessionId===E)||null,[J,E]);i.useEffect(()=>{if(!E)return;const L=J.find(Q=>Q.providerSessionId===E);L!=null&&L.canResume||G("")},[J,E]);const Ee=i.useCallback((L,Q)=>{He.current=Q,Je.current=L.selectedWorkspaceKey||"__home__",pt(L.selectedWorkspaceKey||"__home__"),Xe(L)},[]),Ae=i.useCallback(()=>{He.current&&(vt(!0),He.current().finally(()=>{He.current=null,vt(!1),Xe(null)}))},[]),$e=i.useCallback(L=>{if(!L)return;z(ge=>ge.includes(L)?ge:[...ge,L]);const Q=tt.current[L];Q&&clearTimeout(Q),tt.current[L]=setTimeout(()=>{z(ge=>ge.includes(L)?ge.filter(Be=>Be!==L):ge),delete tt.current[L]},2e4)},[]);i.useEffect(()=>{for(const Q of a)yt(Q.status)!=="stopped"&&(B.includes(Q.type)&&!U.current.has(Q.type)&&(U.current.add(Q.type),C("info",`${M.get(Q.type)||Q.type} launched`,!0)),ot(Q.type));const L=new Set(a.filter(Q=>yt(Q.status)!=="stopped").map(Q=>Q.type));U.current.forEach(Q=>{!B.includes(Q)&&!L.has(Q)&&U.current.delete(Q)})},[C,ot,a,B,M]),i.useEffect(()=>()=>{Object.values(tt.current).forEach(clearTimeout),tt.current={}},[]);const[Fe,Me]=i.useState({}),[Qe,et]=i.useState(null);i.useEffect(()=>{if(!N||!r||!c)return;(async()=>{try{const Q=await c(r,"get_ide_extensions",{}),ge=(Q==null?void 0:Q.result)||Q;ge!=null&&ge.success&&(ge!=null&&ge.ideExtensions)&&Me(ge.ideExtensions)}catch{}})()},[N,r,c]);const bt=L=>N?ct(L.type):e==="cli"?L.cliName:L.acpName,gt=N?t.detectedIdes||[]:[],dt=i.useCallback(async L=>{const Q=(L==null?void 0:L.type)||j,ge=(L==null?void 0:L.workspacePath)??Ge;if(N){await x(Q,ge?{workspace:ge}:void 0)&&$e(Q);return}const Be=await l.runLaunchCliCore({cliType:Q,dir:L!=null&&L.workspaceId?void 0:ge||void 0,workspaceId:(L==null?void 0:L.workspaceId)||void 0,useHome:(L==null?void 0:L.useHome)||!(L!=null&&L.workspaceId)&&!ge,argsStr:(L==null?void 0:L.argsStr)??(H||void 0),model:(L==null?void 0:L.model)??(w&&F||void 0),resumeSessionId:(L==null?void 0:L.resumeSessionId)||!w&&e==="cli"&&Q===j&&E||void 0});if(Be.success||Be.pending){const _e=(L==null?void 0:L.argsStr)??H;!N&&(_e!=null&&_e.trim())&&(xu(r,Q,_e),oe(Q)),$e(Q),Be.success&&Be.sessionId&&A(Be.sessionId)}},[l,x,w,N,H,F,oe,$e,r,A,Ge,E,j]),ht=hd(N?"ide":w?"acp":"cli",!N&&!w&&!!E),Ue=fd(N?"ide":w?"acp":"cli",!N&&!w&&!!E),Kt=()=>{var _e;const L=N?ct(j):M.get(j)||j,Q=!N&&!w&&!!E,{options:ge,selectedKey:Be}=ks({machine:t,currentWorkspaceId:me&&me!=="__custom__"?me:null,currentWorkspacePath:Ge});Ee({title:Q?Qo(L):gs("start-fresh",L),description:Q?Zo():ys("start-fresh"),confirmLabel:ht,busyLabel:Ue,workspaceOptions:ge,selectedWorkspaceKey:Be,details:[{label:"Mode",value:_.label},{label:"Provider",value:L},...!N&&e==="cli"&&E?[{label:"Resume",value:((_e=J.find(Oe=>Oe.providerSessionId===E))==null?void 0:_e.title)||E}]:[],...!N&&H.trim()?[{label:"Arguments",value:H.trim()}]:[],...w&&F.trim()?[{label:"Model",value:F.trim()}]:[]]},async()=>{const Oe=ge.find(nt=>nt.key===Je.current);Oe!=null&&Oe.workspaceId?(ie(Oe.workspaceId),le("")):Oe!=null&&Oe.workspacePath?(ie("__custom__"),le(Oe.workspacePath)):(ie(""),le("")),await dt({workspaceId:(Oe==null?void 0:Oe.workspaceId)??null,workspacePath:(Oe==null?void 0:Oe.workspacePath)??"",useHome:!(Oe!=null&&Oe.workspaceId)&&!(Oe!=null&&Oe.workspacePath)})})},te=L=>{N?p(L):S(L.type,L.workspace,L.id)},De=i.useCallback(async(L,Q,ge=!1)=>{if(L.mode===Q){ge&&L.sessionId&&A(L.sessionId);return}if(!c||!L.sessionId){ge&&L.sessionId&&A(L.sessionId);return}try{await c(r,"set_cli_view_mode",{targetSessionId:L.sessionId,cliType:L.type,mode:Q}),ge&&A(L.sessionId)}catch(Be){const _e=Dd(Be);Pd(Be)?console.warn(_e?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Be instanceof Error?Be.message:String(Be)):console.error("Failed to switch CLI view mode:",Be)}},[r,A,c]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${_.accent} relative overflow-hidden`,children:[s.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",_.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:N?gt.length>0?gt.map(L=>{const Q=a.find(nt=>(nt.type||"").toLowerCase()===(L.type||"").toLowerCase()&&yt(nt.status)!=="stopped"),ge=L.running||!!Q,Be=!!Q&&Q.cdpConnected,_e=B.includes(L.type||L.id||""),Oe=j===(L.type||"");return s.jsxs("button",{onClick:()=>{if(Be&&Q){const nt=Q.sessionId;nt?h(Zt(nt),{state:{openRemoteForTabKey:nt}}):h("/dashboard",{state:{openRemoteForTabKey:Q.id}});return}_e||W(nt=>nt===(L.type||"")?"":L.type||"")},disabled:!!v||_e,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Be?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Oe?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:v&&v!==L.type?.4:1},children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:o(L.type)}),ge&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Be?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:L.name||ct(L.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Be?"text-green-400":_e?"text-orange-400":Oe?"text-accent-primary":"text-text-muted"}`,children:Be?"Open Session":_e?"Starting...":Oe?"Configure":"Select"})]})]},L.type)}):s.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",s.jsxs("button",{onClick:g,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[s.jsx(ep,{size:14})," Scan System"]})]}):D.length>0?D.map(L=>{const Q=j===L.type,ge=B.includes(L.type),_e=!!a.find(Oe=>Oe.type===L.type&&yt(Oe.status)!=="stopped");return s.jsxs("button",{onClick:()=>W(Oe=>Oe===L.type?"":L.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Q?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:L.icon}),_e&&s.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:L.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ge?"text-orange-400":Q?"text-accent-primary":"text-text-muted"}`,children:ge?"Starting...":Q?"Configure":"Select"})]})]},L.type)}):s.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),j&&(N?gt.find(L=>L.type===j):D.find(L=>L.type===j))&&s.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[s.jsx("span",{children:"Launch Settings"}),s.jsx("span",{className:"text-accent-primary font-bold",children:N?ct(j):M.get(j)||j})]}),s.jsx(Sw,{machine:t,selectedWorkspace:me,resolvedWorkspacePath:Ge,customPath:pe,canBrowse:!!c,onWorkspaceChange:ie,onCustomPathChange:le,onOpenBrowseDialog:Z}),!N&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&e==="cli"&&s.jsx(gu,{busy:!!f||!!v||B.includes(j),savedSessionsLoading:he,savedSessionsError:ve,savedSessionsLoaded:ue,savedSessionsCount:J.length,selectedSession:Pe,onRefresh:()=>void Y(j),onOpenHistory:()=>{j&&(fe(!0),bu({hasLoadedInitialResults:ue,isLoading:he})&&Y(j))},onClearSelection:()=>G("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[w&&s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),s.jsx("input",{type:"text",placeholder:"Leave empty for default",value:F,onChange:L=>P(L.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),s.jsx("input",{type:"text",placeholder:"Optional flags...",value:H,onChange:L=>$(L.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),I.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:I.map(L=>s.jsxs("div",{className:"inline-flex max-w-full items-stretch overflow-hidden rounded-md border border-[#ffffff1a] bg-bg-tertiary text-xs text-text-secondary transition-colors hover:border-accent-primary/40 hover:text-text-primary",title:L,children:[s.jsx("button",{type:"button",className:"min-w-0 max-w-[220px] truncate px-2.5 py-1.5 text-left",onClick:()=>$(L),children:L}),s.jsx("button",{type:"button",className:"flex items-center justify-center border-l border-[#ffffff1a] px-1.5 text-text-muted transition-colors hover:bg-status-error/10 hover:text-status-error focus:outline-none focus:ring-1 focus:ring-status-error/50",onClick:()=>ke(j,L),"aria-label":`Remove startup arguments: ${L}`,title:"Remove startup arguments",children:s.jsx(wt,{size:12})})]},L))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:Kt,disabled:!!f||!!v||B.includes(j),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:f===j||v===j?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+B.filter(L=>!a.some(Q=>Q.type===L&&yt(Q.status)!=="stopped")).length,")"]}),a.length===0&&Ve.length===0?s.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",_.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ve.map(L=>s.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:o(L)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:N?ct(L):M.get(L)||L}),s.jsx("div",{className:"text-[11px] text-text-muted",children:f===L?"Launching process...":"Waiting for process and session to register..."})]})]}),s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${L}`)),a.map(L=>{const Q=N?L:null,ge=!N&&!w?L:null,Be=yt(L.status);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 justify-between items-center mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:o(L.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[bt(L),(Q==null?void 0:Q.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",Q.version]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted flex min-w-0 flex-wrap items-center gap-2",children:[s.jsx("span",{className:"truncate",children:L.workspace||"—"}),u&&L.git&&L.workspace?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:_e=>{_e.stopPropagation(),u(L.daemonId??r,L.workspace)},children:s.jsx(qs,{git:L.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(qs,{git:L.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(ge==null?void 0:ge.mode)&&s.jsx("span",{className:ge.mode==="chat"?"text-violet-400":"text-text-secondary",children:ge.mode==="chat"?"Chat view":"Terminal view"})]}),ge&&(ge.runtimeKey||ge.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ge.runtimeKey&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),s.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",ge.runtimeKey]}),s.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var _e;(_e=navigator.clipboard)==null||_e.writeText(`adhdev attach ${ge.runtimeKey}`),k(ge.runtimeKey||null),window.setTimeout(()=>{k(Oe=>Oe===ge.runtimeKey?null:Oe)},1200)},children:T===ge.runtimeKey?"Copied":"Copy"})]}),ge.runtimeWriteOwner&&s.jsx("span",{style:{color:ge.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ge.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:kw(ge.runtimeWriteOwner)})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Be==="stopped"?"bg-red-500/[0.08] text-red-500":Be==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Be}),N&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const _e=L.sessionId;if(_e){h(Zt(_e),{state:{openRemoteForTabKey:_e}});return}h("/dashboard",{state:{openRemoteForTabKey:L.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:s.jsx(_t,{size:13})}),s.jsx("button",{onClick:()=>{const _e=L.workspace||"",{options:Oe,selectedKey:nt}=ks({machine:t,currentWorkspacePath:_e});Ee({title:gs("restart-ide",ct(L.type)),description:ys("restart-ide"),confirmLabel:Ys("restart-ide"),busyLabel:Xs("restart-ide"),workspaceOptions:Oe,selectedWorkspaceKey:nt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:ct(L.type)}]},async()=>{const Mt=Oe.find(ss=>ss.key===Je.current),ft=(Mt==null?void 0:Mt.workspacePath)??"";if(ft&&ft!==_e){await dt({type:L.type,workspacePath:ft});return}await b(L)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:s.jsx(Rr,{size:14})})]}),w&&s.jsx("button",{onClick:()=>{const _e=L.sessionId;_e&&A(_e)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!L.sessionId,children:s.jsx(es,{size:14})}),ge&&Be!=="stopped"&&s.jsxs(s.Fragment,{children:[ge.mode&&s.jsx(Yo,{mode:ge.mode,onChange:_e=>void De(ge,_e,!1),compact:!0}),s.jsx("button",{onClick:()=>{const _e=L.sessionId;_e&&A(_e)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!L.sessionId,children:ge.mode==="chat"?s.jsx(es,{size:14}):s.jsx(_t,{size:13})})]}),Be==="stopped"?s.jsx("button",{onClick:()=>{const _e=L.workspace||"",Oe=N?ct(L.type):bt(L),{options:nt,selectedKey:Mt}=ks({machine:t,currentWorkspacePath:_e});Ee({title:gs("restart-stopped",Oe),description:ys("restart-stopped"),confirmLabel:Ys("restart-stopped"),busyLabel:Xs("restart-stopped"),workspaceOptions:nt,selectedWorkspaceKey:Mt,details:[{label:"Mode",value:_.label},{label:"Provider",value:Oe}]},async()=>{const ft=nt.find(ss=>ss.key===Je.current);await dt({type:L.type,workspaceId:(ft==null?void 0:ft.workspaceId)??null,workspacePath:(ft==null?void 0:ft.workspacePath)??"",useHome:!(ft!=null&&ft.workspaceId)&&!(ft!=null&&ft.workspacePath)})})},disabled:B.includes(L.type),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-green-500/20 text-green-400 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",title:"Restart",children:B.includes(L.type)?"⏳":s.jsx(Po,{size:14})}):s.jsx("button",{onClick:()=>te(L),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:s.jsx(wt,{size:14})})]})]}),Q&&Q.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:Q.aiAgents.map(_e=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Mn(_e.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[_e.name," · ",yt(_e.status)]},_e.id))}),Q&&(Fe[Q.type]||[]).length>0&&c&&s.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[s.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:(Fe[Q.type]||[]).map(_e=>s.jsxs("button",{disabled:Qe===`${Q.type}.${_e.type}`,onClick:async()=>{const Oe=`${Q.type}.${_e.type}`;et(Oe);try{await c(r,"set_ide_extension",{ideType:Q.type,extensionType:_e.type,enabled:!_e.enabled}),Me(nt=>({...nt,[Q.type]:(nt[Q.type]||[]).map(Mt=>Mt.type===_e.type?{...Mt,enabled:!Mt.enabled}:Mt)}))}catch(nt){console.error("Extension toggle failed:",nt)}finally{et(null)}},className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-medium border transition-colors duration-150 cursor-pointer ${_e.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${_e.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),_e.name,s.jsx("span",{className:"text-[9px] font-normal",children:_e.enabled?"ON":"OFF"})]},_e.type))})]})]},L.id)})]}),de&&c&&s.jsx(ea,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:R,directories:ce,busy:je,error:Ie,confirmLabel:"Use this folder",onClose:()=>re(!1),onNavigate:L=>{V(L)},onConfirm:L=>{le(L),ie("__custom__"),re(!1)}}),ze&&s.jsx(li,{title:ze.title,description:ze.description,details:ze.details,workspaceOptions:ze.workspaceOptions,selectedWorkspaceKey:rt,onWorkspaceChange:L=>{Je.current=L,pt(L)},confirmLabel:ze.confirmLabel,busyLabel:ze.busyLabel,busy:xt,onConfirm:Ae,onCancel:()=>{He.current=null,Xe(null)}}),xe&&se&&s.jsx(ei,{activeConv:se,ides:[],isCreatingChat:!1,isRefreshingHistory:he,savedSessions:J,isSavedSessionsLoading:he,isResumingSavedSessionId:Ce,savedHistoryFilters:we,missingWorkspaceResumePath:Ge||null,onSavedHistoryFiltersChange:be,onClose:()=>fe(!1),onNewChat:()=>{G(""),fe(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Y(j)},onResumeSavedSession:L=>{if(!L.canResume||Ce)return;const Q=K(L);G(L.providerSessionId),ae(L),ee(L.providerSessionId),fe(!1),dt({type:L.providerType,workspaceId:Q.workspaceId,workspacePath:Q.workspacePath,useHome:Q.useHome,resumeSessionId:L.providerSessionId}).finally(()=>{ee(ge=>ge===L.providerSessionId?null:ge)})}})]})}const ac=[{id:"ide",label:"IDE",helper:"Open a graphical workspace and attach CDP"},{id:"cli",label:"CLI",helper:"Launch a terminal-first workspace on this machine"},{id:"acp",label:"ACP",helper:"Launch an ACP-backed workspace on this machine"}];function Cw({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:o,actions:l,getIcon:c,initialCategory:d="ide",initialWorkspaceId:m,initialWorkspacePath:u,sendDaemonCommand:h,onOpenGitDialog:x}){var g;const[S,b]=i.useState(d);i.useEffect(()=>{b(d)},[d]);const p=i.useMemo(()=>({ide:n.length,cli:a.length,acp:o.length}),[n.length,a.length,o.length]);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:"Workspace Launcher"}),s.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[s.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:ac.map(v=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${S===v.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>b(v.id),children:[s.jsx("span",{children:v.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${S===v.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:p[v.id]})]},v.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(g=ac.find(v=>v.id===S))==null?void 0:g.helper})]}),S==="ide"&&s.jsx(Xa,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:c,actions:l,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),S==="cli"&&s.jsx(Xa,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:c,actions:l,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),S==="acp"&&s.jsx(Xa,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:o,getIcon:c,actions:l,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x})]})}function Iw({onNicknameSynced:e}={}){var le,B,z,de,re,R,q,ce,Ne,je;const{id:t}=Sm(),r=As(),n=To(),{sendCommand:a}=jt(),o=Er(),l=Md(),c=od(),d=c.ides||[],m=c.initialLoaded??!0,u=d.find(O=>O.id===t&&O.type==="adhdev-daemon"),h=d.some(O=>O.type==="adhdev-daemon"),x=t?(le=c.connectionRetryStatuses)==null?void 0:le[t]:void 0,S=!!(x!=null&&x.blocked),[b,p]=i.useState("workspace"),[g,v]=i.useState(null),f=i.useCallback((O,Ie)=>{v({daemonId:O,workspace:Ie})},[]),[C,T]=i.useState("ide"),k=i.useRef(null),[A,_]=i.useState(null),N=i.useRef("__home__"),[w,D]=i.useState("__home__"),[M,j]=i.useState(!1),W=i.useRef(null);i.useEffect(()=>{!t||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||o(t,{minFreshMs:3e4}).catch(()=>{})},[o,u,t]),i.useEffect(()=>{if(!t||!u||b!=="overview")return;const O=u.machine;(typeof(O==null?void 0:O.cpus)!="number"||typeof(O==null?void 0:O.totalMem)!="number"||typeof(O==null?void 0:O.arch)!="string"||typeof(O==null?void 0:O.release)!="string")&&l(t,{minFreshMs:3e4}).catch(()=>{})},[b,l,u,t]),Mb(t&&b==="overview"?[t]:[],{enabled:b==="overview",intervalMs:jf});const H=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},$=jv({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:W});i.useEffect(()=>it.onToast(Ie=>{c.setToasts(He=>{if(He.some(Je=>Je.message===Ie.message&&Ie.timestamp-Je.timestamp<3e3))return He;const Xe={id:Ie.id,message:Ie.message,type:Ie.type,timestamp:Ie.timestamp,targetKey:Ie.targetKey,actions:Ie.actions};return[...He.slice(-4),Xe]});const Le=Ie.duration||5e3;setTimeout(()=>c.setToasts(He=>He.filter(ze=>ze.id!==Ie.id)),Le)}),[c]);const I=(u==null?void 0:u.availableProviders)||[],y={};for(const O of I)y[O.type]=O.icon;const F=O=>y[O]||"",P=u?{id:u.id,hostname:Pc(u,{fallbackId:u.id}),platform:((B=u.machine)==null?void 0:B.platform)||"unknown",arch:((z=u.machine)==null?void 0:z.arch)||"",cpus:((de=u.machine)==null?void 0:de.cpus)||0,totalMem:((re=u.machine)==null?void 0:re.totalMem)||0,freeMem:(R=u.machine)==null?void 0:R.freeMem,availableMem:(q=u.machine)==null?void 0:q.availableMem,loadavg:(ce=u.machine)==null?void 0:ce.loadavg,uptime:(Ne=u.machine)==null?void 0:Ne.uptime,release:((je=u.machine)==null?void 0:je.release)||"",cdpConnected:!!u.cdpConnected,machineNickname:u.machineNickname||null,p2p:u.p2p?{screenshotActive:!1,...u.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:u.detectedIdes||[],workspaces:u.workspaces||[],defaultWorkspaceId:u.defaultWorkspaceId??u.activeWorkspaceId??null,defaultWorkspacePath:u.defaultWorkspacePath??u.activeWorkspacePath??null}:null,E=d.filter(O=>O.daemonId===t&&O.type!=="adhdev-daemon").filter(O=>!_r(O)&&!Fs(O)).map(O=>({id:O.id,sessionId:O.sessionId,type:O.type,version:O.version||"",instanceId:O.instanceId||"",status:O.status,workspace:O.workspace||null,terminals:O.terminals||0,aiAgents:ph(O.aiAgents||(O.agents||[]).map(Ie=>({id:Ie.name,name:Ie.name,status:Ie.status,version:Ie.version}))),activeChat:O.activeChat||null,chats:O.chats||[],childSessions:O.childSessions||[],cdpConnected:O.cdpConnected||!1,daemonId:t,lastMessageAt:O.lastMessageAt})),G=d.filter(O=>O.daemonId===t&&_r(O)).map(O=>({id:O.id,sessionId:O.sessionId,type:O.type,cliName:O.cliName||O.type,status:O.status,workspace:O.workspace||"",activeChat:O.activeChat||null,providerSessionId:O.providerSessionId,mode:O.mode,runtimeKey:O.runtimeKey,runtimeDisplayName:O.runtimeDisplayName,runtimeWorkspaceLabel:O.runtimeWorkspaceLabel,runtimeWriteOwner:O.runtimeWriteOwner||null,runtimeAttachedClients:O.runtimeAttachedClients||[],daemonId:t,lastMessageAt:O.lastMessageAt})),J=d.filter(O=>O.daemonId===t&&Fs(O)).map(O=>({id:O.id,sessionId:O.sessionId,type:O.type,acpName:O.cliName||O.type,status:O.status,workspace:O.workspace||"",activeChat:O.activeChat||null,providerSessionId:O.providerSessionId,daemonId:t,lastMessageAt:O.lastMessageAt})),ye=u?At(u,{fallbackId:t}):"",he="workspace",ne=n.state,ue=ne==null?void 0:ne.initialMachineTab,Se=ne==null?void 0:ne.initialWorkspaceCategory,ve=ne==null?void 0:ne.initialWorkspaceId,X=ne==null?void 0:ne.initialWorkspacePath,xe=ue==="ides"||ue==="clis"||ue==="acps"?"workspace":ue||he,fe=ue==="ides"?"ide":ue==="clis"?"cli":ue==="acps"?"acp":Se,we=[...E.map(O=>{var Ie;return{id:`ide:${O.type}:${O.workspace||""}`,label:((Ie=O.activeChat)==null?void 0:Ie.title)||O.type,kind:"ide",providerType:O.type,subtitle:O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:O.lastMessageAt||0}}),...G.map(O=>{var Ie;return{id:`cli:${O.type}:${O.workspace||""}`,label:((Ie=O.activeChat)==null?void 0:Ie.title)||O.cliName,kind:"cli",providerType:O.type,providerSessionId:O.providerSessionId,subtitle:O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:O.lastMessageAt||0}}),...J.map(O=>{var Ie;return{id:`acp:${O.type}:${O.workspace||""}`,label:((Ie=O.activeChat)==null?void 0:Ie.title)||O.acpName,kind:"acp",providerType:O.type,providerSessionId:O.providerSessionId,subtitle:Cs(O.summaryMetadata)||O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:O.lastMessageAt||0}})].sort((O,Ie)=>(Ie.lastLaunchedAt||0)-(O.lastLaunchedAt||0)),be=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(O=>({id:O.id,label:O.title||O.providerName||O.providerType,kind:O.kind,providerType:O.providerType,providerSessionId:O.providerSessionId,subtitle:Cs(O.summaryMetadata)||O.workspace||void 0,workspace:O.workspace,summaryMetadata:O.summaryMetadata,lastLaunchedAt:O.lastLaunchedAt})):we,Ce=i.useMemo(()=>{var Ie;const O=((Ie=c.connectionStates)==null?void 0:Ie[t||""])||void 0;return d.filter(Le=>Le.daemonId===t&&Le.type!=="adhdev-daemon").flatMap(Le=>ti(Le,{connectionStates:t&&O?{[t]:O}:void 0,defaultConnectionState:O})).filter(Le=>!(Le.transport==="pty"&&Le.mode==="terminal")).sort((Le,He)=>yo(He)-yo(Le))},[d,c.connectionStates,t]),ee=i.useCallback(O=>{const Ie=Yd(O);Ie&&r(Zt(Ie))},[r]),me=i.useCallback(()=>{k.current&&(j(!0),k.current().finally(()=>{k.current=null,j(!1),_(null)}))},[]),ie=i.useCallback(O=>{if(!P)return;const{options:Ie,selectedKey:Le}=ks({machine:P,currentWorkspacePath:O.workspace}),He=async()=>{T(O.kind),p("workspace")};k.current=async()=>{const ze=Ie.find(rt=>rt.key===N.current),Xe=(ze==null?void 0:ze.workspacePath)??null,Je=(ze==null?void 0:ze.workspaceId)??null;if(O.kind==="ide"&&O.providerType){await $.handleLaunchIde(O.providerType,Xe?{workspace:Xe}:void 0);return}if((O.kind==="cli"||O.kind==="acp")&&O.providerType){await $.runLaunchCliCore({cliType:O.providerType,dir:Je?void 0:Xe||"",workspaceId:Je||void 0,model:O.kind==="acp"&&Ec(O.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:O.providerSessionId});return}await He()},N.current=Le,D(Le),_({title:O.kind==="ide"?gs("restart-ide",O.label):O.providerSessionId?Qo(O.label):gs("start-fresh",O.label),description:O.kind==="ide"?ys("restart-ide"):O.providerSessionId?Zo():ys("start-fresh"),confirmLabel:O.kind==="ide"?Ys("restart-ide"):O.providerSessionId?Pn(!0):Ys("start-fresh"),busyLabel:O.kind==="ide"?Xs("restart-ide"):O.providerSessionId?Xo(!0):Xs("start-fresh"),workspaceOptions:Ie,details:[{label:"Mode",value:O.kind.toUpperCase()},...O.providerType?[{label:"Provider",value:O.providerType}]:[]]})},[$,P]);if(i.useEffect(()=>{p(xe)},[he,xe,t]),i.useEffect(()=>{fe&&T(fe)},[fe,t]),!P)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:H,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 pe=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_t,{size:14})," Workspace"]}),count:E.length+G.length+J.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(Kn,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(sp,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Qm,{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:H,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[$.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:$.nicknameInput,onChange:O=>$.setNicknameInput(O.target.value),onKeyDown:O=>{O.key==="Enter"&&$.handleSaveNickname(),O.key==="Escape"&&$.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:$.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>$.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{$.setEditingNickname(!0),$.setNicknameInput(P.machineNickname||"")},title:"Click to set nickname",children:ye}),S?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:[P.platform," · ",P.arch]}),s.jsxs("span",{children:[P.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),P.p2p.available&&s.jsxs("span",{children:["P2P ",P.p2p.state==="connected"?"connected":P.p2p.state]}),P.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:P.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:pe.map(O=>s.jsxs("button",{onClick:()=>p(O.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${b===O.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[O.label,O.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${b===O.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:O.count})]},O.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:[b==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(jw,{machineEntry:u,providers:I,recentLaunches:be,currentConversations:Ce,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",zd(u))}catch{}},onOpenRecent:ie,onOpenConversation:ee}),s.jsx(Cw,{machine:P,machineId:t,providers:I,ideSessions:E,cliSessions:G,acpSessions:J,actions:$,getIcon:F,initialCategory:C,initialWorkspaceId:ve,initialWorkspacePath:X,sendDaemonCommand:a,onOpenGitDialog:f})]}),b==="providers"&&s.jsx(Lv,{machineId:t,providers:I,sendDaemonCommand:a}),b==="overview"&&s.jsx(kv,{machineId:t,machine:P,ideSessions:E,cliSessions:G,acpSessions:J,actions:$,sendDaemonCommand:a}),b==="session-host"&&s.jsx(vw,{machineId:t,cliSessions:G,sendDaemonCommand:a}),b==="logs"&&s.jsx(pw,{machineId:t,sendDaemonCommand:a})]})})}),$.launchPick&&P&&s.jsx(ww,{machine:P,launchPick:$.launchPick,actions:$}),A&&s.jsx(li,{title:A.title,description:A.description,details:A.details,workspaceOptions:A.workspaceOptions,selectedWorkspaceKey:w,onWorkspaceChange:O=>{N.current=O,D(O)},confirmLabel:A.confirmLabel,busyLabel:A.busyLabel,busy:M,onConfirm:me,onCancel:()=>{k.current=null,_(null)}}),g&&s.jsx(Du,{daemonId:g.daemonId,workspace:g.workspace,onClose:()=>v(null)}),s.jsx(xd,{toasts:c.toasts||[],onDismiss:O=>c.setToasts(Ie=>Ie.filter(Le=>Le.id!==O)),onClickToast:O=>{O.targetKey&&r(Zt(O.targetKey))}}),s.jsx("style",{children:`
|
|
92
92
|
@keyframes toast-in {
|
|
93
93
|
from { opacity: 0; transform: translateX(40px); }
|
|
94
94
|
to { opacity: 1; transform: translateX(0); }
|
|
95
95
|
}
|
|
96
|
-
`})]})}const mn=[{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."}],
|
|
96
|
+
`})]})}const mn=[{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."}],Tw={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,sessionCleanupOnNodeRemove:"preserve"};function jn(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 Mw(e){const t=jn(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 Aw(e,t){return t.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function _w(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 Lw(e,t){return[...Array.isArray(t==null?void 0:t.cliSessions)?t.cliSessions:[],...Array.isArray(t==null?void 0:t.acpSessions)?t.acpSessions:[],...Array.isArray(t==null?void 0:t.sessions)?t.sessions:[]].filter(n=>{var a;return((a=n==null?void 0:n.settings)==null?void 0:a.meshNodeId)===e.id||(n==null?void 0:n.workspace)===e.workspace}).map(n=>{var a;return{id:n.sessionId||n.id||n.instanceId||"unknown",provider:n.providerType||n.cliType||n.acpType||n.type||"unknown",status:n.status||((a=n.activeChat)==null?void 0:a.status)||"unknown"}})}function Ja(e){return{...Tw,...(e==null?void 0:e.policy)||{}}}function Rw({meshId:e,availableCliAgents:t}){const r=t.find(a=>{const o=a.id.toLowerCase(),l=a.name.toLowerCase();return o==="hermes-cli"||o.includes("hermes")||l.includes("hermes")}),n=qd(r==null?void 0:r.meshCoordinator,{meshId:e});return n?s.jsx(St,{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(yu,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}function Pw(){var le;const{sendCommand:e}=jt(),{ides:t}=cs(),r=t.find(B=>B.daemonMode||B.type==="adhdev-daemon"),n=(r==null?void 0:r.id)||"",a=[];let o=[];if(r){const B=r.availableProviders||[];o=Hx(B);for(const z of B)z.category==="cli"&&a.push({id:z.type||z.id,name:z.displayName||z.name||z.type,meshCoordinator:z.meshCoordinator})}const[l,c]=i.useState([]),[d,m]=i.useState(null),[u,h]=i.useState(!0),[x,S]=i.useState(null),[b,p]=i.useState(!1),[g,v]=i.useState(null),[f,C]=i.useState({}),[T,k]=i.useState([]),[A,_]=i.useState(null),[N,w]=i.useState(null),[D,M]=i.useState(null),[j,W]=i.useState(!1),[H,$]=i.useState(null),[I,y]=i.useState(!1),[F,P]=i.useState(""),[E,G]=i.useState(""),[J,ye]=i.useState(!1),[he,ne]=i.useState(""),[ue,Se]=i.useState([]),ve=l.find(B=>B.id===d)||null;i.useEffect(()=>{C(Object.fromEntries(((ve==null?void 0:ve.nodes)||[]).map(B=>[B.id,jn(B)])))},[ve]),i.useEffect(()=>{const B=Ux(o);J&&ue.length===0&&B.length>0&&Se(B)},[J,o,ue.length]),i.useEffect(()=>{const B=new Set(((ve==null?void 0:ve.nodes)||[]).map(z=>z.id));A&&!B.has(A)&&_(null)},[ve,A]);const X=i.useCallback(async()=>{if(n){h(!0);try{const B=await e(n,"list_meshes");B!=null&&B.success?(c(B.meshes||[]),S(null)):S((B==null?void 0:B.error)||"Failed to load meshes")}catch(B){S((B==null?void 0:B.message)||"Failed to load meshes")}finally{h(!1)}}},[n,e]),xe=i.useCallback(async B=>{if(!n||!B){k([]);return}try{const z=await e(n,"get_mesh_queue",{meshId:B});z!=null&&z.success?k(Array.isArray(z.queue)?z.queue:[]):k([])}catch{k([])}},[n,e]);i.useEffect(()=>{X()},[X]),i.useEffect(()=>{xe(d)},[xe,d]);async function fe(){if(!(!n||!d))try{W(!0),$(null);const B=await e(n,"mesh_status",{meshId:d});if((B==null?void 0:B.success)===!1){w(null),M(null),$((B==null?void 0:B.error)||"mesh_status failed");return}const z=Ru(B);if(z){const de=ku(z);w(de),M(z)}else w(null),M(null),$("mesh_status returned an unexpected payload.")}catch(B){w(null),M(null),$((B==null?void 0:B.message)||"Failed to load mesh graph")}finally{W(!1)}}i.useEffect(()=>{d&&(w(null),M(null),$(null),fe())},[d]);async function we(){var B;if(!(!n||!F.trim()))try{const z=await e(n,"create_mesh",{name:F.trim(),repoIdentity:E.trim()||void 0});z!=null&&z.success?(y(!1),P(""),G(""),await X(),m(((B=z.mesh)==null?void 0:B.id)||null)):S((z==null?void 0:z.error)||"Create failed")}catch(z){S((z==null?void 0:z.message)||"Create failed")}}async function be(B){if(!(!n||!confirm("Delete this mesh?")))try{await e(n,"delete_mesh",{meshId:B}),m(null),await X()}catch(z){S((z==null?void 0:z.message)||"Delete failed")}}async function Ce(){if(!(!n||!d||!he.trim()))try{const B=await e(n,"add_mesh_node",{meshId:d,workspace:he.trim(),providerPriority:ho(ue,o)});B!=null&&B.success?(ye(!1),ne(""),Se([]),await X(),await xe(d)):S((B==null?void 0:B.error)||"Add node failed")}catch(B){S((B==null?void 0:B.message)||"Add node failed")}}async function ee(B){var re;if(!n||!d)return;const z=Ja(ve),de=((re=mn.find(R=>R.value===z.sessionCleanupOnNodeRemove))==null?void 0:re.label)||"Preserve history and runtimes";if(confirm(`Remove this node?
|
|
97
97
|
|
|
98
|
-
Node removal cleanup policy: ${de}`))try{await e(n,"remove_mesh_node",{meshId:d,nodeId:B}),A===B&&_(null),await X(),await xe(d)}catch(R){S((R==null?void 0:R.message)||"Remove node failed")}}async function me(B){if(!n||!d)return;const z={...Ja(ve),...B};try{p(!0),S(null);const de=await e(n,"update_mesh",{meshId:d,policy:z});if((de==null?void 0:de.success)===!1){S(de.error||"Policy update failed");return}await X()}catch(de){S((de==null?void 0:de.message)||"Policy update failed")}finally{p(!1)}}async function ie(B){if(!n||!d)return;const z=ho(f[B.id]||jn(B),o),de={...B.policy||{}};delete de.provider_priority,z.length?de.providerPriority=z:delete de.providerPriority;try{v(B.id),S(null);const re=await e(n,"update_mesh_node",{meshId:d,nodeId:B.id,policy:de});if((re==null?void 0:re.success)===!1){S(re.error||"Node policy update failed");return}await X()}catch(re){S((re==null?void 0:re.message)||"Node policy update failed")}finally{v(null)}}if(!n)return s.jsx(kr,{icon:s.jsx(as,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})});if(!ve)return s.jsxs(kr,{icon:s.jsx(as,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>y(!0),children:"+ Create Mesh"}),children:[x&&s.jsx(Os,{variant:"error",className:"mb-4",children:x}),C&&s.jsx(St,{title:"New Mesh",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Lt,{label:"Name",children:s.jsx(ga,{value:F,onChange:B=>P(B.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(Lt,{label:"Repo Identity (optional)",children:s.jsx(ga,{value:E,onChange:B=>G(B.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:we,disabled:!F.trim(),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>y(!1),children:"Cancel"})]})]})}),u?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):l.length===0?s.jsx(Dn,{icon:s.jsx(as,{}),title:"No meshes",description:"Create a mesh to get started."}):s.jsx("div",{className:"flex flex-col gap-2",children:l.map(B=>s.jsxs("button",{className:"text-left w-full p-4 rounded-xl border border-border-subtle bg-bg-panel hover:border-accent-primary/40 transition-colors",onClick:()=>m(B.id),children:[s.jsx("div",{className:"font-semibold text-sm",children:B.name}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5 font-mono",children:B.repoIdentity||"No repo identity"}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-1",children:[B.nodes.length," node(s)"]})]},B.id))})]});const pe=Ja(ve);return s.jsxs(kr,{icon:s.jsx(as,{}),title:ve.name,subtitle:ve.repoIdentity||"Repo Mesh",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(null),children:"← Back"}),s.jsx("button",{className:"btn btn-sm",style:{color:"var(--color-red-400)"},onClick:()=>be(ve.id),children:"Delete"})]}),children:[x&&s.jsx(Os,{variant:"error",className:"mb-4",children:x}),s.jsxs(St,{title:"Policy",description:"Coordinator safety defaults and node-removal session cleanup behavior for this local mesh.",children:[s.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[s.jsx(Lt,{label:"Checkpoint before task",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:pe.requirePreTaskCheckpoint?"yes":"no",onChange:B=>me({requirePreTaskCheckpoint:B.target.value==="yes"}),disabled:b,children:[s.jsx("option",{value:"no",children:"No"}),s.jsx("option",{value:"yes",children:"Yes"})]})}),s.jsx(Lt,{label:"Checkpoint after task",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:pe.requirePostTaskCheckpoint?"yes":"no",onChange:B=>me({requirePostTaskCheckpoint:B.target.value==="yes"}),disabled:b,children:[s.jsx("option",{value:"yes",children:"Yes"}),s.jsx("option",{value:"no",children:"No"})]})}),s.jsx(Lt,{label:"Push approval",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:pe.requireApprovalForPush?"required":"not_required",onChange:B=>me({requireApprovalForPush:B.target.value==="required"}),disabled:b,children:[s.jsx("option",{value:"required",children:"Require approval before push"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(Lt,{label:"Destructive git approval",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:pe.requireApprovalForDestructiveGit?"required":"not_required",onChange:B=>me({requireApprovalForDestructiveGit:B.target.value==="required"}),disabled:b,children:[s.jsx("option",{value:"required",children:"Require approval"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(Lt,{label:"Dirty workspace behavior",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:pe.dirtyWorkspaceBehavior||"warn",onChange:B=>me({dirtyWorkspaceBehavior:B.target.value}),disabled:b,children:[s.jsx("option",{value:"warn",children:"Warn and continue"}),s.jsx("option",{value:"block",children:"Block task"}),s.jsx("option",{value:"checkpoint_then_continue",children:"Checkpoint then continue"})]})}),s.jsx(Lt,{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(pe.maxParallelTasks??2),onChange:B=>me({maxParallelTasks:Number(B.target.value)}),disabled:b,children:[1,2,3,4,5,6,7,8].map(B=>s.jsx("option",{value:B,children:B},B))})})]}),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(Lt,{label:"Node removal session cleanup",hint:"Separate transcript cleanup from runtime/process cleanup. Preserve is safest when completed work may need review.",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:pe.sessionCleanupOnNodeRemove||"preserve",onChange:B=>me({sessionCleanupOnNodeRemove:B.target.value}),disabled:b,children:mn.map(B=>s.jsx("option",{value:B.value,children:B.label},B.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((le=mn.find(B=>B.value===pe.sessionCleanupOnNodeRemove))==null?void 0:le.description)||mn[0].description})]}),b&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving policy..."})]}),s.jsxs(St,{title:"Visualization",description:"Live mesh topology: branches, worktrees, sessions, and orphan detection.",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",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.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:fe,disabled:j,children:j?"Loading...":"Refresh Graph"})]}),H&&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:H}),!N||!D?s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:j?"Loading graph...":"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology from this standalone daemon."}):s.jsx(_u,{graph:N,status:D,emptyMessage:"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology from this standalone daemon.",daemonId:n,sendDaemonCommand:e})]}),s.jsxs(St,{title:"Nodes",description:"Workspaces participating in this mesh.",children:[s.jsx("div",{className:"flex justify-end mb-3",children:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>ye(!0),children:"+ Add Node"})}),J&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:"Add Node"}),s.jsx("button",{onClick:()=>ye(!1),className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(wt,{size:16})})]}),s.jsx(Lt,{label:"Workspace Path",children:s.jsx(ga,{value:he,onChange:B=>ne(B.target.value),placeholder:"/Users/dev/projects/myapp",autoFocus:!0})}),s.jsx(Lt,{label:"Provider Priority",hint:"Order used when launching without an explicit provider. Empty means fail closed unless a provider is selected explicitly.",children:s.jsx(al,{value:ue,availableProviders:o,onChange:Se})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:Ce,disabled:!he.trim(),className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>ye(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),ve.nodes.length===0?s.jsx(Dn,{icon:s.jsx(Ns,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:ve.nodes.map(B=>{const z=jn(B),de=Nw(B),re=Cw(B,I),R=Tw(B,r),q=A===B.id;return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary cursor-pointer transition-colors ${q?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`,role:"button",tabIndex:0,onClick:()=>_(q?null:B.id),onKeyDown:ce=>{(ce.key==="Enter"||ce.key===" ")&&(ce.preventDefault(),_(q?null:B.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"text-sm font-medium",children:B.workspace.split("/").pop()}),re.length>0&&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:[re.length," active task",re.length===1?"":"s"]})]}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:B.workspace}),s.jsx("div",{className:"mt-3 max-w-2xl",onClick:ce=>ce.stopPropagation(),children:s.jsxs(Lt,{label:"Provider priority",hint:"Used when launches omit an explicit provider. Empty keeps fail-closed behavior until a provider is selected manually.",children:[s.jsx(al,{value:f[B.id]??z,availableProviders:o,onChange:ce=>T(Ne=>({...Ne,[B.id]:ce})),disabled:g===B.id,saveButton:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:ce=>{ce.stopPropagation(),ie(B)},disabled:g===B.id,children:g===B.id?"Saving...":"Save policy"})}),s.jsxs("div",{className:"mt-2 text-[12px]",children:[s.jsx("span",{className:"text-text-muted",children:"Effective provider priority: "}),s.jsx("span",{className:de.configured?"text-text-primary font-mono":"text-amber-400",children:de.label}),de.launchBlockedMessage&&s.jsxs("span",{className:"ml-2 text-amber-400",children:["(",de.launchBlockedMessage,")"]})]})]})})]}),s.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:ce=>{ce.stopPropagation(),ee(B.id)},children:s.jsx(wt,{size:14})})]}),q&&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:B.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",s.jsx("span",{className:de.configured?"text-green-400":"text-amber-400",children:de.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:B.repoRoot||B.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",R.length]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Branch / git:"})," not loaded in standalone list view"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Health:"})," ",re.length>0||R.length>0?"active":"idle/unknown"]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active queue assignments"}),re.length===0?s.jsx("div",{children:"No active assigned queue task for this node."}):s.jsx("ul",{className:"m-0 pl-4",children:re.map(ce=>s.jsx("li",{className:"font-mono",children:Iw(ce)},ce.id))})]}),R.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:R.map(ce=>s.jsxs("li",{className:"font-mono",children:[ce.provider," / ",ce.status," / ",ce.id]},ce.id))})]})]})]},B.id)})})]}),s.jsx(Mw,{meshId:ve.id,availableCliAgents:a})]})}function fi(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function _w(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=fi();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 Ut(e,t){return await fetch(_w(e),{credentials:"same-origin",...t})}function $u(){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 Lw{constructor(){Ze(this,"adapters",new Map);Ze(this,"states",new Map);Ze(this,"runtimeListeners",new Map);Ze(this,"screenshotCallbacks",new Map);Ze(this,"statusCallbacks",new Set)}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)}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"}sendData(t,r){return!1}sendPtyInput(t,r,n){return!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,l){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:o,rows:l})}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 Ut(`${a.pathname}${a.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(c=d.error)}catch{}return{success:!1,error:c}}const l=await o.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof l.seq=="number"?l.seq:0,text:typeof l.text=="string"?l.text:"",truncated:!!l.truncated,cols:typeof l.cols=="number"?l.cols:void 0,rows:typeof l.rows=="number"?l.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 Yt=new Lw;function Rw(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=fi();return r?`${t}?token=${encodeURIComponent(r)}`:t}const pn=Rw(),ac=3e3,Pw=3e4;let Ot=null,Dw=0;const Wn=new Map;let ms=null,Ir=null;function oc(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function fr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function Ew(e){return e==="connected"?"connected":e}async function kn(e,t,r){const n=yd(e,r||{}),a=Ot;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++Dw}_${Date.now()}`;return new Promise((l,c)=>{const d=setTimeout(()=>{Wn.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);Wn.set(o,{resolve:m=>{clearTimeout(d),l(m)},reject:m=>{clearTimeout(d),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 No(e,t){const r=Ot;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 $w(e,t,r){const n=Ot;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=yd(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}}class Bw{constructor(t){Ze(this,"daemonId");Ze(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Ot==null?void 0:Ot.readyState)===WebSocket.OPEN}get connectionState(){return(Ot==null?void 0:Ot.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return kn(this.daemonId,t,r)}async sendInput(t,r){return kn(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,ms&&(clearInterval(ms),ms=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await kn(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());Yt.emitScreenshot(this.daemonId,a)}}catch{}};r(),ms=setInterval(r,2e3)}stopScreenshots(t){ms&&(clearInterval(ms),ms=null)}}let Pt=null;function Ow(e){return(!Pt||Pt.daemonId!==e)&&(Pt=new Bw(e)),Pt}function Fw({children:e}){const t=i.useRef(Mr()),r=Mr();t.current=r;const{setUserName:n}=cs(),a=i.useRef(n);a.current=n;const o=i.useRef(null),l=i.useRef(null),[,c]=i.useState("disconnected"),d=i.useCallback((p,g)=>{c(p),Ir==null||Ir(p,g)},[]),m=i.useRef(null),u=i.useRef(),h=i.useRef(ac),x=i.useRef(!0),S=i.useRef(!1),b=i.useRef("initial_connect");return i.useEffect(()=>{x.current=!0,S.current=!1;function p(){var f,T;if(!x.current||((f=m.current)==null?void 0:f.readyState)===WebSocket.OPEN||((T=m.current)==null?void 0:T.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${pn}...`),fr("connect_attempt",{url:pn,reason:b.current,delayMs:h.current});let v;try{v=new WebSocket(pn)}catch(I){console.error("[Standalone WS] Failed to create WebSocket:",I),g();return}m.current=v,v.onopen=()=>{if(!x.current){v.close();return}d("connected"),h.current=ac,fr("open",{url:pn,reason:b.current}),Qt.resubscribeAll({sendData:No}),console.log("[Standalone WS] Connected")},Ot=v,v.onmessage=I=>{var k,A;try{const _=JSON.parse(I.data);if((_.type==="command_result"||_.type==="error")&&_.requestId){const N=Wn.get(_.requestId);N&&(Wn.delete(_.requestId),_.type==="error"?N.reject(new Error(((k=_.data)==null?void 0:k.message)||"Command failed")):N.resolve(_.data));return}if(_.type==="session_output"){const N=_.sessionId||_.cliId||_.cliType;N&&Yt.emitSessionOutput(N,typeof _.data=="string"?_.data:"",typeof _.seq=="number"?_.seq:void 0);return}if(_.type==="runtime_snapshot"){Yt.emitRuntimeSnapshot(_.sessionId,typeof _.text=="string"?_.text:"",typeof _.seq=="number"?_.seq:0,!!_.truncated,typeof _.cols=="number"?_.cols:void 0,typeof _.rows=="number"?_.rows:void 0);return}if(_.type==="topic_update"){const N=_.update;N&&Qt.publish(N);return}if(_.type==="status"||_.type==="initial_state"){const N=_.data;if(!N)return;const{injectEntries:w,markLoaded:D,getIdes:M}=t.current,j=N.instanceId||"standalone",W=M().find(C=>C.id===j),H=Ow(j);Yt.register(j,H),Yt.setState(j,"connected"),d("connected",j),Yt.emitStatus(j,N);const $=Rn(N,{daemonId:j,existingDaemon:W,existingEntries:M()});oc("ws_status",{type:_.type,daemonId:j,sessions:(N.sessions||[]).map(C=>({id:C.id,parentId:C.parentId,providerType:C.providerType,kind:C.kind,transport:C.transport,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,title:C.title})),recentLaunches:(N.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),oc("entries",{daemonId:j,entries:$.filter(C=>C.type!=="adhdev-daemon").map(C=>({id:C.id,type:C.type,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,sessionId:C.sessionId}))}),$.length>0&&w($,{authoritativeDaemonIds:[j]}),D(),l.current!==j&&((A=o.current)==null||A.call(o),l.current=j,o.current=Qt.subscribe({sendData:No},j,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${j}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const y=t.current.getIdes(),F=y.find(E=>E.id===j),P=Rn(C.status,{daemonId:j,existingDaemon:F,existingEntries:y,timestamp:C.timestamp});P.length>0&&t.current.injectEntries(P,{authoritativeDaemonIds:[j]}),C.userName&&a.current&&a.current(C.userName)}))}}catch(_){console.error("[Standalone WS] Parse error:",_)}},v.onclose=I=>{x.current&&(Pt==null||Pt.stopScreenshots(),Pt&&Yt.setState(Pt.daemonId,"disconnected"),d("disconnected"),m.current=null,b.current=`close:${I.code}${I.wasClean?":clean":":unclean"}`,fr("close",{code:I.code,reason:I.reason||"",wasClean:I.wasClean}),g())},v.onerror=I=>{S.current||!x.current||(b.current="error",fr("error",{message:I instanceof Event?"event":String(I),readyState:v.readyState}),console.warn("[Standalone WS] Error, will reconnect:",I))}}function g(){if(!x.current)return;clearTimeout(u.current);const v=h.current;console.log(`[Standalone WS] Reconnecting in ${v}ms...`),fr("schedule_reconnect",{reason:b.current,delayMs:v}),u.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,Pw),p()},v)}return p(),()=>{var v;x.current=!1,S.current=!0,(v=o.current)==null||v.call(o),o.current=null,l.current=null,clearTimeout(u.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,Ot=null),Pt&&(Pt.stopScreenshots(),Yt.unregister(Pt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function Ww({children:e}){const[t,r]=i.useState("disconnected"),[n,a]=i.useState(null);i.useEffect(()=>(Ir=(l,c)=>{r(l),c&&a(c)},()=>{Ir=null}),[]);const o=i.useMemo(()=>{const l=t==="connected",c=Ew(t),d={};return n&&(d[n]=c),d.standalone=c,{wsStatus:t,isConnected:l,connectionStates:d}},[t,n]);return s.jsx(Fm,{connectionOverrides:o,children:s.jsx(Fw,{children:e})})}const Bu="adhdev_standalone_font_preferences",Ss={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},ra=[{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"}],Lr=[{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"}],Kw=new Set(ra.map(e=>e.id)),Hw=new Set(Lr.map(e=>e.id));function Vt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Sn("chat",t.chat),code:Sn("code",t.code),terminal:Sn("terminal",t.terminal)}}function Sn(e,t){const r=Ss[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"?Kw:Hw).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function Nn(e,t){var a;const r=Sn(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?ra:Lr;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function Uw(e){const t=Vt(e),r=Nn("chat",t.chat),n=Nn("code",t.code),a=Nn("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function fs(e,t=document.documentElement){const r=Vt(e),n=Uw(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function Co(e){const t=Vt(e);try{localStorage.setItem(Bu,JSON.stringify(t))}catch{}return t}function zw(){try{const e=localStorage.getItem(Bu);if(e)return Vt(JSON.parse(e))}catch{}return Ss}function Vw(){return fs(zw())}function xr(e,t){var n;const r=e==="chat"?ra:Lr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const Gw=[{id:"dashboard",path:"/dashboard",icon:s.jsx(xc,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(is,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(zs,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(Kn,{}),label:"Settings"}];function qw({children:e}){const t=As(),r=To(),n=i.useMemo(()=>Gw.map(o=>({...o,active:r.pathname.startsWith(o.path),onSelect:()=>t(o.path)})),[r.pathname,t]),a=i.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(gc,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(yc,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(eb,{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.81"]}),footerActions:({collapsed:o,toggleCollapsed:l})=>s.jsxs("div",{className:`nav-item cursor-pointer ${o?"justify-center py-2.5 px-0":"mt-1"}`,onClick:l,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 Yw=[{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(es,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(vc,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(_t,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(zs,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(gc,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Xw=[{icon:s.jsx(rp,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(xc,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Hn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Xm,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(bc,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Qm,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Jw=[{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 Qw(){return s.jsxs(kr,{icon:s.jsx(yc,{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.81"]}),children:[s.jsx(St,{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(St,{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:Yw.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(St,{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:vd.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:jd.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:wd.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(St,{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:Xw.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(St,{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:Jw.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(Dn,{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(pp,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Qa(e,t,r){return{...e,[t]:r}}function Za({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:l=>{const c=l.target.value;o(c==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:c})},children:a.map(l=>s.jsx("option",{value:l.id,children:l.label},l.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:l=>o({preset:"custom",customFamily:l.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:Nn(e,n)})]})]})]})}function Zw({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:o,onSave:l,onResetToSaved:c,onResetToDefaults:d}){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(Za,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:ra,onChange:u=>o(Qa(e,"chat",u))}),s.jsx(Za,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Lr,onChange:u=>o(Qa(e,"code",u))}),s.jsx(Za,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Lr,onChange:u=>o(Qa(e,"terminal",u))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",xr("chat",e.chat.preset)," · Code: ",xr("code",e.code.preset)," · Terminal: ",xr("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",xr("chat",Ss.chat.preset)," / ",xr("code",Ss.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:l,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:d,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function ej(){const{ides:e}=cs(),t=e.find(X=>X.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=jt(),{userName:a}=cs(),[o,l]=i.useState(a||""),[c,d]=i.useState(null),[m,u]=i.useState(null),[h,x]=i.useState(Ss),[S,b]=i.useState(!1),[p,g]=i.useState(""),[v,f]=i.useState(""),[T,I]=i.useState("127.0.0.1"),[k,A]=i.useState(""),[_,N]=i.useState(""),[w,D]=i.useState(""),[M,j]=i.useState(""),[W,H]=i.useState(""),[$,C]=i.useState(!1),y=async()=>{const xe=await(await Ut("/auth/session")).json();d(xe)},F=async()=>{const xe=await(await Ut("/api/v1/standalone/preferences")).json();u(xe),I(xe.standaloneBindHost);const fe=Vt(xe.standaloneFontPreferences);x(fe),fs(fe),Co(fe)};i.useEffect(()=>{a!==void 0&&l(a)},[a]),i.useEffect(()=>{Promise.all([y(),F()]).catch(X=>{j(X instanceof Error?X.message:String(X))})},[]),i.useEffect(()=>{fs(h)},[h]);const P=X=>{const xe=X.target.value.trim();t!=null&&t.id&&xe!==a&&n(t.id,"set_user_name",{userName:xe}).catch(console.error)},[E,G]=i.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),J=X=>{G(X);try{localStorage.setItem("adhdev_sound",X?"1":"0")}catch{}},ye=async()=>{g(""),f(""),b(!0);try{const X=Vt(h),xe=await Ut("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:X})}),fe=await xe.json();if(!xe.ok)throw new Error((fe==null?void 0:fe.error)||"Failed to save standalone font preferences");const we=Vt(fe.standaloneFontPreferences);u(fe),x(we),fs(we),Co(we),f("Standalone chat fonts saved for this self-hosted dashboard.")}catch(X){g(X instanceof Error?X.message:String(X))}finally{b(!1)}},he=()=>{const X=Vt(m==null?void 0:m.standaloneFontPreferences);g(""),f(""),x(X),fs(X)},ne=()=>{g(""),f(""),x(Ss),fs(Ss)},ue=async()=>{j(""),H(""),C(!0);try{const X=await Ut("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:T})}),xe=await X.json();if(!X.ok)throw new Error((xe==null?void 0:xe.error)||"Failed to save standalone network preference");u(xe),I(xe.standaloneBindHost),H(xe.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){j(X instanceof Error?X.message:String(X))}finally{C(!1)}},Se=async()=>{if(j(""),H(""),_.trim().length<4){j("Password must be at least 4 characters.");return}if(_!==w){j("New password and confirmation do not match.");return}C(!0);try{const X=await Ut("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,newPassword:_})}),xe=await X.json();if(!X.ok)throw new Error((xe==null?void 0:xe.error)||"Failed to save password");d(xe),await F(),A(""),N(""),D(""),H(c!=null&&c.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),$u()}catch(X){j(X instanceof Error?X.message:String(X))}finally{C(!1)}},ve=async()=>{j(""),H(""),C(!0);try{const X=await Ut("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,clear:!0})}),xe=await X.json();if(!X.ok)throw new Error((xe==null?void 0:xe.error)||"Failed to clear password");d(xe),await F(),A(""),N(""),D(""),H("Standalone password disabled.")}catch(X){j(X instanceof Error?X.message:String(X))}finally{C(!1)}};return s.jsxs(kr,{icon:s.jsx(Kn,{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(St,{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.81"]}),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(St,{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:T==="127.0.0.1",onChange:()=>I("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:T==="0.0.0.0",onChange:()=>I("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:()=>{ue()},disabled:$,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:$?"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(St,{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."}),M&&s.jsx(Os,{variant:"error",children:M}),W&&s.jsx(Os,{variant:"success",children:W}),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=>A(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:_,onChange:X=>N(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:w,onChange:X=>D(X.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{Se()},disabled:$,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:$?"Saving…":c!=null&&c.hasPasswordAuth?"Update password":"Enable password"}),(c==null?void 0:c.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{ve()},disabled:$,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(St,{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(St,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(cb,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(St,{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(pb,{})]}),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(wb,{})]}),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(Zw,{value:h,savedValue:Vt(m==null?void 0:m.standaloneFontPreferences),saving:S,error:p,notice:v,onChange:x,onSave:()=>{ye()},onResetToSaved:he,onResetToDefaults:ne})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout."}),s.jsx(Sb,{})]})]})}),s.jsx(St,{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(ob,{}),s.jsx(hs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(mp,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:E,onChange:J})]})}),s.jsx(St,{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(Ym,{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=>l(X.target.value),onBlur:P,onKeyDown:X=>{X.key==="Enter"&&X.currentTarget.blur()}})]})})})]})}Qx();yb();Vw();const tj=hc({baseUrl:"",getToken:fi});function sj({children:e}){const[t,r]=i.useState(null),[n,a]=i.useState(!0),[o,l]=i.useState(""),[c,d]=i.useState(""),[m,u]=i.useState(!1),h=async()=>{a(!0),d("");try{const b=await(await Ut("/auth/session")).json();r(b)}catch(S){d(S instanceof Error?S.message:String(S))}finally{a(!1)}};i.useEffect(()=>{h()},[]),i.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let S=!1;return(async()=>{try{const b=await Ut("/api/v1/standalone/preferences");if(!b.ok)return;const p=await b.json();if(S)return;const g=Vt(p.standaloneFontPreferences);fs(g),Co(g)}catch{}})(),()=>{S=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const x=async S=>{S.preventDefault(),u(!0),d("");try{const b=await Ut("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),p=await b.json();if(!b.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),l(""),$u()}catch(b){d(b instanceof Error?b.message:String(b))}finally{u(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:x,children:[s.jsx("input",{type:"password",value:o,onChange:S=>l(S.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 ic(){const{ides:e,initialLoaded:t}=cs();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(so,{to:`/machines/${r.id}`,replace:!0}):s.jsx(so,{to:"/dashboard",replace:!0})}function rj(){const e=i.useMemo(()=>({sendCommand:kn,sendData:No,sendPtyInput:$w}),[]);return s.jsx(Sm,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Hm,{client:tj,children:s.jsx(sj,{children:s.jsx(Ww,{children:s.jsx(zm,{value:e,children:s.jsx(qw,{children:s.jsxs(Nm,{children:[s.jsx(rs,{path:"/dashboard",element:s.jsx(bv,{})}),s.jsx(rs,{path:"/machine",element:s.jsx(ic,{})}),s.jsx(rs,{path:"/machines/:id",element:s.jsx(kw,{})}),s.jsx(rs,{path:"/machines",element:s.jsx(ic,{})}),s.jsx(rs,{path:"/about",element:s.jsx(Qw,{})}),s.jsx(rs,{path:"/settings",element:s.jsx(ej,{})}),s.jsx(rs,{path:"/mesh",element:s.jsx(Aw,{})}),s.jsx(rs,{path:"*",element:s.jsx(so,{to:"/dashboard",replace:!0})})]})})})})})})})}lx({connectionManager:Yt});Cm(document.getElementById("root")).render(s.jsx(rj,{}));
|
|
98
|
+
Node removal cleanup policy: ${de}`))try{await e(n,"remove_mesh_node",{meshId:d,nodeId:B}),A===B&&_(null),await X(),await xe(d)}catch(R){S((R==null?void 0:R.message)||"Remove node failed")}}async function me(B){if(!n||!d)return;const z={...Ja(ve),...B};try{p(!0),S(null);const de=await e(n,"update_mesh",{meshId:d,policy:z});if((de==null?void 0:de.success)===!1){S(de.error||"Policy update failed");return}await X()}catch(de){S((de==null?void 0:de.message)||"Policy update failed")}finally{p(!1)}}async function ie(B){if(!n||!d)return;const z=ho(f[B.id]||jn(B),o),de={...B.policy||{}};delete de.provider_priority,z.length?de.providerPriority=z:delete de.providerPriority;try{v(B.id),S(null);const re=await e(n,"update_mesh_node",{meshId:d,nodeId:B.id,policy:de});if((re==null?void 0:re.success)===!1){S(re.error||"Node policy update failed");return}await X()}catch(re){S((re==null?void 0:re.message)||"Node policy update failed")}finally{v(null)}}if(!n)return s.jsx(kr,{icon:s.jsx(as,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})});if(!ve)return s.jsxs(kr,{icon:s.jsx(as,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>y(!0),children:"+ Create Mesh"}),children:[x&&s.jsx(Os,{variant:"error",className:"mb-4",children:x}),I&&s.jsx(St,{title:"New Mesh",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Lt,{label:"Name",children:s.jsx(ga,{value:F,onChange:B=>P(B.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(Lt,{label:"Repo Identity (optional)",children:s.jsx(ga,{value:E,onChange:B=>G(B.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:we,disabled:!F.trim(),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>y(!1),children:"Cancel"})]})]})}),u?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):l.length===0?s.jsx(Dn,{icon:s.jsx(as,{}),title:"No meshes",description:"Create a mesh to get started."}):s.jsx("div",{className:"flex flex-col gap-2",children:l.map(B=>s.jsxs("button",{className:"text-left w-full p-4 rounded-xl border border-border-subtle bg-bg-panel hover:border-accent-primary/40 transition-colors",onClick:()=>m(B.id),children:[s.jsx("div",{className:"font-semibold text-sm",children:B.name}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5 font-mono",children:B.repoIdentity||"No repo identity"}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-1",children:[B.nodes.length," node(s)"]})]},B.id))})]});const pe=Ja(ve);return s.jsxs(kr,{icon:s.jsx(as,{}),title:ve.name,subtitle:ve.repoIdentity||"Repo Mesh",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(null),children:"← Back"}),s.jsx("button",{className:"btn btn-sm",style:{color:"var(--color-red-400)"},onClick:()=>be(ve.id),children:"Delete"})]}),children:[x&&s.jsx(Os,{variant:"error",className:"mb-4",children:x}),s.jsxs(St,{title:"Policy",description:"Coordinator safety defaults and node-removal session cleanup behavior for this local mesh.",children:[s.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[s.jsx(Lt,{label:"Checkpoint before task",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:pe.requirePreTaskCheckpoint?"yes":"no",onChange:B=>me({requirePreTaskCheckpoint:B.target.value==="yes"}),disabled:b,children:[s.jsx("option",{value:"no",children:"No"}),s.jsx("option",{value:"yes",children:"Yes"})]})}),s.jsx(Lt,{label:"Checkpoint after task",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:pe.requirePostTaskCheckpoint?"yes":"no",onChange:B=>me({requirePostTaskCheckpoint:B.target.value==="yes"}),disabled:b,children:[s.jsx("option",{value:"yes",children:"Yes"}),s.jsx("option",{value:"no",children:"No"})]})}),s.jsx(Lt,{label:"Push approval",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:pe.requireApprovalForPush?"required":"not_required",onChange:B=>me({requireApprovalForPush:B.target.value==="required"}),disabled:b,children:[s.jsx("option",{value:"required",children:"Require approval before push"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(Lt,{label:"Destructive git approval",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:pe.requireApprovalForDestructiveGit?"required":"not_required",onChange:B=>me({requireApprovalForDestructiveGit:B.target.value==="required"}),disabled:b,children:[s.jsx("option",{value:"required",children:"Require approval"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(Lt,{label:"Dirty workspace behavior",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:pe.dirtyWorkspaceBehavior||"warn",onChange:B=>me({dirtyWorkspaceBehavior:B.target.value}),disabled:b,children:[s.jsx("option",{value:"warn",children:"Warn and continue"}),s.jsx("option",{value:"block",children:"Block task"}),s.jsx("option",{value:"checkpoint_then_continue",children:"Checkpoint then continue"})]})}),s.jsx(Lt,{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(pe.maxParallelTasks??2),onChange:B=>me({maxParallelTasks:Number(B.target.value)}),disabled:b,children:[1,2,3,4,5,6,7,8].map(B=>s.jsx("option",{value:B,children:B},B))})})]}),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(Lt,{label:"Node removal session cleanup",hint:"Separate transcript cleanup from runtime/process cleanup. Preserve is safest when completed work may need review.",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:pe.sessionCleanupOnNodeRemove||"preserve",onChange:B=>me({sessionCleanupOnNodeRemove:B.target.value}),disabled:b,children:mn.map(B=>s.jsx("option",{value:B.value,children:B.label},B.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((le=mn.find(B=>B.value===pe.sessionCleanupOnNodeRemove))==null?void 0:le.description)||mn[0].description})]}),b&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving policy..."})]}),s.jsxs(St,{title:"Visualization",description:"Live mesh topology: branches, worktrees, sessions, and orphan detection.",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",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.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:fe,disabled:j,children:j?"Loading...":"Refresh Graph"})]}),H&&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:H}),!N||!D?s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:j?"Loading graph...":"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology from this standalone daemon."}):s.jsx(Lu,{graph:N,status:D,emptyMessage:"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology from this standalone daemon.",daemonId:n,sendDaemonCommand:e})]}),s.jsxs(St,{title:"Nodes",description:"Workspaces participating in this mesh.",children:[s.jsx("div",{className:"flex justify-end mb-3",children:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>ye(!0),children:"+ Add Node"})}),J&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:"Add Node"}),s.jsx("button",{onClick:()=>ye(!1),className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(wt,{size:16})})]}),s.jsx(Lt,{label:"Workspace Path",children:s.jsx(ga,{value:he,onChange:B=>ne(B.target.value),placeholder:"/Users/dev/projects/myapp",autoFocus:!0})}),s.jsx(Lt,{label:"Provider Priority",hint:"Order used when launching without an explicit provider. Empty means fail closed unless a provider is selected explicitly.",children:s.jsx(al,{value:ue,availableProviders:o,onChange:Se})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:Ce,disabled:!he.trim(),className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>ye(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),ve.nodes.length===0?s.jsx(Dn,{icon:s.jsx(Ns,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:ve.nodes.map(B=>{const z=jn(B),de=Mw(B),re=Aw(B,T),R=Lw(B,r),q=A===B.id;return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary cursor-pointer transition-colors ${q?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`,role:"button",tabIndex:0,onClick:()=>_(q?null:B.id),onKeyDown:ce=>{(ce.key==="Enter"||ce.key===" ")&&(ce.preventDefault(),_(q?null:B.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"text-sm font-medium",children:B.workspace.split("/").pop()}),re.length>0&&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:[re.length," active task",re.length===1?"":"s"]})]}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:B.workspace}),s.jsx("div",{className:"mt-3 max-w-2xl",onClick:ce=>ce.stopPropagation(),children:s.jsxs(Lt,{label:"Provider priority",hint:"Used when launches omit an explicit provider. Empty keeps fail-closed behavior until a provider is selected manually.",children:[s.jsx(al,{value:f[B.id]??z,availableProviders:o,onChange:ce=>C(Ne=>({...Ne,[B.id]:ce})),disabled:g===B.id,saveButton:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:ce=>{ce.stopPropagation(),ie(B)},disabled:g===B.id,children:g===B.id?"Saving...":"Save policy"})}),s.jsxs("div",{className:"mt-2 text-[12px]",children:[s.jsx("span",{className:"text-text-muted",children:"Effective provider priority: "}),s.jsx("span",{className:de.configured?"text-text-primary font-mono":"text-amber-400",children:de.label}),de.launchBlockedMessage&&s.jsxs("span",{className:"ml-2 text-amber-400",children:["(",de.launchBlockedMessage,")"]})]})]})})]}),s.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:ce=>{ce.stopPropagation(),ee(B.id)},children:s.jsx(wt,{size:14})})]}),q&&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:B.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",s.jsx("span",{className:de.configured?"text-green-400":"text-amber-400",children:de.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:B.repoRoot||B.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",R.length]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Branch / git:"})," not loaded in standalone list view"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Health:"})," ",re.length>0||R.length>0?"active":"idle/unknown"]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active queue assignments"}),re.length===0?s.jsx("div",{children:"No active assigned queue task for this node."}):s.jsx("ul",{className:"m-0 pl-4",children:re.map(ce=>s.jsx("li",{className:"font-mono",children:_w(ce)},ce.id))})]}),R.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:R.map(ce=>s.jsxs("li",{className:"font-mono",children:[ce.provider," / ",ce.status," / ",ce.id]},ce.id))})]})]})]},B.id)})})]}),s.jsx(Rw,{meshId:ve.id,availableCliAgents:a})]})}function fi(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function Dw(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=fi();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 Ut(e,t){return await fetch(Dw(e),{credentials:"same-origin",...t})}function Bu(){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 Ew{constructor(){Ze(this,"adapters",new Map);Ze(this,"states",new Map);Ze(this,"runtimeListeners",new Map);Ze(this,"screenshotCallbacks",new Map);Ze(this,"statusCallbacks",new Set)}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)}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"}sendData(t,r){return!1}sendPtyInput(t,r,n){return!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,l){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:o,rows:l})}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 Ut(`${a.pathname}${a.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(c=d.error)}catch{}return{success:!1,error:c}}const l=await o.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof l.seq=="number"?l.seq:0,text:typeof l.text=="string"?l.text:"",truncated:!!l.truncated,cols:typeof l.cols=="number"?l.cols:void 0,rows:typeof l.rows=="number"?l.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 Yt=new Ew;function $w(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=fi();return r?`${t}?token=${encodeURIComponent(r)}`:t}const pn=$w(),oc=3e3,Bw=3e4;let Ot=null,Ow=0;const Wn=new Map;let ms=null,Ir=null;function ic(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function fr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function Fw(e){return e==="connected"?"connected":e}async function kn(e,t,r){const n=vd(e,r||{}),a=Ot;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++Ow}_${Date.now()}`;return new Promise((l,c)=>{const d=setTimeout(()=>{Wn.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);Wn.set(o,{resolve:m=>{clearTimeout(d),l(m)},reject:m=>{clearTimeout(d),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 No(e,t){const r=Ot;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 Ww(e,t,r){const n=Ot;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=vd(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}}class Kw{constructor(t){Ze(this,"daemonId");Ze(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Ot==null?void 0:Ot.readyState)===WebSocket.OPEN}get connectionState(){return(Ot==null?void 0:Ot.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return kn(this.daemonId,t,r)}async sendInput(t,r){return kn(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,ms&&(clearInterval(ms),ms=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await kn(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());Yt.emitScreenshot(this.daemonId,a)}}catch{}};r(),ms=setInterval(r,2e3)}stopScreenshots(t){ms&&(clearInterval(ms),ms=null)}}let Pt=null;function Hw(e){return(!Pt||Pt.daemonId!==e)&&(Pt=new Kw(e)),Pt}function Uw({children:e}){const t=i.useRef(Mr()),r=Mr();t.current=r;const{setUserName:n}=cs(),a=i.useRef(n);a.current=n;const o=i.useRef(null),l=i.useRef(null),[,c]=i.useState("disconnected"),d=i.useCallback((p,g)=>{c(p),Ir==null||Ir(p,g)},[]),m=i.useRef(null),u=i.useRef(),h=i.useRef(oc),x=i.useRef(!0),S=i.useRef(!1),b=i.useRef("initial_connect");return i.useEffect(()=>{x.current=!0,S.current=!1;function p(){var f,C;if(!x.current||((f=m.current)==null?void 0:f.readyState)===WebSocket.OPEN||((C=m.current)==null?void 0:C.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${pn}...`),fr("connect_attempt",{url:pn,reason:b.current,delayMs:h.current});let v;try{v=new WebSocket(pn)}catch(T){console.error("[Standalone WS] Failed to create WebSocket:",T),g();return}m.current=v,v.onopen=()=>{if(!x.current){v.close();return}d("connected"),h.current=oc,fr("open",{url:pn,reason:b.current}),Qt.resubscribeAll({sendData:No}),console.log("[Standalone WS] Connected")},Ot=v,v.onmessage=T=>{var k,A;try{const _=JSON.parse(T.data);if((_.type==="command_result"||_.type==="error")&&_.requestId){const N=Wn.get(_.requestId);N&&(Wn.delete(_.requestId),_.type==="error"?N.reject(new Error(((k=_.data)==null?void 0:k.message)||"Command failed")):N.resolve(_.data));return}if(_.type==="session_output"){const N=_.sessionId||_.cliId||_.cliType;N&&Yt.emitSessionOutput(N,typeof _.data=="string"?_.data:"",typeof _.seq=="number"?_.seq:void 0);return}if(_.type==="runtime_snapshot"){Yt.emitRuntimeSnapshot(_.sessionId,typeof _.text=="string"?_.text:"",typeof _.seq=="number"?_.seq:0,!!_.truncated,typeof _.cols=="number"?_.cols:void 0,typeof _.rows=="number"?_.rows:void 0);return}if(_.type==="topic_update"){const N=_.update;N&&Qt.publish(N);return}if(_.type==="status"||_.type==="initial_state"){const N=_.data;if(!N)return;const{injectEntries:w,markLoaded:D,getIdes:M}=t.current,j=N.instanceId||"standalone",W=M().find(I=>I.id===j),H=Hw(j);Yt.register(j,H),Yt.setState(j,"connected"),d("connected",j),Yt.emitStatus(j,N);const $=Rn(N,{daemonId:j,existingDaemon:W,existingEntries:M()});ic("ws_status",{type:_.type,daemonId:j,sessions:(N.sessions||[]).map(I=>({id:I.id,parentId:I.parentId,providerType:I.providerType,kind:I.kind,transport:I.transport,unread:I.unread,inboxBucket:I.inboxBucket,lastSeenAt:I.lastSeenAt,lastUpdated:I.lastUpdated,title:I.title})),recentLaunches:(N.recentLaunches||[]).map(I=>({id:I.id,providerType:I.providerType,kind:I.kind,workspace:I.workspace,lastLaunchedAt:I.lastLaunchedAt}))}),ic("entries",{daemonId:j,entries:$.filter(I=>I.type!=="adhdev-daemon").map(I=>({id:I.id,type:I.type,unread:I.unread,inboxBucket:I.inboxBucket,lastSeenAt:I.lastSeenAt,lastUpdated:I.lastUpdated,sessionId:I.sessionId}))}),$.length>0&&w($,{authoritativeDaemonIds:[j]}),D(),l.current!==j&&((A=o.current)==null||A.call(o),l.current=j,o.current=Qt.subscribe({sendData:No},j,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${j}`,params:{includeSessions:!0}},I=>{if(I.topic!=="daemon.metadata")return;const y=t.current.getIdes(),F=y.find(E=>E.id===j),P=Rn(I.status,{daemonId:j,existingDaemon:F,existingEntries:y,timestamp:I.timestamp});P.length>0&&t.current.injectEntries(P,{authoritativeDaemonIds:[j]}),I.userName&&a.current&&a.current(I.userName)}))}}catch(_){console.error("[Standalone WS] Parse error:",_)}},v.onclose=T=>{x.current&&(Pt==null||Pt.stopScreenshots(),Pt&&Yt.setState(Pt.daemonId,"disconnected"),d("disconnected"),m.current=null,b.current=`close:${T.code}${T.wasClean?":clean":":unclean"}`,fr("close",{code:T.code,reason:T.reason||"",wasClean:T.wasClean}),g())},v.onerror=T=>{S.current||!x.current||(b.current="error",fr("error",{message:T instanceof Event?"event":String(T),readyState:v.readyState}),console.warn("[Standalone WS] Error, will reconnect:",T))}}function g(){if(!x.current)return;clearTimeout(u.current);const v=h.current;console.log(`[Standalone WS] Reconnecting in ${v}ms...`),fr("schedule_reconnect",{reason:b.current,delayMs:v}),u.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,Bw),p()},v)}return p(),()=>{var v;x.current=!1,S.current=!0,(v=o.current)==null||v.call(o),o.current=null,l.current=null,clearTimeout(u.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,Ot=null),Pt&&(Pt.stopScreenshots(),Yt.unregister(Pt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function zw({children:e}){const[t,r]=i.useState("disconnected"),[n,a]=i.useState(null);i.useEffect(()=>(Ir=(l,c)=>{r(l),c&&a(c)},()=>{Ir=null}),[]);const o=i.useMemo(()=>{const l=t==="connected",c=Fw(t),d={};return n&&(d[n]=c),d.standalone=c,{wsStatus:t,isConnected:l,connectionStates:d}},[t,n]);return s.jsx(Wm,{connectionOverrides:o,children:s.jsx(Uw,{children:e})})}const Ou="adhdev_standalone_font_preferences",Ss={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},ra=[{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"}],Lr=[{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"}],Vw=new Set(ra.map(e=>e.id)),Gw=new Set(Lr.map(e=>e.id));function Vt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Sn("chat",t.chat),code:Sn("code",t.code),terminal:Sn("terminal",t.terminal)}}function Sn(e,t){const r=Ss[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"?Vw:Gw).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function Nn(e,t){var a;const r=Sn(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?ra:Lr;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function qw(e){const t=Vt(e),r=Nn("chat",t.chat),n=Nn("code",t.code),a=Nn("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function fs(e,t=document.documentElement){const r=Vt(e),n=qw(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function Co(e){const t=Vt(e);try{localStorage.setItem(Ou,JSON.stringify(t))}catch{}return t}function Yw(){try{const e=localStorage.getItem(Ou);if(e)return Vt(JSON.parse(e))}catch{}return Ss}function Xw(){return fs(Yw())}function xr(e,t){var n;const r=e==="chat"?ra:Lr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const Jw=[{id:"dashboard",path:"/dashboard",icon:s.jsx(bc,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(is,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(zs,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(Kn,{}),label:"Settings"}];function Qw({children:e}){const t=As(),r=To(),n=i.useMemo(()=>Jw.map(o=>({...o,active:r.pathname.startsWith(o.path),onSelect:()=>t(o.path)})),[r.pathname,t]),a=i.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(yc,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(vc,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(tb,{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.81"]}),footerActions:({collapsed:o,toggleCollapsed:l})=>s.jsxs("div",{className:`nav-item cursor-pointer ${o?"justify-center py-2.5 px-0":"mt-1"}`,onClick:l,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 Zw=[{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(es,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(wc,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(_t,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(zs,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(yc,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],ej=[{icon:s.jsx(np,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(bc,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Hn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Jm,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(gc,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Zm,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],tj=[{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 sj(){return s.jsxs(kr,{icon:s.jsx(vc,{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.81"]}),children:[s.jsx(St,{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(St,{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:Zw.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(St,{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:wd.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:kd.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:jd.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(St,{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:ej.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(St,{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:tj.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(Dn,{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(hp,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Qa(e,t,r){return{...e,[t]:r}}function Za({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:l=>{const c=l.target.value;o(c==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:c})},children:a.map(l=>s.jsx("option",{value:l.id,children:l.label},l.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:l=>o({preset:"custom",customFamily:l.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:Nn(e,n)})]})]})]})}function rj({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:o,onSave:l,onResetToSaved:c,onResetToDefaults:d}){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(Za,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:ra,onChange:u=>o(Qa(e,"chat",u))}),s.jsx(Za,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Lr,onChange:u=>o(Qa(e,"code",u))}),s.jsx(Za,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Lr,onChange:u=>o(Qa(e,"terminal",u))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",xr("chat",e.chat.preset)," · Code: ",xr("code",e.code.preset)," · Terminal: ",xr("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",xr("chat",Ss.chat.preset)," / ",xr("code",Ss.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:l,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:d,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function nj(){const{ides:e}=cs(),t=e.find(X=>X.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=jt(),{userName:a}=cs(),[o,l]=i.useState(a||""),[c,d]=i.useState(null),[m,u]=i.useState(null),[h,x]=i.useState(Ss),[S,b]=i.useState(!1),[p,g]=i.useState(""),[v,f]=i.useState(""),[C,T]=i.useState("127.0.0.1"),[k,A]=i.useState(""),[_,N]=i.useState(""),[w,D]=i.useState(""),[M,j]=i.useState(""),[W,H]=i.useState(""),[$,I]=i.useState(!1),y=async()=>{const xe=await(await Ut("/auth/session")).json();d(xe)},F=async()=>{const xe=await(await Ut("/api/v1/standalone/preferences")).json();u(xe),T(xe.standaloneBindHost);const fe=Vt(xe.standaloneFontPreferences);x(fe),fs(fe),Co(fe)};i.useEffect(()=>{a!==void 0&&l(a)},[a]),i.useEffect(()=>{Promise.all([y(),F()]).catch(X=>{j(X instanceof Error?X.message:String(X))})},[]),i.useEffect(()=>{fs(h)},[h]);const P=X=>{const xe=X.target.value.trim();t!=null&&t.id&&xe!==a&&n(t.id,"set_user_name",{userName:xe}).catch(console.error)},[E,G]=i.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),J=X=>{G(X);try{localStorage.setItem("adhdev_sound",X?"1":"0")}catch{}},ye=async()=>{g(""),f(""),b(!0);try{const X=Vt(h),xe=await Ut("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:X})}),fe=await xe.json();if(!xe.ok)throw new Error((fe==null?void 0:fe.error)||"Failed to save standalone font preferences");const we=Vt(fe.standaloneFontPreferences);u(fe),x(we),fs(we),Co(we),f("Standalone chat fonts saved for this self-hosted dashboard.")}catch(X){g(X instanceof Error?X.message:String(X))}finally{b(!1)}},he=()=>{const X=Vt(m==null?void 0:m.standaloneFontPreferences);g(""),f(""),x(X),fs(X)},ne=()=>{g(""),f(""),x(Ss),fs(Ss)},ue=async()=>{j(""),H(""),I(!0);try{const X=await Ut("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:C})}),xe=await X.json();if(!X.ok)throw new Error((xe==null?void 0:xe.error)||"Failed to save standalone network preference");u(xe),T(xe.standaloneBindHost),H(xe.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){j(X instanceof Error?X.message:String(X))}finally{I(!1)}},Se=async()=>{if(j(""),H(""),_.trim().length<4){j("Password must be at least 4 characters.");return}if(_!==w){j("New password and confirmation do not match.");return}I(!0);try{const X=await Ut("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,newPassword:_})}),xe=await X.json();if(!X.ok)throw new Error((xe==null?void 0:xe.error)||"Failed to save password");d(xe),await F(),A(""),N(""),D(""),H(c!=null&&c.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Bu()}catch(X){j(X instanceof Error?X.message:String(X))}finally{I(!1)}},ve=async()=>{j(""),H(""),I(!0);try{const X=await Ut("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,clear:!0})}),xe=await X.json();if(!X.ok)throw new Error((xe==null?void 0:xe.error)||"Failed to clear password");d(xe),await F(),A(""),N(""),D(""),H("Standalone password disabled.")}catch(X){j(X instanceof Error?X.message:String(X))}finally{I(!1)}};return s.jsxs(kr,{icon:s.jsx(Kn,{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(St,{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.81"]}),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(St,{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:C==="127.0.0.1",onChange:()=>T("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:C==="0.0.0.0",onChange:()=>T("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:()=>{ue()},disabled:$,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:$?"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(St,{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."}),M&&s.jsx(Os,{variant:"error",children:M}),W&&s.jsx(Os,{variant:"success",children:W}),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=>A(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:_,onChange:X=>N(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:w,onChange:X=>D(X.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{Se()},disabled:$,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:$?"Saving…":c!=null&&c.hasPasswordAuth?"Update password":"Enable password"}),(c==null?void 0:c.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{ve()},disabled:$,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(St,{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(St,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(db,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(St,{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(hb,{})]}),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(jb,{})]}),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(rj,{value:h,savedValue:Vt(m==null?void 0:m.standaloneFontPreferences),saving:S,error:p,notice:v,onChange:x,onSave:()=>{ye()},onResetToSaved:he,onResetToDefaults:ne})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout."}),s.jsx(Nb,{})]})]})}),s.jsx(St,{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(ib,{}),s.jsx(hs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(pp,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:E,onChange:J})]})}),s.jsx(St,{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(Xm,{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=>l(X.target.value),onBlur:P,onKeyDown:X=>{X.key==="Enter"&&X.currentTarget.blur()}})]})})})]})}Zx();vb();Xw();const aj=fc({baseUrl:"",getToken:fi});function oj({children:e}){const[t,r]=i.useState(null),[n,a]=i.useState(!0),[o,l]=i.useState(""),[c,d]=i.useState(""),[m,u]=i.useState(!1),h=async()=>{a(!0),d("");try{const b=await(await Ut("/auth/session")).json();r(b)}catch(S){d(S instanceof Error?S.message:String(S))}finally{a(!1)}};i.useEffect(()=>{h()},[]),i.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let S=!1;return(async()=>{try{const b=await Ut("/api/v1/standalone/preferences");if(!b.ok)return;const p=await b.json();if(S)return;const g=Vt(p.standaloneFontPreferences);fs(g),Co(g)}catch{}})(),()=>{S=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const x=async S=>{S.preventDefault(),u(!0),d("");try{const b=await Ut("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),p=await b.json();if(!b.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),l(""),Bu()}catch(b){d(b instanceof Error?b.message:String(b))}finally{u(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:x,children:[s.jsx("input",{type:"password",value:o,onChange:S=>l(S.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 lc(){const{ides:e,initialLoaded:t}=cs();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(so,{to:`/machines/${r.id}`,replace:!0}):s.jsx(so,{to:"/dashboard",replace:!0})}function ij(){const e=i.useMemo(()=>({sendCommand:kn,sendData:No,sendPtyInput:Ww}),[]);return s.jsx(Nm,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Um,{client:aj,children:s.jsx(oj,{children:s.jsx(zw,{children:s.jsx(Vm,{value:e,children:s.jsx(Qw,{children:s.jsxs(Cm,{children:[s.jsx(rs,{path:"/dashboard",element:s.jsx(wv,{})}),s.jsx(rs,{path:"/machine",element:s.jsx(lc,{})}),s.jsx(rs,{path:"/machines/:id",element:s.jsx(Iw,{})}),s.jsx(rs,{path:"/machines",element:s.jsx(lc,{})}),s.jsx(rs,{path:"/about",element:s.jsx(sj,{})}),s.jsx(rs,{path:"/settings",element:s.jsx(nj,{})}),s.jsx(rs,{path:"/mesh",element:s.jsx(Pw,{})}),s.jsx(rs,{path:"*",element:s.jsx(so,{to:"/dashboard",replace:!0})})]})})})})})})})}cx({connectionManager:Yt});Im(document.getElementById("root")).render(s.jsx(ij,{}));
|