@adhdev/daemon-standalone 0.9.59 → 0.9.60

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,7 +1,7 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-DbJP_JGY.js","assets/vendor-BRZ4K-AC.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
- var gd=Object.defineProperty;var yd=(e,t,r)=>t in e?gd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ye=(e,t,r)=>yd(e,typeof t!="symbol"?t+"":t,r);import{r as i,j as s,M as Ia,a as vd,b as wd,c as jd,u as Ps,R as kt,d as sr,t as kd,e as Sd,D as Nd,f as aa,g as oa,h as La,i as Cd,k as Td,B as Md,l as Ad,m as Xt,N as ia,n as Id}from"./vendor-BRZ4K-AC.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 c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&n(c)}).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 Ld(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 Ns=Ld();function Co(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 Rd(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function _d(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Bi(e,t){var f;if(!e)return t??null;if(!t)return e??null;const r=_d(e,"messages"),n=r?Array.isArray(e.messages)?e.messages:[]:void 0,a=e.status==="waiting_approval"||Array.isArray((f=e.activeModal)==null?void 0:f.buttons)&&e.activeModal.buttons.length>0,o=r&&a&&(n==null?void 0:n.length)===0&&Array.isArray(t.messages)&&t.messages.length>0,c=r?o?t.messages:n??[]:t.messages,l=e.activeModal||(e.status==="waiting_approval"?t.activeModal:null),d={...t,...e,activeModal:l,inputContent:e.inputContent??t.inputContent};return r?{...d,messages:c}:d}function qs(e,t){const r=Rd(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:Bi(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)}}function Ki(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(c=>c.id===a.id);return o?qs(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 To(e){return!!e&&typeof e=="object"&&"text"in e}function Ra(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:To(o)?String(o.text||""):"").join(r):To(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Kt(e){return Ra(e,{normalizeWhitespace:!0})}const Oi=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}),Wi=i.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Mo(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 Fi(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,c=t.versionMismatch===!0||e.versionMismatch===!0,l=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||c&&a&&o&&a!==o)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function Pd(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 wn(e){if(!e||typeof e!="object")return"";const t=e,r=Pd(Kt(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 Dd(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=wn(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:wn(e[0]),last:wn(e[e.length-1])}}function ca(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function la(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(ca(e)&&ca(t)){const c=e.messages;Array.isArray(c)&&c===t.messages&&r.add(c)}if(Array.isArray(e)&&Array.isArray(t)){const c=Math.min(e.length,t.length);for(let l=0;l<c;l+=1)la(e[l],t[l],r);return}const n=e,a=t,o=new Set([...Object.keys(n),...Object.keys(a)]);for(const c of o)c!=="messages"&&la(n[c],a[c],r)}function Xs(e,t){return Array.isArray(e)?e.map(r=>Xs(r,t)):!e||typeof e!="object"?e:ca(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?Dd(a,t):Xs(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,Xs(n,t)]))}function Ed(e,t){try{const r=new WeakSet;return la(e,t,r),JSON.stringify(Xs(e,r))===JSON.stringify(Xs(t,r))}catch{return!1}}function da(e,t,r){return Ed(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Hi(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function $d(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function Ao(e,t,r,n){var l;const a=(l=t.chats)!=null&&l.length?t.chats:e.chats,o=Ki(e.childSessions,t.childSessions,{preserveMissing:n}),c=Bi(t.activeChat,e.activeChat);return Fi(e,t,{...e,...t,chats:a,childSessions:o,activeChat:c,_lastUpdate:r})}function Bd(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=Ki(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((o=e.chats)!=null&&o.length)&&(n.chats=t.chats);for(const c 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"])$d(n,t,c);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function Kd(e,t,r,n){const a=Bd(e,t,n),o=Object.keys(a).length>0?Fi(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return da(e,o,r)}function Od(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 c=Hi(o);c&&r.add(c),c&&o.type!=="adhdev-daemon"&&n.add(c),c&&o.type==="adhdev-daemon"&&o._sessionListAuthoritative&&a.add(c)}return{incomingIds:t,incomingDaemonIds:r,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:a}}function Wd(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 Fd(e,t,r,n){return!!(r.has(t)&&e.transport&&!n.has(t))}function Hd(e,t,r){var u,p;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(m=>({...m,_lastUpdate:n}));const o=new Map;for(const m of t)o.set(m.id,m);const{incomingIds:c,incomingDaemonIds:l,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:f}=Od(e);for(const m of e){const y=o.get(m.id);if(!y){o.set(m.id,{...m,_lastUpdate:n});continue}const N=Mo(m),h=Mo(y),j=Hi(m),x=!a.has(j);if(N>h){const A=Ao(y,m,n,x);o.set(m.id,da(y,A,n));continue}if(N<h){o.set(m.id,Kd(y,m,n,x));continue}const b=m.timestamp||n,v=y._lastUpdate||y.timestamp||0;if(b>=v){const A=Ao(y,m,n,x);o.set(m.id,da(y,A,n));continue}(u=m.chats)!=null&&u.length&&!((p=y.chats)!=null&&p.length)&&o.set(m.id,{...y,chats:m.chats})}for(const[m,y]of o){const N=y.daemonId||m.split(":")[0];if(!l.has(N))continue;if(a.has(N)&&f.has(N)&&!c.has(m)){o.delete(m);continue}const h=n-(y._lastUpdate||y.timestamp||0);Wd(y,N,h,c,a,d)&&o.delete(m)}for(const[m,y]of o){const N=y.daemonId||m.split(":")[0];if(Fd(y,N,l,d))continue;n-(y._lastUpdate||y.timestamp||0)>3e5&&y.status!=="online"&&o.delete(m)}return Array.from(o.values())}function Ud(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 zd({children:e,connectionOverrides:t}){const[r,n]=i.useState([]),[a,o]=i.useState(!1),[c,l]=i.useState([]),[d,f]=i.useState(void 0),u=i.useRef(r);i.useEffect(()=>{u.current=r},[r]);const p=i.useCallback((x,b)=>{n(v=>{let A=!1;const g=v.map(M=>M.id!==x||M.chats===b?M:(A=!0,{...M,chats:b}));return A?g:v})},[]),m=i.useCallback((x,b)=>{n(v=>{const A=v.length===0?x:Hd(x,v,b),g=!Ud(v,A);return g&&Ns.record({kind:"dashboard.entries_applied",payload:{incoming:Co(x),next:Co(A)}}),g?A:v})},[]),y=i.useCallback(()=>o(!0),[]),N=i.useMemo(()=>({injectEntries:m,markLoaded:y,getIdes:()=>u.current}),[m,y]),h=t,j=i.useMemo(()=>({ides:r,updateRouteChats:p,initialLoaded:a,toasts:c,setToasts:l,wsStatus:(h==null?void 0:h.wsStatus)??"connected",isConnected:(h==null?void 0:h.isConnected)??!0,connectionStates:(h==null?void 0:h.connectionStates)??{},connectionTransports:(h==null?void 0:h.connectionTransports)??{},showReconnected:(h==null?void 0:h.showReconnected)??!1,retryConnection:h==null?void 0:h.retryConnection,retryServerConnection:h==null?void 0:h.retryServerConnection,connectionLoginUrl:h==null?void 0:h.connectionLoginUrl,isP2PActive:(h==null?void 0:h.isP2PActive)??!1,p2pStates:(h==null?void 0:h.p2pStates)??{},userRole:h==null?void 0:h.userRole,connectionRetryStatuses:h==null?void 0:h.connectionRetryStatuses,userName:d,setUserName:f}),[r,p,a,c,h==null?void 0:h.wsStatus,h==null?void 0:h.isConnected,h==null?void 0:h.connectionStates,h==null?void 0:h.connectionTransports,h==null?void 0:h.showReconnected,h==null?void 0:h.retryConnection,h==null?void 0:h.retryServerConnection,h==null?void 0:h.connectionLoginUrl,h==null?void 0:h.isP2PActive,h==null?void 0:h.p2pStates,h==null?void 0:h.userRole,h==null?void 0:h.connectionRetryStatuses,d]);return s.jsx(Wi.Provider,{value:N,children:s.jsx(Oi.Provider,{value:j,children:e})})}function ds(){return i.useContext(Oi)}function rr(){return i.useContext(Wi)}function Ui(e){const{baseUrl:t,getToken:r,onUnauthorized:n}=e;function a(l){return l.startsWith("http")?l:`${t}${l.startsWith("/")?"":"/"}${l}`}function o(l){const d=r==null?void 0:r(),f=a(l),u=l.startsWith("http")?new URL(f):new URL(f,typeof window<"u"?window.location.origin:"http://localhost");return d&&u.searchParams.set("token",d),!l.startsWith("http")&&!t?`${u.pathname}${u.search}${u.hash}`:u.toString()}async function c(l,d={}){const f={"Content-Type":"application/json",...d.headers||{}},u=r==null?void 0:r();u&&(f.Authorization=`Bearer ${u}`);const p=a(l),m=new AbortController,y=setTimeout(()=>m.abort(),15e3);try{const N=await fetch(p,{...d,headers:f,signal:m.signal});if(N.status===401)throw n==null||n(),new Error("Unauthorized");if(!N.ok){const h=await N.json().catch(()=>({error:N.statusText}));throw new Error(h.error||`API Error: ${N.status}`)}return N.json()}finally{clearTimeout(y)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,d,f={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:d,payload:f})}),execTerminal:(l,d,f)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:f})}),sendAgentMessage:(l,d,f)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:f})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,d,f)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:d,action:f?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,d,f={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:d,payload:f})}),getMuxEventsUrl:l=>o(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>o(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const Vd=Ui({baseUrl:"http://localhost:3847"}),Gd=i.createContext(Vd);function qd({client:e,children:t}){return s.jsx(Gd.Provider,{value:e,children:t})}const Yd={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},zi=i.createContext(Yd);function Xd({value:e,children:t}){return s.jsx(zi.Provider,{value:e,children:t})}function mt(){return i.useContext(zi)}function Jd(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 Qd(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Vi(e){return e?Jd([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Qd(e.content)]):""}const Oe={size:18};function Gi({size:e=Oe.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 _a({size:e=Oe.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 us({size:e=Oe.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 qi({size:e=Oe.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 Zd({size:e=Oe.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 eu({size:e=Oe.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 Yi({size:e=Oe.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 tu({size:e=Oe.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 on({size:e=Oe.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 Xi({size:e=Oe.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 su({size:e=Oe.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 Ut({size:e=Oe.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 Tt({size:e=Oe.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 Pa({size:e=Oe.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 ru({size:e=Oe.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 Cs({size:e=Oe.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 lr({size:e=Oe.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 nr({size:e=Oe.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 ar({size:e=Oe.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 Ji({size:e=Oe.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 Da({size:e=Oe.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 Qi({size:e=Oe.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 nu({size:e=Oe.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 Ea({size:e=Oe.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 au({size:e=Oe.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 $a({size:e=Oe.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 Zi({size:e=Oe.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 St({size:e=Oe.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 ou({size:e=Oe.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 iu({size:e=Oe.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 cu({size:e=Oe.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 lu({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),s.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function cn({size:e=Oe.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 du({size:e=Oe.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 uu({size:e=Oe.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 fu({size:e=Oe.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 mu({size:e=Oe.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 pu({size:e=Oe.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 hu({size:e=Oe.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 xu({size:e=Oe.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 bu({size:e=Oe.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 gu({size:e=Oe.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 yu({size:e=Oe.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 vu({size:e=Oe.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 wu({size:e=Oe.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 ec=[vd,{singleTilde:!1}],tc=[ec,wd,jd],ju=[ec],Ba=200,ku=80,Io=650,Ks=new Map;function Gr(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function Su(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}:${Vi(n)}`}function Nu(e,t,r,n){return e||!t?!1:Gr(r,n)}function Cu({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=ku,bottomThresholdPx:a=Ba}){const o=Math.max(0,Number(e)||0),c=Math.max(0,Number(t)||0),l=Math.max(0,Number(r)||0);return Math.max(0,c-l)<=0?{showTop:!1,showBottom:!1}:{showTop:o>n,showBottom:Math.max(0,c-o-l)>a}}function Tu(e){return Cu({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function Ys(e,t=Ba){return!!e&&e.fromBottom>=t}function Mu(e,t){return Gr(e,t)?!Ys(e):!0}function Au({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function Iu({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function jn(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function sc(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Lu(e,t,r){return Number(e.receivedAt||r[qr(e,t)]||0)||0}function rc(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Ru(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function gr(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 kn(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 Lo(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):rc(e)?s.jsx(Ia,{remarkPlugins:tc,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function yr({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:Lo(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=kn(r);return a?s.jsx("img",{src:a,alt:gr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=kn(r);return a?s.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=kn(r);return a?s.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"},`video-${n}`):r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:gr(r.uri,"video")},`video-link-${n}`):null}if(r.type==="resource_link")return r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:r.name||gr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=gr(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}),Lo(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 qr(e,t){const r=e,n=Ra(e.content,{joiner:`
3
- `});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 _u=i.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(Ia,{remarkPlugins:ju,children:t.text}),s.jsx("span",{className:"action-time",children:sc(t.timestamp)})]})},(e,t)=>e.log===t.log),Pu=i.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:o,isTextExpanded:c,onToggleTextExpanded:l}){var M,T,k;const d=(t.role||"").toLowerCase(),f=d==="user"||d==="human",u=t.kind||(d==="tool"?"tool":"standard"),p=Ru(t.content)?t.content:null,m=!!(p!=null&&p.some(w=>w.type!=="text")),y=Ra(t.content,{joiner:`
4
- `});if(u==="thought"){const w=typeof((M=t.meta)==null?void 0:M.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought",children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(cu,{size:13}),s.jsx("span",{children:w})]}),s.jsx("div",{className:"chat-msg-body",children:y})]})}if(u==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),m&&p?s.jsx("div",{className:"tool-text w-full",children:s.jsx(yr,{parts:p,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:y})]});if(u==="terminal"){const w=(T=t.meta)!=null&&T.isRunning?"⏳":"✅",K=typeof((k=t.meta)==null?void 0:k.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal",children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:w}),s.jsx("span",{children:K})]}),m&&p?s.jsx("div",{className:"chat-msg-body",children:s.jsx(yr,{parts:p,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:y})]})}if(u==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:m&&p?s.jsx(yr,{parts:p,renderAsPreformatted:!1}):y.slice(0,100)});const N=t.meta,j=(typeof(N==null?void 0:N.renderMode)=="string"?N.renderMode.trim():"")==="preformatted",x=y,b=!1,v=x,A=j,g=!A&&rc(v);return s.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${f?"self-end":"self-start"}`,children:(x||m||f)&&s.jsxs("div",{className:`chat-bubble ${f?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${x||m?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:f?a||"You":t.senderName||n}),r!=null&&s.jsx("span",{className:"chat-time",children:sc(r)})]}),(x||m)&&s.jsx("div",{className:"chat-markdown",children:m&&p?s.jsx(yr,{parts:p,renderAsPreformatted:A}):A?s.jsx("pre",{className:"chat-preformatted",children:v}):g?s.jsx(Ia,{remarkPlugins:tc,children:v}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:v})}),b]})})},(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),Du=i.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:o=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:d={},lastMessageHash:f,emptyState:u,onLoadMore:p,isLoadingMore:m,hasMoreHistory:y,hiddenLiveCount:N=0,loadError:h,scrollToBottomRequestNonce:j,isVisible:x=!0},b){const v=i.useRef(null),A=i.useRef(null),g=i.useRef(null),M=i.useRef(0),T=i.useRef(""),k=i.useRef(""),w=i.useRef(!1),K=i.useRef(null),R=i.useRef(!1),S=i.useRef(null),O=i.useRef(!1),[U,P]=i.useState(new Set),[C,I]=i.useState({showTop:!1,showBottom:!1}),W=i.useRef(!1),E=i.useRef(!1),$=i.useRef(x),F=i.useRef(x),J=i.useRef(null);F.current=x;const he=()=>{const q=v.current;return q?q.scrollHeight-q.scrollTop-q.clientHeight<Ba:!0},le=i.useCallback(()=>{const q=v.current,Y=q?Tu(q):{showTop:!1,showBottom:!1};I(ce=>ce.showTop===Y.showTop&&ce.showBottom===Y.showBottom?ce:Y)},[]),te=i.useCallback((q="auto")=>{var ce;const Y=v.current;Y&&(Y.scrollTo({top:Y.scrollHeight,behavior:q}),(ce=Y.ownerDocument.defaultView)==null||ce.requestAnimationFrame(()=>le()))},[le]),ye=i.useCallback((q="auto")=>{var ce;const Y=v.current;Y&&(Y.scrollTo({top:0,behavior:q}),(ce=Y.ownerDocument.defaultView)==null||ce.requestAnimationFrame(()=>le()))},[le]),fe=i.useCallback(()=>{var Z;const q=v.current,Y=(Z=window.getSelection)==null?void 0:Z.call(window);if(!q||!Y||Y.rangeCount===0||Y.isCollapsed){O.current=!1;return}const ce=Y.anchorNode,ke=Y.focusNode;O.current=!!(ce&&ke&&q.contains(ce)&&q.contains(ke))},[]),be=Su(t,f),X=i.useCallback(()=>{const q=v.current;if(!q||!l||!F.current)return;const Y={top:q.scrollTop,fromBottom:Math.max(0,q.scrollHeight-q.scrollTop-q.clientHeight),messageFingerprint:be};J.current={contextKey:l,snapshot:Y},Ks.set(l,Y)},[l,be]),ae=i.useCallback((q="auto")=>{K.current!=null&&cancelAnimationFrame(K.current),K.current=requestAnimationFrame(()=>{K.current=null,te(q)})},[te]),ge=i.useCallback(()=>{W.current=!1,R.current=!0,E.current=!0,S.current!=null&&window.clearTimeout(S.current),S.current=window.setTimeout(()=>{R.current=!1,S.current=null},Io)},[]);i.useEffect(()=>{const q=!w.current,Y=k.current!==l;if(k.current=l,q||Y){w.current=!0;const ke=l?Ks.get(l):null,Z=!!ke&&Gr(ke,be);W.current=Z?Ys(ke):!1,R.current=Mu(ke,be),O.current||(Z?requestAnimationFrame(()=>{const Se=v.current;Se&&(jn(Se,ke),W.current=Ys(ke),le(),E.current=!0)}):ae("auto")),M.current=t.length,T.current=be;return}t.length>M.current;const ce=be!==T.current;Au({hasSelection:O.current,userScrolledUp:W.current,hasChatContentChanged:ce})&&ae("auto"),M.current=t.length,T.current=be},[be,l,t.length,ae,le]),i.useEffect(()=>{j&&(ge(),O.current||ae("auto"))},[ge,ae,j]),i.useEffect(()=>{const q=$.current;q&&!x&&X(),F.current=x,$.current=x;const Y=l?Ks.get(l):null;if(Nu(q,x,Y,be)){if(!Y)return;W.current=Ys(Y),R.current=!1,O.current||requestAnimationFrame(()=>{const ce=v.current;ce&&(jn(ce,Y),le())});return}},[x,l,be,ge,X,ae,le]),i.useEffect(()=>()=>{const q=J.current;q&&Ks.set(q.contextKey,q.snapshot),K.current!=null&&cancelAnimationFrame(K.current),S.current!=null&&window.clearTimeout(S.current)},[]),i.useEffect(()=>{const q=A.current,Y=v.current;if(!q||!Y)return;const ce=()=>{S.current!=null&&window.clearTimeout(S.current),S.current=window.setTimeout(()=>{R.current=!1,S.current=null},Io)},ke=new ResizeObserver(()=>{le();const Z=R.current;Iu({hasSelection:O.current,userScrolledUp:W.current,contextAutoScrollActive:Z})&&(ae("auto"),Z&&ce())});return ke.observe(q),Y!==q&&ke.observe(Y),()=>{ke.disconnect(),S.current!=null&&(window.clearTimeout(S.current),S.current=null)}},[ae,l,le]),i.useImperativeHandle(b,()=>({scrollToBottom:(q="smooth")=>{te(q)}}),[te]),i.useEffect(()=>{const q=v.current;if(!q)return;let Y;const ce=()=>{X(),clearTimeout(Y),Y=setTimeout(()=>{W.current=!he(),le()},50)};return q.addEventListener("scroll",ce,{passive:!0}),()=>{q.removeEventListener("scroll",ce),clearTimeout(Y)}},[X,le]),i.useEffect(()=>(document.addEventListener("selectionchange",fe),()=>document.removeEventListener("selectionchange",fe)),[fe]);const ee=i.useRef(0),de=i.useRef(!1);i.useEffect(()=>{const q=v.current;if(!q||!de.current||ee.current===0)return;const Y=q.scrollHeight-ee.current;Y>0&&(q.scrollTop=Y),le(),X(),ee.current=0,de.current=!1},[t.length,X,le]),i.useEffect(()=>{if(E.current||!l)return;const q=Ks.get(l),Y=v.current;if(!(!q||!Y)){if(!Gr(q,be)){te("auto"),E.current=!0;return}jn(Y,q),W.current=Ys(q),le(),E.current=!0}},[l,be,t.length,te,le]);const we=()=>{const q=v.current;q&&(ee.current=q.scrollHeight),de.current=!0,p==null||p()},ue=()=>{W.current=!0,ye("smooth"),X()},xe=()=>{ge(),te("smooth"),X()},se=i.useMemo(()=>{const q=t.map((Z,Se)=>({type:"message",data:Z,index:Se,ts:Lu(Z,Se,d)}));if(!r||r.length===0)return q;const Y=[...r].sort((Z,Se)=>Z.timestamp-Se.timestamp).map((Z,Se)=>({type:"action",data:Z,index:Se,ts:Z.timestamp})),ce=[];let ke=0;for(const Z of q){for(;ke<Y.length&&Z.ts>0&&Y[ke].ts<Z.ts;)ce.push(Y[ke++]);ce.push(Z)}for(;ke<Y.length;)ce.push(Y[ke++]);return ce},[t,r,d]),ie=N>0||!!y,re=N>0?`↑ Show ${Math.min(N,80)} earlier messages${N>80?` (${N} hidden)`:""}`:h?`↻ ${h}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:v,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:A,className:"chat-container-content",children:[m&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),ie&&!m&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:we,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${h&&N===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:re})}),se.length===0&&!ie&&(u||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),se.map(q=>{if(q.type==="action"){const We=q.data;return s.jsx(_u,{log:We},`action-${q.index}`)}const Y=q.data,ce=q.index,ke=qr(Y,ce),Z=Y.receivedAt||d[ke],Se=`${l}-${ke}`,Me=U.has(Se);return s.jsx(Pu,{message:Y,receivedAt:Z,agentName:n,userName:a,isCliMode:o,isTextExpanded:Me,onToggleTextExpanded:()=>P(We=>{const Fe=new Set(We);return Me?Fe.delete(Se):Fe.add(Se),Fe})},`msg-${ke}`)}),c&&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:g})]})}),(C.showTop||C.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[C.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:ue,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),C.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:xe,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),Eu=i.memo(Du,(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.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),$u="modulepreload",Bu=function(e){return"/"+e},Ro={},Ku=function(t,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));a=Promise.allSettled(r.map(d=>{if(d=Bu(d),d in Ro)return;Ro[d]=!0;const f=d.endsWith(".css"),u=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const p=document.createElement("link");if(p.rel=f?"stylesheet":$u,f||(p.as="script"),p.crossOrigin="",p.href=d,l&&p.setAttribute("nonce",l),document.head.appendChild(p),f)return new Promise((m,y)=>{p.addEventListener("load",m),p.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return a.then(c=>{for(const l of c||[])l.status==="rejected"&&o(l.reason);return t().catch(o)})};let _o=!1;const nc=i.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:o="measured"},c)=>{const l=i.useRef(null),[d,f]=i.useState(null),u=i.useRef([]),p=i.useRef(!1),m=i.useRef(!1),y=i.useRef(!1),N=i.useRef(!1),h=()=>{const j=l.current;if(j){p.current&&(j.clear(),p.current=!1);for(const x of u.current)j.write(x.data,x.onProcessed);u.current=[],m.current&&(j.fit(),m.current=!1),y.current&&(j.bumpResize(),y.current=!1),N.current&&(j.scrollToTop(),N.current=!1)}};return i.useImperativeHandle(c,()=>({write:(j,x)=>{l.current?l.current.write(j,x):u.current.push({data:j,onProcessed:x})},clear:()=>{l.current?l.current.clear():(u.current=[],p.current=!0)},reset:()=>{l.current&&typeof l.current.reset=="function"?l.current.reset():(u.current=[],p.current=!0)},resize:(j,x)=>{l.current&&typeof l.current.resize=="function"&&l.current.resize(j,x)},fit:()=>{l.current?l.current.fit():m.current=!0},bumpResize:()=>{l.current?l.current.bumpResize():y.current=!0},scrollToTop:()=>{l.current?l.current.scrollToTop():N.current=!0},getSelection:()=>{var j,x;return((x=(j=l.current)==null?void 0:j.getSelection)==null?void 0:x.call(j))||""},getVisibleText:()=>{var j,x;return((x=(j=l.current)==null?void 0:j.getVisibleText)==null?void 0:x.call(j))||""}}),[]),i.useEffect(()=>{d&&h()},[d]),i.useEffect(()=>{let j=!1;return Ku(()=>import("./terminal-DbJP_JGY.js"),__vite__mapDeps([0,1,2])).then(x=>{_o||(_o=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),j||f(()=>x.GhosttyTerminalView)}).catch(x=>{console.error("[CliTerminal] failed to load terminal renderer",x)}),()=>{j=!0}},[]),d?s.jsx(d,{ref:l,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"}})});nc.displayName="CliTerminal";function vr({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 Po({value:e,max:t,label:r,color:n="#8b5cf6",detail:a,compact:o=!1}){const c=t>0?Math.min(Math.round(e/t*100),100):0,l=c>85?"#ef4444":c>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:[c,"%"]})]}),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:`${c}%`,background:l}})})]}):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:[c,"%"]})]}),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:`${c}%`,background:`linear-gradient(90deg, ${l}, ${l}cc)`}})}),a&&s.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function Ou({cursorPos:e,viewportRef:t,imgRef:r}){var b;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),o=(b=t.current)==null?void 0:b.getBoundingClientRect();if(!o)return null;const c=n.naturalWidth||a.width,l=n.naturalHeight||a.height,d=c/l,f=a.width/a.height;let u,p,m,y;d>f?(u=a.width,p=a.width/d,m=0,y=(a.height-p)/2):(p=a.height,u=a.height*d,m=(a.width-u)/2,y=0);const N=a.left-o.left+m+u*e.nx,h=a.top-o.top+y+p*e.ny,j=Math.max(8,Math.min(o.width-8,N)),x=Math.max(8,Math.min(o.height-8,h));return s.jsxs("div",{style:{position:"absolute",left:j-8,top:x-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 Wu({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:o,imeText:c,setImeText:l,handleImeSubmit:d,isConnActive:f,zoom:u,isMobile:p,mobileFillZoom:m,onZoomOut:y,onZoomReset:N,onZoomIn:h,transportType:j,screenshotUsage:x,lastActionStatus:b}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:v=>v.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[s.jsxs("div",{onClick:t,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[s.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),s.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),s.jsxs("div",{className:"relative",children:[s.jsx("div",{onClick:()=>{n(v=>!v),o(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&s.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:s.jsx("input",{type:"text",placeholder:"Type & Enter...",value:c,autoFocus:!0,onTouchStart:v=>v.stopPropagation(),onChange:v=>l(v.target.value),onKeyDown:v=>{d(v)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{o(v=>!v),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:f?"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:f?"#22c55e":"#eab308",boxShadow:f?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:f?"#22c55e":"#eab308"},children:f?"Connected":"WS"})]}),u>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(u*100),"%"]}),j==="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"}),j==="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"}),x&&x.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:x.budgetExhausted?"#ef4444":"#c4b5fd",background:x.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:x.budgetExhausted?"TURN blocked":`TURN ${x.dailyUsedMinutes}/${x.dailyBudgetMinutes}m`}),b&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:b})]})]}),a&&s.jsxs("div",{onTouchStart:v=>v.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",u<=(p?m:1)+.01?p?"FILL":"FIT":`${Math.round(u*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:v=>{v.stopPropagation(),y()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),s.jsx("button",{onClick:v=>{v.stopPropagation(),N()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:p?"FILL":"FIT"}),s.jsx("button",{onClick:v=>{v.stopPropagation(),h()},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 Fu({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 Hu(){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 Do(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 dr(e,t){const r=i.useRef(null),n=i.useRef(0);i.useEffect(()=>{if(!Hu())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(([c,l])=>[c,Do(l)]))}),r.current=t;return}const o=Object.keys({...a,...t}).filter(c=>!Object.is(a[c],t[c]));o.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:o,snapshot:Object.fromEntries(o.map(c=>[c,Do(t[c])]))}),r.current=t})}function Uu({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:o,zoomRef:c,panXRef:l,panYRef:d,setPanX:f,setPanY:u,setZoom:p,lastWheelTimeRef:m,onAction:y,setLastActionStatus:N,spawnRippleFromNormalized:h,clampPan:j,isMobile:x,mobileFillZoom:b}){const[v,A]=i.useState(null),g=i.useRef(null),M=i.useRef(null),T=i.useRef(null),k=i.useRef(!1),w=i.useRef(null),K=i.useRef(0),R=i.useRef(null),S=i.useRef(1),O=i.useRef({x:0,y:0}),U=i.useRef(!1),P=i.useRef(n),C=i.useRef(y),I=30,W=550,E=18,$=60,F=400,J=12,he=()=>{if(g.current)return;const ye={nx:.5,ny:.5};g.current=ye,A(ye)};return i.useEffect(()=>{P.current=n,n==="mouse"&&he()},[n]),i.useEffect(()=>{C.current=y},[y]),i.useEffect(()=>{const ye=e.current;if(!ye)return;const fe=de=>{if(!r.current)return null;const we=r.current.getBoundingClientRect();return!we.width||!we.height?null:{nx:Math.max(0,Math.min(1,(de.clientX-we.left)/we.width)),ny:Math.max(0,Math.min(1,(de.clientY-we.top)/we.height))}},be=(de,we)=>{if(!r.current)return{dnx:0,dny:0};const ue=r.current,xe=ue.getBoundingClientRect(),se=ue.naturalWidth||xe.width,ie=ue.naturalHeight||xe.height,re=se/ie,q=xe.width/xe.height;let Y,ce;return re>q?(Y=xe.width,ce=xe.width/re):(ce=xe.height,Y=xe.height*re),{dnx:de/Y,dny:we/ce}},X=(de,we,ue)=>{if(ue<=1.05)return;const xe=-(de-.5)*100,se=-(we-.5)*100,ie=j(xe,se,ue);(Math.abs(ie.x-l.current)>.1||Math.abs(ie.y-d.current)>.1)&&(f(ie.x),u(ie.y),l.current=ie.x,d.current=ie.y)},ae=de=>{const we=t.current;if(we&&de.target instanceof Node&&we.contains(de.target))de.preventDefault();else return;if(de.touches.length===1){const ue=de.touches[0];M.current={x:ue.clientX,y:ue.clientY,time:Date.now()},T.current={x:ue.clientX,y:ue.clientY},U.current||(k.current=!1),w.current=setTimeout(()=>{if(!k.current&&!U.current)if(k.current=!0,P.current==="mouse"){const xe=g.current||{nx:.5,ny:.5};N("Right Click"),h(xe.nx,xe.ny,"right"),C.current("input_click",{...xe,button:"right"}).catch(()=>{})}else{const xe=fe(ue);xe&&(N("Right Click"),h(xe.nx,xe.ny,"right"),C.current("input_click",{...xe,button:"right"}).catch(()=>{}))}},500);return}if(de.touches.length===2){w.current&&clearTimeout(w.current),k.current=!0,U.current=!0;const ue=de.touches[1].clientX-de.touches[0].clientX,xe=de.touches[1].clientY-de.touches[0].clientY;R.current=Math.sqrt(ue*ue+xe*xe),S.current=c.current,O.current={x:(de.touches[0].clientX+de.touches[1].clientX)/2,y:(de.touches[0].clientY+de.touches[1].clientY)/2}}},ge=de=>{const we=t.current;if(we&&de.target instanceof Node&&we.contains(de.target)&&de.preventDefault(),de.touches.length===1&&T.current){const ue=de.touches[0],xe=ue.clientX-T.current.x,se=ue.clientY-T.current.y;if(!k.current&&M.current){const ie=ue.clientX-M.current.x,re=ue.clientY-M.current.y;Math.sqrt(ie*ie+re*re)>8&&(k.current=!0,w.current&&clearTimeout(w.current))}if(k.current)if(P.current==="mouse"){const ie=be(xe,se),re=g.current||{nx:.5,ny:.5},q=Math.max(0,Math.min(1,re.nx+ie.dnx)),Y=Math.max(0,Math.min(1,re.ny+ie.dny));g.current={nx:q,ny:Y},A({nx:q,ny:Y}),N(`Cursor: ${Math.round(q*100)}%, ${Math.round(Y*100)}%`),X(q,Y,c.current);const ce=Date.now();ce-m.current>=30&&(m.current=ce,C.current("input_mouseMoved",{nx:q,ny:Y}).catch(()=>{}))}else if(c.current>1){const ie=t.current;if(ie){const re=ie.clientWidth,q=ie.clientHeight,Y=l.current+xe/re*100,ce=d.current+se/q*100,ke=j(Y,ce,c.current);f(ke.x),u(ke.y),l.current=ke.x,d.current=ke.y}}else{const ie=fe(ue);if(ie){const re=Date.now();re-m.current>=40&&(m.current=re,N("Scroll"),C.current("input_wheel",{nx:ie.nx,ny:ie.ny,deltaX:Math.round(-xe*2.5),deltaY:Math.round(-se*2.5)}).catch(()=>{}))}}T.current={x:ue.clientX,y:ue.clientY};return}if(de.touches.length===2&&R.current!==null){const ue=de.touches[1].clientX-de.touches[0].clientX,xe=de.touches[1].clientY-de.touches[0].clientY,ie=Math.sqrt(ue*ue+xe*xe)/R.current,re=(de.touches[0].clientX+de.touches[1].clientX)/2,q=(de.touches[0].clientY+de.touches[1].clientY)/2,Y=re-O.current.x,ce=q-O.current.y,ke=Math.abs(ie-1)>.03;if(P.current==="mouse"){if(ke){const Z=Math.max(o,Math.min(5,S.current*ie));p(Z),c.current=Z}else if(Math.abs(Y)>2||Math.abs(ce)>2){const Z=g.current||{nx:.5,ny:.5},Se=Date.now();Se-m.current>=30&&(m.current=Se,N("Scroll"),C.current("input_wheel",{nx:Z.nx,ny:Z.ny,deltaX:Math.round(-Y*3),deltaY:Math.round(-ce*3)}).catch(()=>{}))}}else{const Z=Math.max(o,Math.min(5,S.current*ie));p(Z),c.current=Z;const Se=t.current;if(Se&&Z>1){const Me=Se.clientWidth,We=Se.clientHeight,Fe=l.current+Y/Me*100,D=d.current+ce/We*100,Ne=j(Fe,D,Z);f(Ne.x),u(Ne.y),l.current=Ne.x,d.current=Ne.y}}O.current={x:re,y:q}}},ee=de=>{var we;if(w.current&&clearTimeout(w.current),R.current=null,de.touches.length===1&&U.current){const ue=de.touches[0];M.current={x:ue.clientX,y:ue.clientY,time:Date.now()},T.current={x:ue.clientX,y:ue.clientY},k.current=!0;return}if(de.touches.length===0){if(U.current){U.current=!1,k.current=!1;return}if(de.changedTouches.length===1){const ue=de.changedTouches[0],xe=Date.now(),se=xe-(((we=M.current)==null?void 0:we.time)||0),ie=M.current?ue.clientX-M.current.x:0,re=M.current?ue.clientY-M.current.y:0,q=Math.sqrt(ie*ie+re*re);if(P.current==="mouse"){if(se<I||se>W||q>E){k.current=!1;return}const Y=g.current||fe(ue);Y&&(N(`Click: ${Math.round(Y.nx*100)}%, ${Math.round(Y.ny*100)}%`),h(Y.nx,Y.ny,"left"),C.current("input_click",{...Y}).catch(()=>{}))}else{if(k.current){k.current=!1;return}if(se<$||se>F||q>J){k.current=!1;return}const Y=fe(ue);if(!Y)return;xe-K.current<300?(N("Double tap"),h(Y.nx,Y.ny,"double"),C.current("input_click",{...Y,clickCount:2}).catch(()=>{}),K.current=0):(N(`Tap: ${Math.round(Y.nx*100)}%, ${Math.round(Y.ny*100)}%`),h(Y.nx,Y.ny,"left"),C.current("input_click",{...Y}).catch(()=>{}),K.current=xe)}}k.current=!1}};return ye.addEventListener("touchstart",ae,{passive:!1}),ye.addEventListener("touchmove",ge,{passive:!1}),ye.addEventListener("touchend",ee,{passive:!1}),()=>{ye.removeEventListener("touchstart",ae),ye.removeEventListener("touchmove",ge),ye.removeEventListener("touchend",ee),w.current&&clearTimeout(w.current)}},[e,t,r,o,c,l,d,f,u,p,m,N,h,j]),{cursorPos:v,cursorPosRef:g,handleToggleInputMode:()=>{a(ye=>{const fe=ye==="touch"?"mouse":"touch";return fe==="mouse"&&he(),fe})},handleZoomReset:()=>{const ye=x?b:1;p(ye),c.current=ye,f(0),u(0),l.current=0,d.current=0}}}function ac({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:o}){const c=i.useRef(null),l=i.useRef(null),d=i.useRef(null),[f,u]=i.useState(null),[p,m]=i.useState(""),[,y]=i.useState(!1),[N,h]=i.useState([]),j=i.useRef(0),[x,b]=i.useState(!1),[v,A]=i.useState(!1),g=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[M,T]=i.useState(g?"mouse":"touch"),[k,w]=i.useState(1),K=i.useRef(!1),[R,S]=i.useState(1),[O,U]=i.useState(0),[P,C]=i.useState(0);dr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:M,zoom:R,panX:O,panY:P,isMenuOpen:x,isImeOpen:v});const I=i.useRef(0),W=i.useRef(R),E=i.useRef(O),$=i.useRef(P);i.useEffect(()=>{W.current=R},[R]),i.useEffect(()=>{E.current=O},[O]),i.useEffect(()=>{$.current=P},[P]),i.useEffect(()=>{var se;(se=c.current)==null||se.focus()},[]);const F=r==="connected",J=n,he=F?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",le=F?"The remote stream is warming up":"Waiting for the remote stream to catch up";i.useEffect(()=>{if(!g||K.current||!J)return;const se=d.current,ie=l.current;if(!se||!ie)return;const re=()=>{const q=ie.clientWidth,Y=ie.clientHeight,ce=se.naturalWidth,ke=se.naturalHeight;if(!ce||!ke||!q||!Y)return;const Z=Math.min(q/ce,Y/ke),Me=Math.max(q/ce,Y/ke)/Z;Me>1.01&&(w(Me),S(Me),W.current=Me),K.current=!0};se.complete&&se.naturalWidth?re():se.addEventListener("load",re,{once:!0})},[J,g]);const te=.5;i.useEffect(()=>{R<=te&&(U(0),C(0))},[R,te]);const ye=(se,ie,re)=>{if(re<=te)return{x:0,y:0};const q=(re-1)/(2*re)*100,Y=(re-1)/(2*re)*100;return{x:Math.max(-q,Math.min(q,se)),y:Math.max(-Y,Math.min(Y,ie))}},fe=(se,ie)=>{if(!d.current)return null;const re=d.current.getBoundingClientRect();return!re.width||!re.height?null:{nx:Math.max(0,Math.min(1,(se-re.left)/re.width)),ny:Math.max(0,Math.min(1,(ie-re.top)/re.height))}},be=(se,ie,re)=>{const q=l.current;if(!q)return;const Y=q.getBoundingClientRect(),ce=++j.current;h(ke=>[...ke,{id:ce,x:se-Y.left,y:ie-Y.top,type:re}]),setTimeout(()=>h(ke=>ke.filter(Z=>Z.id!==ce)),600)},X=(se,ie,re)=>{const q=d.current,Y=l.current;if(!q||!Y)return;const ce=q.getBoundingClientRect(),ke=Y.getBoundingClientRect(),Z=q.naturalWidth||ce.width,Se=q.naturalHeight||ce.height,Me=Z/Se,We=ce.width/ce.height;let Fe,D,Ne,Ie;Me>We?(Fe=ce.width,D=ce.width/Me,Ne=0,Ie=(ce.height-D)/2):(D=ce.height,Fe=ce.height*Me,Ne=(ce.width-Fe)/2,Ie=0);const Re=ce.left-ke.left+Ne+Fe*se,De=ce.top-ke.top+Ie+D*ie,He=++j.current;h(Ue=>[...Ue,{id:He,x:Re,y:De,type:re}]),setTimeout(()=>h(Ue=>Ue.filter(Qe=>Qe.id!==He)),600)},ae=async se=>{var re;const ie=fe(se.clientX,se.clientY);if(ie){u(`Click: ${Math.round(ie.nx*100)}%, ${Math.round(ie.ny*100)}%`),be(se.clientX,se.clientY,"left"),(re=c.current)==null||re.focus();try{const q=await e("input_click",{nx:ie.nx,ny:ie.ny});q!=null&&q.success||t(`❌ Click failed: ${q==null?void 0:q.error}`)}catch(q){t(`❌ Click error: ${q.message||q}`)}}},ge=async(se,ie,re,q=0)=>{try{await e("input_key",{type:re?"char":"keyDown",key:se,code:ie,text:re?se:void 0,unmodifiedText:re?se:void 0,modifiers:q})}catch(Y){t(`❌ Key error: ${Y.message||Y}`)}},ee=async se=>{if(se.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(se.key)&&se.preventDefault();let re=0;se.altKey&&(re|=1),se.ctrlKey&&(re|=2),se.metaKey&&(re|=4),se.shiftKey&&(re|=8),u(`Key: ${se.key}`),await ge(se.key,se.code,se.key.length===1,re)},de=async se=>{if(se.key==="Enter"){if(se.nativeEvent.isComposing)return;if(p){const ie=p;m(""),u(`IME Sent: ${ie}`);try{const re=await e("input_type",{text:ie});re!=null&&re.success||t(`❌ IME error: ${re==null?void 0:re.error}`)}catch(re){t(`❌ IME error: ${re.message}`)}}else u("Key: Enter"),await ge("Enter","Enter",!1)}};i.useEffect(()=>{const se=c.current;if(!se)return;const ie=re=>{var q;if((q=d.current)!=null&&q.contains(re.target)){re.preventDefault();const Y=Date.now();if(Y-I.current<40)return;I.current=Y;const ce=fe(re.clientX,re.clientY);if(!ce)return;u(`Scroll: ${Math.round(re.deltaY)}`),e("input_wheel",{nx:ce.nx,ny:ce.ny,deltaX:Math.round(re.deltaX),deltaY:Math.round(re.deltaY)}).catch(()=>{})}};return se.addEventListener("wheel",ie,{passive:!1}),()=>se.removeEventListener("wheel",ie)},[e]);const{cursorPos:we,handleToggleInputMode:ue,handleZoomReset:xe}=Uu({containerRef:c,viewportRef:l,imgRef:d,inputMode:M,setInputMode:T,minZoom:te,zoomRef:W,panXRef:E,panYRef:$,setPanX:U,setPanY:C,setZoom:S,lastWheelTimeRef:I,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:X,clampPan:ye,isMobile:g,mobileFillZoom:k});return s.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ee,onContextMenu:se=>se.preventDefault(),onFocus:()=>y(!0),onBlur:()=>y(!1),tabIndex:0,children:[s.jsxs("div",{ref:l,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(${R}) translate(${O}%, ${P}%)`,transformOrigin:"center center",cursor:M==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:ae,onContextMenu:se=>se.preventDefault(),onDragStart:se=>se.preventDefault()}):s.jsx(Fu,{waitingLabel:he,waitingHint:le,transportType:o}),M==="mouse"&&J&&s.jsx(Ou,{cursorPos:we,viewportRef:l,imgRef:d}),N.map(se=>{const re={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[se.type];return s.jsxs("div",{style:{position:"absolute",left:se.x,top:se.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${re}, 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(${re}, 0.9)`,boxShadow:`0 0 12px rgba(${re}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},se.id)})]}),s.jsx(Wu,{inputMode:M,onToggleInputMode:ue,isImeOpen:v,setIsImeOpen:A,isMenuOpen:x,setIsMenuOpen:b,imeText:p,setImeText:m,handleImeSubmit:de,isConnActive:F,zoom:R,isMobile:g,mobileFillZoom:k,onZoomOut:()=>S(se=>Math.max(.5,se-.25)),onZoomReset:xe,onZoomIn:()=>S(se=>Math.min(5,se+.25)),transportType:o,screenshotUsage:a,lastActionStatus:f}),s.jsx("style",{children:`
2
+ var yd=Object.defineProperty;var vd=(e,t,r)=>t in e?yd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ye=(e,t,r)=>vd(e,typeof t!="symbol"?t+"":t,r);import{r as i,j as s,M as Ia,a as wd,b as jd,c as kd,u as Ps,R as kt,d as sr,t as Sd,e as Nd,D as Cd,f as aa,g as oa,h as La,i as Td,k as Md,B as Ad,l as Id,m as Xt,N as ia,n as Ld}from"./vendor-BRZ4K-AC.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 c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&n(c)}).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 Rd(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 Ns=Rd();function Co(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 _d(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Pd(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Bi(e,t){var f;if(!e)return t??null;if(!t)return e??null;const r=Pd(e,"messages"),n=r?Array.isArray(e.messages)?e.messages:[]:void 0,a=e.status==="waiting_approval"||Array.isArray((f=e.activeModal)==null?void 0:f.buttons)&&e.activeModal.buttons.length>0,o=r&&a&&(n==null?void 0:n.length)===0&&Array.isArray(t.messages)&&t.messages.length>0,c=r?o?t.messages:n??[]:t.messages,l=e.activeModal||(e.status==="waiting_approval"?t.activeModal:null),d={...t,...e,activeModal:l,inputContent:e.inputContent??t.inputContent};return r?{...d,messages:c}:d}function qs(e,t){const r=_d(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:Bi(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)}}function Ki(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(c=>c.id===a.id);return o?qs(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 To(e){return!!e&&typeof e=="object"&&"text"in e}function Ra(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:To(o)?String(o.text||""):"").join(r):To(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Kt(e){return Ra(e,{normalizeWhitespace:!0})}const Oi=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}),Wi=i.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Mo(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 Fi(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,c=t.versionMismatch===!0||e.versionMismatch===!0,l=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||c&&a&&o&&a!==o)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function Dd(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 wn(e){if(!e||typeof e!="object")return"";const t=e,r=Dd(Kt(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 Ed(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=wn(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:wn(e[0]),last:wn(e[e.length-1])}}function ca(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function la(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(ca(e)&&ca(t)){const c=e.messages;Array.isArray(c)&&c===t.messages&&r.add(c)}if(Array.isArray(e)&&Array.isArray(t)){const c=Math.min(e.length,t.length);for(let l=0;l<c;l+=1)la(e[l],t[l],r);return}const n=e,a=t,o=new Set([...Object.keys(n),...Object.keys(a)]);for(const c of o)c!=="messages"&&la(n[c],a[c],r)}function Xs(e,t){return Array.isArray(e)?e.map(r=>Xs(r,t)):!e||typeof e!="object"?e:ca(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?Ed(a,t):Xs(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,Xs(n,t)]))}function $d(e,t){try{const r=new WeakSet;return la(e,t,r),JSON.stringify(Xs(e,r))===JSON.stringify(Xs(t,r))}catch{return!1}}function da(e,t,r){return $d(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Hi(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function Bd(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function Ao(e,t,r,n){var l;const a=(l=t.chats)!=null&&l.length?t.chats:e.chats,o=Ki(e.childSessions,t.childSessions,{preserveMissing:n}),c=Bi(t.activeChat,e.activeChat);return Fi(e,t,{...e,...t,chats:a,childSessions:o,activeChat:c,_lastUpdate:r})}function Kd(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=Ki(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((o=e.chats)!=null&&o.length)&&(n.chats=t.chats);for(const c 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"])Bd(n,t,c);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function Od(e,t,r,n){const a=Kd(e,t,n),o=Object.keys(a).length>0?Fi(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return da(e,o,r)}function Wd(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 c=Hi(o);c&&r.add(c),c&&o.type!=="adhdev-daemon"&&n.add(c),c&&o.type==="adhdev-daemon"&&o._sessionListAuthoritative&&a.add(c)}return{incomingIds:t,incomingDaemonIds:r,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:a}}function Fd(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 Hd(e,t,r,n){return!!(r.has(t)&&e.transport&&!n.has(t))}function Ud(e,t,r){var u,p;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(m=>({...m,_lastUpdate:n}));const o=new Map;for(const m of t)o.set(m.id,m);const{incomingIds:c,incomingDaemonIds:l,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:f}=Wd(e);for(const m of e){const y=o.get(m.id);if(!y){o.set(m.id,{...m,_lastUpdate:n});continue}const N=Mo(m),h=Mo(y),j=Hi(m),x=!a.has(j);if(N>h){const A=Ao(y,m,n,x);o.set(m.id,da(y,A,n));continue}if(N<h){o.set(m.id,Od(y,m,n,x));continue}const b=m.timestamp||n,v=y._lastUpdate||y.timestamp||0;if(b>=v){const A=Ao(y,m,n,x);o.set(m.id,da(y,A,n));continue}(u=m.chats)!=null&&u.length&&!((p=y.chats)!=null&&p.length)&&o.set(m.id,{...y,chats:m.chats})}for(const[m,y]of o){const N=y.daemonId||m.split(":")[0];if(!l.has(N))continue;if(a.has(N)&&f.has(N)&&!c.has(m)){o.delete(m);continue}const h=n-(y._lastUpdate||y.timestamp||0);Fd(y,N,h,c,a,d)&&o.delete(m)}for(const[m,y]of o){const N=y.daemonId||m.split(":")[0];if(Hd(y,N,l,d))continue;n-(y._lastUpdate||y.timestamp||0)>3e5&&y.status!=="online"&&o.delete(m)}return Array.from(o.values())}function zd(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 Vd({children:e,connectionOverrides:t}){const[r,n]=i.useState([]),[a,o]=i.useState(!1),[c,l]=i.useState([]),[d,f]=i.useState(void 0),u=i.useRef(r);i.useEffect(()=>{u.current=r},[r]);const p=i.useCallback((x,b)=>{n(v=>{let A=!1;const g=v.map(M=>M.id!==x||M.chats===b?M:(A=!0,{...M,chats:b}));return A?g:v})},[]),m=i.useCallback((x,b)=>{n(v=>{const A=v.length===0?x:Ud(x,v,b),g=!zd(v,A);return g&&Ns.record({kind:"dashboard.entries_applied",payload:{incoming:Co(x),next:Co(A)}}),g?A:v})},[]),y=i.useCallback(()=>o(!0),[]),N=i.useMemo(()=>({injectEntries:m,markLoaded:y,getIdes:()=>u.current}),[m,y]),h=t,j=i.useMemo(()=>({ides:r,updateRouteChats:p,initialLoaded:a,toasts:c,setToasts:l,wsStatus:(h==null?void 0:h.wsStatus)??"connected",isConnected:(h==null?void 0:h.isConnected)??!0,connectionStates:(h==null?void 0:h.connectionStates)??{},connectionTransports:(h==null?void 0:h.connectionTransports)??{},showReconnected:(h==null?void 0:h.showReconnected)??!1,retryConnection:h==null?void 0:h.retryConnection,retryServerConnection:h==null?void 0:h.retryServerConnection,connectionLoginUrl:h==null?void 0:h.connectionLoginUrl,isP2PActive:(h==null?void 0:h.isP2PActive)??!1,p2pStates:(h==null?void 0:h.p2pStates)??{},userRole:h==null?void 0:h.userRole,connectionRetryStatuses:h==null?void 0:h.connectionRetryStatuses,userName:d,setUserName:f}),[r,p,a,c,h==null?void 0:h.wsStatus,h==null?void 0:h.isConnected,h==null?void 0:h.connectionStates,h==null?void 0:h.connectionTransports,h==null?void 0:h.showReconnected,h==null?void 0:h.retryConnection,h==null?void 0:h.retryServerConnection,h==null?void 0:h.connectionLoginUrl,h==null?void 0:h.isP2PActive,h==null?void 0:h.p2pStates,h==null?void 0:h.userRole,h==null?void 0:h.connectionRetryStatuses,d]);return s.jsx(Wi.Provider,{value:N,children:s.jsx(Oi.Provider,{value:j,children:e})})}function ds(){return i.useContext(Oi)}function rr(){return i.useContext(Wi)}function Ui(e){const{baseUrl:t,getToken:r,onUnauthorized:n}=e;function a(l){return l.startsWith("http")?l:`${t}${l.startsWith("/")?"":"/"}${l}`}function o(l){const d=r==null?void 0:r(),f=a(l),u=l.startsWith("http")?new URL(f):new URL(f,typeof window<"u"?window.location.origin:"http://localhost");return d&&u.searchParams.set("token",d),!l.startsWith("http")&&!t?`${u.pathname}${u.search}${u.hash}`:u.toString()}async function c(l,d={}){const f={"Content-Type":"application/json",...d.headers||{}},u=r==null?void 0:r();u&&(f.Authorization=`Bearer ${u}`);const p=a(l),m=new AbortController,y=setTimeout(()=>m.abort(),15e3);try{const N=await fetch(p,{...d,headers:f,signal:m.signal});if(N.status===401)throw n==null||n(),new Error("Unauthorized");if(!N.ok){const h=await N.json().catch(()=>({error:N.statusText}));throw new Error(h.error||`API Error: ${N.status}`)}return N.json()}finally{clearTimeout(y)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,d,f={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:d,payload:f})}),execTerminal:(l,d,f)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:f})}),sendAgentMessage:(l,d,f)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:f})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,d,f)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:d,action:f?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,d,f={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:d,payload:f})}),getMuxEventsUrl:l=>o(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>o(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const Gd=Ui({baseUrl:"http://localhost:3847"}),qd=i.createContext(Gd);function Yd({client:e,children:t}){return s.jsx(qd.Provider,{value:e,children:t})}const Xd={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},zi=i.createContext(Xd);function Jd({value:e,children:t}){return s.jsx(zi.Provider,{value:e,children:t})}function mt(){return i.useContext(zi)}function Qd(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 Zd(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Vi(e){return e?Qd([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Zd(e.content)]):""}const Oe={size:18};function Gi({size:e=Oe.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 _a({size:e=Oe.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 us({size:e=Oe.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 qi({size:e=Oe.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 eu({size:e=Oe.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 tu({size:e=Oe.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 Yi({size:e=Oe.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 su({size:e=Oe.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 on({size:e=Oe.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 Xi({size:e=Oe.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 ru({size:e=Oe.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 Ut({size:e=Oe.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 Tt({size:e=Oe.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 Pa({size:e=Oe.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 nu({size:e=Oe.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 Cs({size:e=Oe.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 lr({size:e=Oe.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 nr({size:e=Oe.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 ar({size:e=Oe.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 Ji({size:e=Oe.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 Da({size:e=Oe.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 Qi({size:e=Oe.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 au({size:e=Oe.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 Ea({size:e=Oe.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 ou({size:e=Oe.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 $a({size:e=Oe.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 Zi({size:e=Oe.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 St({size:e=Oe.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 iu({size:e=Oe.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 cu({size:e=Oe.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 lu({size:e=Oe.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 du({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),s.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function cn({size:e=Oe.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 uu({size:e=Oe.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 fu({size:e=Oe.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 mu({size:e=Oe.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 pu({size:e=Oe.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 hu({size:e=Oe.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 xu({size:e=Oe.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 bu({size:e=Oe.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 gu({size:e=Oe.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 yu({size:e=Oe.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 vu({size:e=Oe.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 wu({size:e=Oe.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 ju({size:e=Oe.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 ec=[wd,{singleTilde:!1}],tc=[ec,jd,kd],ku=[ec],Ba=200,Su=80,Io=650,Ks=new Map;function Gr(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function Nu(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}:${Vi(n)}`}function Cu(e,t,r,n){return e||!t?!1:Gr(r,n)}function Tu({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=Su,bottomThresholdPx:a=Ba}){const o=Math.max(0,Number(e)||0),c=Math.max(0,Number(t)||0),l=Math.max(0,Number(r)||0);return Math.max(0,c-l)<=0?{showTop:!1,showBottom:!1}:{showTop:o>n,showBottom:Math.max(0,c-o-l)>a}}function Mu(e){return Tu({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function Ys(e,t=Ba){return!!e&&e.fromBottom>=t}function Au(e,t){return Gr(e,t)?!Ys(e):!0}function Iu({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function Lu({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function jn(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function sc(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Ru(e,t,r){return Number(e.receivedAt||r[qr(e,t)]||0)||0}function rc(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function _u(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function gr(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 kn(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 Lo(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):rc(e)?s.jsx(Ia,{remarkPlugins:tc,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function yr({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:Lo(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=kn(r);return a?s.jsx("img",{src:a,alt:gr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=kn(r);return a?s.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=kn(r);return a?s.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"},`video-${n}`):r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:gr(r.uri,"video")},`video-link-${n}`):null}if(r.type==="resource_link")return r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:r.name||gr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=gr(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}),Lo(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 qr(e,t){const r=e,n=Ra(e.content,{joiner:`
3
+ `});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 Pu=i.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(Ia,{remarkPlugins:ku,children:t.text}),s.jsx("span",{className:"action-time",children:sc(t.timestamp)})]})},(e,t)=>e.log===t.log),Du=i.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:o,isTextExpanded:c,onToggleTextExpanded:l}){var M,T,k;const d=(t.role||"").toLowerCase(),f=d==="user"||d==="human",u=t.kind||(d==="tool"?"tool":"standard"),p=_u(t.content)?t.content:null,m=!!(p!=null&&p.some(w=>w.type!=="text")),y=Ra(t.content,{joiner:`
4
+ `});if(u==="thought"){const w=typeof((M=t.meta)==null?void 0:M.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought",children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(lu,{size:13}),s.jsx("span",{children:w})]}),s.jsx("div",{className:"chat-msg-body",children:y})]})}if(u==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),m&&p?s.jsx("div",{className:"tool-text w-full",children:s.jsx(yr,{parts:p,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:y})]});if(u==="terminal"){const w=(T=t.meta)!=null&&T.isRunning?"⏳":"✅",K=typeof((k=t.meta)==null?void 0:k.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal",children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:w}),s.jsx("span",{children:K})]}),m&&p?s.jsx("div",{className:"chat-msg-body",children:s.jsx(yr,{parts:p,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:y})]})}if(u==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:m&&p?s.jsx(yr,{parts:p,renderAsPreformatted:!1}):y.slice(0,100)});const N=t.meta,j=(typeof(N==null?void 0:N.renderMode)=="string"?N.renderMode.trim():"")==="preformatted",x=y,b=!1,v=x,A=j,g=!A&&rc(v);return s.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${f?"self-end":"self-start"}`,children:(x||m||f)&&s.jsxs("div",{className:`chat-bubble ${f?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${x||m?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:f?a||"You":t.senderName||n}),r!=null&&s.jsx("span",{className:"chat-time",children:sc(r)})]}),(x||m)&&s.jsx("div",{className:"chat-markdown",children:m&&p?s.jsx(yr,{parts:p,renderAsPreformatted:A}):A?s.jsx("pre",{className:"chat-preformatted",children:v}):g?s.jsx(Ia,{remarkPlugins:tc,children:v}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:v})}),b]})})},(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),Eu=i.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:o=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:d={},lastMessageHash:f,emptyState:u,onLoadMore:p,isLoadingMore:m,hasMoreHistory:y,hiddenLiveCount:N=0,loadError:h,scrollToBottomRequestNonce:j,isVisible:x=!0},b){const v=i.useRef(null),A=i.useRef(null),g=i.useRef(null),M=i.useRef(0),T=i.useRef(""),k=i.useRef(""),w=i.useRef(!1),K=i.useRef(null),R=i.useRef(!1),S=i.useRef(null),O=i.useRef(!1),[H,P]=i.useState(new Set),[C,I]=i.useState({showTop:!1,showBottom:!1}),W=i.useRef(!1),E=i.useRef(!1),$=i.useRef(x),z=i.useRef(x),J=i.useRef(null);z.current=x;const he=()=>{const q=v.current;return q?q.scrollHeight-q.scrollTop-q.clientHeight<Ba:!0},ce=i.useCallback(()=>{const q=v.current,Y=q?Mu(q):{showTop:!1,showBottom:!1};I(le=>le.showTop===Y.showTop&&le.showBottom===Y.showBottom?le:Y)},[]),te=i.useCallback((q="auto")=>{var le;const Y=v.current;Y&&(Y.scrollTo({top:Y.scrollHeight,behavior:q}),(le=Y.ownerDocument.defaultView)==null||le.requestAnimationFrame(()=>ce()))},[ce]),ye=i.useCallback((q="auto")=>{var le;const Y=v.current;Y&&(Y.scrollTo({top:0,behavior:q}),(le=Y.ownerDocument.defaultView)==null||le.requestAnimationFrame(()=>ce()))},[ce]),fe=i.useCallback(()=>{var Z;const q=v.current,Y=(Z=window.getSelection)==null?void 0:Z.call(window);if(!q||!Y||Y.rangeCount===0||Y.isCollapsed){O.current=!1;return}const le=Y.anchorNode,ke=Y.focusNode;O.current=!!(le&&ke&&q.contains(le)&&q.contains(ke))},[]),be=Nu(t,f),X=i.useCallback(()=>{const q=v.current;if(!q||!l||!z.current)return;const Y={top:q.scrollTop,fromBottom:Math.max(0,q.scrollHeight-q.scrollTop-q.clientHeight),messageFingerprint:be};J.current={contextKey:l,snapshot:Y},Ks.set(l,Y)},[l,be]),ae=i.useCallback((q="auto")=>{K.current!=null&&cancelAnimationFrame(K.current),K.current=requestAnimationFrame(()=>{K.current=null,te(q)})},[te]),ge=i.useCallback(()=>{W.current=!1,R.current=!0,E.current=!0,S.current!=null&&window.clearTimeout(S.current),S.current=window.setTimeout(()=>{R.current=!1,S.current=null},Io)},[]);i.useEffect(()=>{const q=!w.current,Y=k.current!==l;if(k.current=l,q||Y){w.current=!0;const ke=l?Ks.get(l):null,Z=!!ke&&Gr(ke,be);W.current=Z?Ys(ke):!1,R.current=Au(ke,be),O.current||(Z?requestAnimationFrame(()=>{const Ce=v.current;Ce&&(jn(Ce,ke),W.current=Ys(ke),ce(),E.current=!0)}):ae("auto")),M.current=t.length,T.current=be;return}t.length>M.current;const le=be!==T.current;Iu({hasSelection:O.current,userScrolledUp:W.current,hasChatContentChanged:le})&&ae("auto"),M.current=t.length,T.current=be},[be,l,t.length,ae,ce]),i.useEffect(()=>{j&&(ge(),O.current||ae("auto"))},[ge,ae,j]),i.useEffect(()=>{const q=$.current;q&&!x&&X(),z.current=x,$.current=x;const Y=l?Ks.get(l):null;if(Cu(q,x,Y,be)){if(!Y)return;W.current=Ys(Y),R.current=!1,O.current||requestAnimationFrame(()=>{const le=v.current;le&&(jn(le,Y),ce())});return}},[x,l,be,ge,X,ae,ce]),i.useEffect(()=>()=>{const q=J.current;q&&Ks.set(q.contextKey,q.snapshot),K.current!=null&&cancelAnimationFrame(K.current),S.current!=null&&window.clearTimeout(S.current)},[]),i.useEffect(()=>{const q=A.current,Y=v.current;if(!q||!Y)return;const le=()=>{S.current!=null&&window.clearTimeout(S.current),S.current=window.setTimeout(()=>{R.current=!1,S.current=null},Io)},ke=new ResizeObserver(()=>{ce();const Z=R.current;Lu({hasSelection:O.current,userScrolledUp:W.current,contextAutoScrollActive:Z})&&(ae("auto"),Z&&le())});return ke.observe(q),Y!==q&&ke.observe(Y),()=>{ke.disconnect(),S.current!=null&&(window.clearTimeout(S.current),S.current=null)}},[ae,l,ce]),i.useImperativeHandle(b,()=>({scrollToBottom:(q="smooth")=>{te(q)}}),[te]),i.useEffect(()=>{const q=v.current;if(!q)return;let Y;const le=()=>{X(),clearTimeout(Y),Y=setTimeout(()=>{W.current=!he(),ce()},50)};return q.addEventListener("scroll",le,{passive:!0}),()=>{q.removeEventListener("scroll",le),clearTimeout(Y)}},[X,ce]),i.useEffect(()=>(document.addEventListener("selectionchange",fe),()=>document.removeEventListener("selectionchange",fe)),[fe]);const ee=i.useRef(0),de=i.useRef(!1);i.useEffect(()=>{const q=v.current;if(!q||!de.current||ee.current===0)return;const Y=q.scrollHeight-ee.current;Y>0&&(q.scrollTop=Y),ce(),X(),ee.current=0,de.current=!1},[t.length,X,ce]),i.useEffect(()=>{if(E.current||!l)return;const q=Ks.get(l),Y=v.current;if(!(!q||!Y)){if(!Gr(q,be)){te("auto"),E.current=!0;return}jn(Y,q),W.current=Ys(q),ce(),E.current=!0}},[l,be,t.length,te,ce]);const we=()=>{const q=v.current;q&&(ee.current=q.scrollHeight),de.current=!0,p==null||p()},ue=()=>{W.current=!0,ye("smooth"),X()},xe=()=>{ge(),te("smooth"),X()},se=i.useMemo(()=>{const q=t.map((Z,Ce)=>({type:"message",data:Z,index:Ce,ts:Ru(Z,Ce,d)}));if(!r||r.length===0)return q;const Y=[...r].sort((Z,Ce)=>Z.timestamp-Ce.timestamp).map((Z,Ce)=>({type:"action",data:Z,index:Ce,ts:Z.timestamp})),le=[];let ke=0;for(const Z of q){for(;ke<Y.length&&Z.ts>0&&Y[ke].ts<Z.ts;)le.push(Y[ke++]);le.push(Z)}for(;ke<Y.length;)le.push(Y[ke++]);return le},[t,r,d]),ie=N>0||!!y,re=N>0?`↑ Show ${Math.min(N,80)} earlier messages${N>80?` (${N} hidden)`:""}`:h?`↻ ${h}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:v,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:A,className:"chat-container-content",children:[m&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),ie&&!m&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:we,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${h&&N===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:re})}),se.length===0&&!ie&&(u||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),se.map(q=>{if(q.type==="action"){const We=q.data;return s.jsx(Pu,{log:We},`action-${q.index}`)}const Y=q.data,le=q.index,ke=qr(Y,le),Z=Y.receivedAt||d[ke],Ce=`${l}-${ke}`,Ee=H.has(Ce);return s.jsx(Du,{message:Y,receivedAt:Z,agentName:n,userName:a,isCliMode:o,isTextExpanded:Ee,onToggleTextExpanded:()=>P(We=>{const Fe=new Set(We);return Ee?Fe.delete(Ce):Fe.add(Ce),Fe})},`msg-${ke}`)}),c&&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:g})]})}),(C.showTop||C.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[C.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:ue,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),C.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:xe,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),$u=i.memo(Eu,(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.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),Bu="modulepreload",Ku=function(e){return"/"+e},Ro={},Ou=function(t,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));a=Promise.allSettled(r.map(d=>{if(d=Ku(d),d in Ro)return;Ro[d]=!0;const f=d.endsWith(".css"),u=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const p=document.createElement("link");if(p.rel=f?"stylesheet":Bu,f||(p.as="script"),p.crossOrigin="",p.href=d,l&&p.setAttribute("nonce",l),document.head.appendChild(p),f)return new Promise((m,y)=>{p.addEventListener("load",m),p.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return a.then(c=>{for(const l of c||[])l.status==="rejected"&&o(l.reason);return t().catch(o)})};let _o=!1;const nc=i.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:o="measured"},c)=>{const l=i.useRef(null),[d,f]=i.useState(null),u=i.useRef([]),p=i.useRef(!1),m=i.useRef(!1),y=i.useRef(!1),N=i.useRef(!1),h=()=>{const j=l.current;if(j){p.current&&(j.clear(),p.current=!1);for(const x of u.current)j.write(x.data,x.onProcessed);u.current=[],m.current&&(j.fit(),m.current=!1),y.current&&(j.bumpResize(),y.current=!1),N.current&&(j.scrollToTop(),N.current=!1)}};return i.useImperativeHandle(c,()=>({write:(j,x)=>{l.current?l.current.write(j,x):u.current.push({data:j,onProcessed:x})},clear:()=>{l.current?l.current.clear():(u.current=[],p.current=!0)},reset:()=>{l.current&&typeof l.current.reset=="function"?l.current.reset():(u.current=[],p.current=!0)},resize:(j,x)=>{l.current&&typeof l.current.resize=="function"&&l.current.resize(j,x)},fit:()=>{l.current?l.current.fit():m.current=!0},bumpResize:()=>{l.current?l.current.bumpResize():y.current=!0},scrollToTop:()=>{l.current?l.current.scrollToTop():N.current=!0},getSelection:()=>{var j,x;return((x=(j=l.current)==null?void 0:j.getSelection)==null?void 0:x.call(j))||""},getVisibleText:()=>{var j,x;return((x=(j=l.current)==null?void 0:j.getVisibleText)==null?void 0:x.call(j))||""}}),[]),i.useEffect(()=>{d&&h()},[d]),i.useEffect(()=>{let j=!1;return Ou(()=>import("./terminal-DbJP_JGY.js"),__vite__mapDeps([0,1,2])).then(x=>{_o||(_o=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),j||f(()=>x.GhosttyTerminalView)}).catch(x=>{console.error("[CliTerminal] failed to load terminal renderer",x)}),()=>{j=!0}},[]),d?s.jsx(d,{ref:l,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"}})});nc.displayName="CliTerminal";function vr({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 Po({value:e,max:t,label:r,color:n="#8b5cf6",detail:a,compact:o=!1}){const c=t>0?Math.min(Math.round(e/t*100),100):0,l=c>85?"#ef4444":c>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:[c,"%"]})]}),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:`${c}%`,background:l}})})]}):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:[c,"%"]})]}),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:`${c}%`,background:`linear-gradient(90deg, ${l}, ${l}cc)`}})}),a&&s.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function Wu({cursorPos:e,viewportRef:t,imgRef:r}){var b;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),o=(b=t.current)==null?void 0:b.getBoundingClientRect();if(!o)return null;const c=n.naturalWidth||a.width,l=n.naturalHeight||a.height,d=c/l,f=a.width/a.height;let u,p,m,y;d>f?(u=a.width,p=a.width/d,m=0,y=(a.height-p)/2):(p=a.height,u=a.height*d,m=(a.width-u)/2,y=0);const N=a.left-o.left+m+u*e.nx,h=a.top-o.top+y+p*e.ny,j=Math.max(8,Math.min(o.width-8,N)),x=Math.max(8,Math.min(o.height-8,h));return s.jsxs("div",{style:{position:"absolute",left:j-8,top:x-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 Fu({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:o,imeText:c,setImeText:l,handleImeSubmit:d,isConnActive:f,zoom:u,isMobile:p,mobileFillZoom:m,onZoomOut:y,onZoomReset:N,onZoomIn:h,transportType:j,screenshotUsage:x,lastActionStatus:b}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:v=>v.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[s.jsxs("div",{onClick:t,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[s.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),s.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),s.jsxs("div",{className:"relative",children:[s.jsx("div",{onClick:()=>{n(v=>!v),o(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&s.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:s.jsx("input",{type:"text",placeholder:"Type & Enter...",value:c,autoFocus:!0,onTouchStart:v=>v.stopPropagation(),onChange:v=>l(v.target.value),onKeyDown:v=>{d(v)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{o(v=>!v),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:f?"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:f?"#22c55e":"#eab308",boxShadow:f?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:f?"#22c55e":"#eab308"},children:f?"Connected":"WS"})]}),u>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(u*100),"%"]}),j==="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"}),j==="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"}),x&&x.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:x.budgetExhausted?"#ef4444":"#c4b5fd",background:x.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:x.budgetExhausted?"TURN blocked":`TURN ${x.dailyUsedMinutes}/${x.dailyBudgetMinutes}m`}),b&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:b})]})]}),a&&s.jsxs("div",{onTouchStart:v=>v.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",u<=(p?m:1)+.01?p?"FILL":"FIT":`${Math.round(u*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:v=>{v.stopPropagation(),y()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),s.jsx("button",{onClick:v=>{v.stopPropagation(),N()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:p?"FILL":"FIT"}),s.jsx("button",{onClick:v=>{v.stopPropagation(),h()},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 Hu({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 Uu(){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 Do(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 dr(e,t){const r=i.useRef(null),n=i.useRef(0);i.useEffect(()=>{if(!Uu())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(([c,l])=>[c,Do(l)]))}),r.current=t;return}const o=Object.keys({...a,...t}).filter(c=>!Object.is(a[c],t[c]));o.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:o,snapshot:Object.fromEntries(o.map(c=>[c,Do(t[c])]))}),r.current=t})}function zu({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:o,zoomRef:c,panXRef:l,panYRef:d,setPanX:f,setPanY:u,setZoom:p,lastWheelTimeRef:m,onAction:y,setLastActionStatus:N,spawnRippleFromNormalized:h,clampPan:j,isMobile:x,mobileFillZoom:b}){const[v,A]=i.useState(null),g=i.useRef(null),M=i.useRef(null),T=i.useRef(null),k=i.useRef(!1),w=i.useRef(null),K=i.useRef(0),R=i.useRef(null),S=i.useRef(1),O=i.useRef({x:0,y:0}),H=i.useRef(!1),P=i.useRef(n),C=i.useRef(y),I=30,W=550,E=18,$=60,z=400,J=12,he=()=>{if(g.current)return;const ye={nx:.5,ny:.5};g.current=ye,A(ye)};return i.useEffect(()=>{P.current=n,n==="mouse"&&he()},[n]),i.useEffect(()=>{C.current=y},[y]),i.useEffect(()=>{const ye=e.current;if(!ye)return;const fe=de=>{if(!r.current)return null;const we=r.current.getBoundingClientRect();return!we.width||!we.height?null:{nx:Math.max(0,Math.min(1,(de.clientX-we.left)/we.width)),ny:Math.max(0,Math.min(1,(de.clientY-we.top)/we.height))}},be=(de,we)=>{if(!r.current)return{dnx:0,dny:0};const ue=r.current,xe=ue.getBoundingClientRect(),se=ue.naturalWidth||xe.width,ie=ue.naturalHeight||xe.height,re=se/ie,q=xe.width/xe.height;let Y,le;return re>q?(Y=xe.width,le=xe.width/re):(le=xe.height,Y=xe.height*re),{dnx:de/Y,dny:we/le}},X=(de,we,ue)=>{if(ue<=1.05)return;const xe=-(de-.5)*100,se=-(we-.5)*100,ie=j(xe,se,ue);(Math.abs(ie.x-l.current)>.1||Math.abs(ie.y-d.current)>.1)&&(f(ie.x),u(ie.y),l.current=ie.x,d.current=ie.y)},ae=de=>{const we=t.current;if(we&&de.target instanceof Node&&we.contains(de.target))de.preventDefault();else return;if(de.touches.length===1){const ue=de.touches[0];M.current={x:ue.clientX,y:ue.clientY,time:Date.now()},T.current={x:ue.clientX,y:ue.clientY},H.current||(k.current=!1),w.current=setTimeout(()=>{if(!k.current&&!H.current)if(k.current=!0,P.current==="mouse"){const xe=g.current||{nx:.5,ny:.5};N("Right Click"),h(xe.nx,xe.ny,"right"),C.current("input_click",{...xe,button:"right"}).catch(()=>{})}else{const xe=fe(ue);xe&&(N("Right Click"),h(xe.nx,xe.ny,"right"),C.current("input_click",{...xe,button:"right"}).catch(()=>{}))}},500);return}if(de.touches.length===2){w.current&&clearTimeout(w.current),k.current=!0,H.current=!0;const ue=de.touches[1].clientX-de.touches[0].clientX,xe=de.touches[1].clientY-de.touches[0].clientY;R.current=Math.sqrt(ue*ue+xe*xe),S.current=c.current,O.current={x:(de.touches[0].clientX+de.touches[1].clientX)/2,y:(de.touches[0].clientY+de.touches[1].clientY)/2}}},ge=de=>{const we=t.current;if(we&&de.target instanceof Node&&we.contains(de.target)&&de.preventDefault(),de.touches.length===1&&T.current){const ue=de.touches[0],xe=ue.clientX-T.current.x,se=ue.clientY-T.current.y;if(!k.current&&M.current){const ie=ue.clientX-M.current.x,re=ue.clientY-M.current.y;Math.sqrt(ie*ie+re*re)>8&&(k.current=!0,w.current&&clearTimeout(w.current))}if(k.current)if(P.current==="mouse"){const ie=be(xe,se),re=g.current||{nx:.5,ny:.5},q=Math.max(0,Math.min(1,re.nx+ie.dnx)),Y=Math.max(0,Math.min(1,re.ny+ie.dny));g.current={nx:q,ny:Y},A({nx:q,ny:Y}),N(`Cursor: ${Math.round(q*100)}%, ${Math.round(Y*100)}%`),X(q,Y,c.current);const le=Date.now();le-m.current>=30&&(m.current=le,C.current("input_mouseMoved",{nx:q,ny:Y}).catch(()=>{}))}else if(c.current>1){const ie=t.current;if(ie){const re=ie.clientWidth,q=ie.clientHeight,Y=l.current+xe/re*100,le=d.current+se/q*100,ke=j(Y,le,c.current);f(ke.x),u(ke.y),l.current=ke.x,d.current=ke.y}}else{const ie=fe(ue);if(ie){const re=Date.now();re-m.current>=40&&(m.current=re,N("Scroll"),C.current("input_wheel",{nx:ie.nx,ny:ie.ny,deltaX:Math.round(-xe*2.5),deltaY:Math.round(-se*2.5)}).catch(()=>{}))}}T.current={x:ue.clientX,y:ue.clientY};return}if(de.touches.length===2&&R.current!==null){const ue=de.touches[1].clientX-de.touches[0].clientX,xe=de.touches[1].clientY-de.touches[0].clientY,ie=Math.sqrt(ue*ue+xe*xe)/R.current,re=(de.touches[0].clientX+de.touches[1].clientX)/2,q=(de.touches[0].clientY+de.touches[1].clientY)/2,Y=re-O.current.x,le=q-O.current.y,ke=Math.abs(ie-1)>.03;if(P.current==="mouse"){if(ke){const Z=Math.max(o,Math.min(5,S.current*ie));p(Z),c.current=Z}else if(Math.abs(Y)>2||Math.abs(le)>2){const Z=g.current||{nx:.5,ny:.5},Ce=Date.now();Ce-m.current>=30&&(m.current=Ce,N("Scroll"),C.current("input_wheel",{nx:Z.nx,ny:Z.ny,deltaX:Math.round(-Y*3),deltaY:Math.round(-le*3)}).catch(()=>{}))}}else{const Z=Math.max(o,Math.min(5,S.current*ie));p(Z),c.current=Z;const Ce=t.current;if(Ce&&Z>1){const Ee=Ce.clientWidth,We=Ce.clientHeight,Fe=l.current+Y/Ee*100,D=d.current+le/We*100,Se=j(Fe,D,Z);f(Se.x),u(Se.y),l.current=Se.x,d.current=Se.y}}O.current={x:re,y:q}}},ee=de=>{var we;if(w.current&&clearTimeout(w.current),R.current=null,de.touches.length===1&&H.current){const ue=de.touches[0];M.current={x:ue.clientX,y:ue.clientY,time:Date.now()},T.current={x:ue.clientX,y:ue.clientY},k.current=!0;return}if(de.touches.length===0){if(H.current){H.current=!1,k.current=!1;return}if(de.changedTouches.length===1){const ue=de.changedTouches[0],xe=Date.now(),se=xe-(((we=M.current)==null?void 0:we.time)||0),ie=M.current?ue.clientX-M.current.x:0,re=M.current?ue.clientY-M.current.y:0,q=Math.sqrt(ie*ie+re*re);if(P.current==="mouse"){if(se<I||se>W||q>E){k.current=!1;return}const Y=g.current||fe(ue);Y&&(N(`Click: ${Math.round(Y.nx*100)}%, ${Math.round(Y.ny*100)}%`),h(Y.nx,Y.ny,"left"),C.current("input_click",{...Y}).catch(()=>{}))}else{if(k.current){k.current=!1;return}if(se<$||se>z||q>J){k.current=!1;return}const Y=fe(ue);if(!Y)return;xe-K.current<300?(N("Double tap"),h(Y.nx,Y.ny,"double"),C.current("input_click",{...Y,clickCount:2}).catch(()=>{}),K.current=0):(N(`Tap: ${Math.round(Y.nx*100)}%, ${Math.round(Y.ny*100)}%`),h(Y.nx,Y.ny,"left"),C.current("input_click",{...Y}).catch(()=>{}),K.current=xe)}}k.current=!1}};return ye.addEventListener("touchstart",ae,{passive:!1}),ye.addEventListener("touchmove",ge,{passive:!1}),ye.addEventListener("touchend",ee,{passive:!1}),()=>{ye.removeEventListener("touchstart",ae),ye.removeEventListener("touchmove",ge),ye.removeEventListener("touchend",ee),w.current&&clearTimeout(w.current)}},[e,t,r,o,c,l,d,f,u,p,m,N,h,j]),{cursorPos:v,cursorPosRef:g,handleToggleInputMode:()=>{a(ye=>{const fe=ye==="touch"?"mouse":"touch";return fe==="mouse"&&he(),fe})},handleZoomReset:()=>{const ye=x?b:1;p(ye),c.current=ye,f(0),u(0),l.current=0,d.current=0}}}function ac({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:o}){const c=i.useRef(null),l=i.useRef(null),d=i.useRef(null),[f,u]=i.useState(null),[p,m]=i.useState(""),[,y]=i.useState(!1),[N,h]=i.useState([]),j=i.useRef(0),[x,b]=i.useState(!1),[v,A]=i.useState(!1),g=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[M,T]=i.useState(g?"mouse":"touch"),[k,w]=i.useState(1),K=i.useRef(!1),[R,S]=i.useState(1),[O,H]=i.useState(0),[P,C]=i.useState(0);dr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:M,zoom:R,panX:O,panY:P,isMenuOpen:x,isImeOpen:v});const I=i.useRef(0),W=i.useRef(R),E=i.useRef(O),$=i.useRef(P);i.useEffect(()=>{W.current=R},[R]),i.useEffect(()=>{E.current=O},[O]),i.useEffect(()=>{$.current=P},[P]),i.useEffect(()=>{var se;(se=c.current)==null||se.focus()},[]);const z=r==="connected",J=n,he=z?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",ce=z?"The remote stream is warming up":"Waiting for the remote stream to catch up";i.useEffect(()=>{if(!g||K.current||!J)return;const se=d.current,ie=l.current;if(!se||!ie)return;const re=()=>{const q=ie.clientWidth,Y=ie.clientHeight,le=se.naturalWidth,ke=se.naturalHeight;if(!le||!ke||!q||!Y)return;const Z=Math.min(q/le,Y/ke),Ee=Math.max(q/le,Y/ke)/Z;Ee>1.01&&(w(Ee),S(Ee),W.current=Ee),K.current=!0};se.complete&&se.naturalWidth?re():se.addEventListener("load",re,{once:!0})},[J,g]);const te=.5;i.useEffect(()=>{R<=te&&(H(0),C(0))},[R,te]);const ye=(se,ie,re)=>{if(re<=te)return{x:0,y:0};const q=(re-1)/(2*re)*100,Y=(re-1)/(2*re)*100;return{x:Math.max(-q,Math.min(q,se)),y:Math.max(-Y,Math.min(Y,ie))}},fe=(se,ie)=>{if(!d.current)return null;const re=d.current.getBoundingClientRect();return!re.width||!re.height?null:{nx:Math.max(0,Math.min(1,(se-re.left)/re.width)),ny:Math.max(0,Math.min(1,(ie-re.top)/re.height))}},be=(se,ie,re)=>{const q=l.current;if(!q)return;const Y=q.getBoundingClientRect(),le=++j.current;h(ke=>[...ke,{id:le,x:se-Y.left,y:ie-Y.top,type:re}]),setTimeout(()=>h(ke=>ke.filter(Z=>Z.id!==le)),600)},X=(se,ie,re)=>{const q=d.current,Y=l.current;if(!q||!Y)return;const le=q.getBoundingClientRect(),ke=Y.getBoundingClientRect(),Z=q.naturalWidth||le.width,Ce=q.naturalHeight||le.height,Ee=Z/Ce,We=le.width/le.height;let Fe,D,Se,Ae;Ee>We?(Fe=le.width,D=le.width/Ee,Se=0,Ae=(le.height-D)/2):(D=le.height,Fe=le.height*Ee,Se=(le.width-Fe)/2,Ae=0);const Le=le.left-ke.left+Se+Fe*se,Pe=le.top-ke.top+Ae+D*ie,He=++j.current;h(Ue=>[...Ue,{id:He,x:Le,y:Pe,type:re}]),setTimeout(()=>h(Ue=>Ue.filter(Qe=>Qe.id!==He)),600)},ae=async se=>{var re;const ie=fe(se.clientX,se.clientY);if(ie){u(`Click: ${Math.round(ie.nx*100)}%, ${Math.round(ie.ny*100)}%`),be(se.clientX,se.clientY,"left"),(re=c.current)==null||re.focus();try{const q=await e("input_click",{nx:ie.nx,ny:ie.ny});q!=null&&q.success||t(`❌ Click failed: ${q==null?void 0:q.error}`)}catch(q){t(`❌ Click error: ${q.message||q}`)}}},ge=async(se,ie,re,q=0)=>{try{await e("input_key",{type:re?"char":"keyDown",key:se,code:ie,text:re?se:void 0,unmodifiedText:re?se:void 0,modifiers:q})}catch(Y){t(`❌ Key error: ${Y.message||Y}`)}},ee=async se=>{if(se.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(se.key)&&se.preventDefault();let re=0;se.altKey&&(re|=1),se.ctrlKey&&(re|=2),se.metaKey&&(re|=4),se.shiftKey&&(re|=8),u(`Key: ${se.key}`),await ge(se.key,se.code,se.key.length===1,re)},de=async se=>{if(se.key==="Enter"){if(se.nativeEvent.isComposing)return;if(p){const ie=p;m(""),u(`IME Sent: ${ie}`);try{const re=await e("input_type",{text:ie});re!=null&&re.success||t(`❌ IME error: ${re==null?void 0:re.error}`)}catch(re){t(`❌ IME error: ${re.message}`)}}else u("Key: Enter"),await ge("Enter","Enter",!1)}};i.useEffect(()=>{const se=c.current;if(!se)return;const ie=re=>{var q;if((q=d.current)!=null&&q.contains(re.target)){re.preventDefault();const Y=Date.now();if(Y-I.current<40)return;I.current=Y;const le=fe(re.clientX,re.clientY);if(!le)return;u(`Scroll: ${Math.round(re.deltaY)}`),e("input_wheel",{nx:le.nx,ny:le.ny,deltaX:Math.round(re.deltaX),deltaY:Math.round(re.deltaY)}).catch(()=>{})}};return se.addEventListener("wheel",ie,{passive:!1}),()=>se.removeEventListener("wheel",ie)},[e]);const{cursorPos:we,handleToggleInputMode:ue,handleZoomReset:xe}=zu({containerRef:c,viewportRef:l,imgRef:d,inputMode:M,setInputMode:T,minZoom:te,zoomRef:W,panXRef:E,panYRef:$,setPanX:H,setPanY:C,setZoom:S,lastWheelTimeRef:I,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:X,clampPan:ye,isMobile:g,mobileFillZoom:k});return s.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ee,onContextMenu:se=>se.preventDefault(),onFocus:()=>y(!0),onBlur:()=>y(!1),tabIndex:0,children:[s.jsxs("div",{ref:l,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(${R}) translate(${O}%, ${P}%)`,transformOrigin:"center center",cursor:M==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:ae,onContextMenu:se=>se.preventDefault(),onDragStart:se=>se.preventDefault()}):s.jsx(Hu,{waitingLabel:he,waitingHint:ce,transportType:o}),M==="mouse"&&J&&s.jsx(Wu,{cursorPos:we,viewportRef:l,imgRef:d}),N.map(se=>{const re={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[se.type];return s.jsxs("div",{style:{position:"absolute",left:se.x,top:se.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${re}, 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(${re}, 0.9)`,boxShadow:`0 0 12px rgba(${re}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},se.id)})]}),s.jsx(Fu,{inputMode:M,onToggleInputMode:ue,isImeOpen:v,setIsImeOpen:A,isMenuOpen:x,setIsMenuOpen:b,imeText:p,setImeText:m,handleImeSubmit:de,isConnActive:z,zoom:R,isMobile:g,mobileFillZoom:k,onZoomOut:()=>S(se=>Math.max(.5,se-.25)),onZoomReset:xe,onZoomIn:()=>S(se=>Math.min(5,se+.25)),transportType:o,screenshotUsage:a,lastActionStatus:f}),s.jsx("style",{children:`
5
5
  @keyframes slideUp {
6
6
  from { opacity: 0; transform: translateY(6px); }
7
7
  to { opacity: 1; transform: translateY(0); }
@@ -24,9 +24,9 @@ var gd=Object.defineProperty;var yd=(e,t,r)=>t in e?gd(e,t,{enumerable:!0,config
24
24
  50% { transform: translateY(-7px); }
25
25
  100% { transform: translateY(0px); }
26
26
  }
27
- `})]})}function ln(e,t={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=t,o=Date.now()-e,c=Math.floor(o/1e3);if(c<a)return n;const l=Math.floor(c/60);if(l<60)return`${l}m${r}`;const d=Math.floor(l/60);if(d<24)return`${d}h${r}`;const f=Math.floor(d/24);return f<7?`${f}d${r}`:new Date(e).toLocaleDateString()}const oc=e=>ln(e);function zu(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 Ds(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 Vu(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...zu(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 Yr(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 dn(e,t,r){const n=Yr(e,t),a=Ds(e),o=a.isReconnecting,c=a.isConnecting,l=a.isGenerating,d=a.isWaiting,f=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||d,u=n.inboxBucket==="working"||l,m=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:m,requiresAction:f,isWorking:u,isReconnecting:o,isConnecting:c,isGenerating:l,isWaiting:d,inboxBucket:f?"needs_attention":u?"working":m?"task_complete":"idle"}}function Gu(e,t,r){return dn(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function ic({activeConv:e,onModalButton:t}){const[r,n]=i.useState(null);if(i.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Ds(e).isWaiting||!e.modalButtons)return null;const o=l=>{r||(n(l),t(l))},c=l=>l.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(nr,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,d)=>{const f=c(l).toLowerCase(),u=/^(run|approve|accept|yes|allow|always)/.test(f),p=/^(reject|deny|delete|remove|abort)/.test(f),m=r===l,y=r!==null;return s.jsx("button",{onClick:()=>o(l),disabled:y,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${u?"font-extrabold":p?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${y&&!m?"opacity-40":"opacity-100"} ${y?"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)"}:p?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:m?"⏳ ...":c(l)},d)})})]})]})}const Ka="adhdev_controls_bar_visible",ua="adhdev:controlsbarvisibilitychange";function Sn(e){if(!e)return!1;try{return e.getItem(Ka)==="1"}catch{return!1}}function qu(e,t){if(t)try{t.setItem(Ka,e?"1":"0")}catch{}}function Yu(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(ua,{detail:{visible:e}}))}function Oa(){const[e,t]=i.useState(()=>typeof window>"u"?!1:Sn(window.localStorage)),r=i.useRef(e),n=i.useCallback((c,l=!0)=>{r.current=c,t(c),typeof window<"u"&&qu(c,window.localStorage),l&&Yu(c)},[]);i.useEffect(()=>{const c=d=>{const f=d.detail,u=typeof(f==null?void 0:f.visible)=="boolean"?f.visible:Sn(window.localStorage);r.current=u,t(u)},l=d=>{if(d.key!==Ka)return;const f=Sn(window.localStorage);r.current=f,t(f)};return window.addEventListener(ua,c),window.addEventListener("storage",l),()=>{window.removeEventListener(ua,c),window.removeEventListener("storage",l)}},[]);const a=i.useCallback(c=>{n(c)},[n]),o=i.useCallback(()=>{n(!r.current)},[n]);return{isVisible:e,setVisibility:a,toggleVisibility:o}}var Xu=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Ju(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function yt(e,t){if(Ju(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":Xu.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 cc(e){return yt(e)==="generating"}function at(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function Qu(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 Nn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function un(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 Zu(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 ef(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function tf(e){return Zu(e.trim().replace(/\.local$/i,""))}function sf(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function lc(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(c=>typeof c=="string"&&c.trim().length>0&&!ef(c));if(r&&r!=="Unknown")return tf(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Ct(e,t={}){return sf(e)||lc(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 uc(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 fs(e,t){return dc(e).join(" · ")}function or(e){return e.transport==="pty"}function js(e){return e.transport==="acp"}function rf(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:at(e)}function Eo(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),c=at(r||"").trim().toLowerCase();return n===a||n===o||n===c}function nf(e){return yt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function af(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),c=yt(n.status);if(!o){t.set(a,{...n,status:c});continue}const l=r.indexOf(o.status||"idle"),d=r.indexOf(c||"idle");d>=0&&(l<0||d<l)&&t.set(a,{...n,status:c})}return Array.from(t.values())}function of(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 cf(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&&of(t.receivedAt)||0}function lf(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function fa(e){return Math.max(lf(e),cf(e.activeChat))}function df(e,t,r,n,a,o){const c=t-e;if(c!==0)return c;const l=r.localeCompare(n);return l!==0?l:a.localeCompare(o)}function Wa(e,t){return df(fa(e),fa(t),Ct(e,{fallbackId:e.id}),Ct(t,{fallbackId:t.id}),e.id,t.id)}const fc="adhdev_notification_prefs",$o={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function uf(){try{const e=localStorage.getItem(fc);if(e){const t=JSON.parse(e);return{...$o,...t}}}catch{}return{...$o}}function ff(e){try{localStorage.setItem(fc,JSON.stringify(e))}catch{}}let Wt=uf(),Dr=[];function mf(){Dr.forEach(e=>e())}function pf(e){Wt={...Wt,...e},ff(Wt),mf()}function hf(){const[,e]=i.useState(0);i.useEffect(()=>{const r=()=>e(n=>n+1);return Dr.push(r),()=>{Dr=Dr.filter(n=>n!==r)}},[]);const t=i.useCallback(r=>{pf(r)},[]);return[{...Wt},t]}function Js(e){if(!Wt.globalEnabled)return!1;switch(e){case"disconnect":return Wt.disconnectAlert;case"completion":return Wt.completionAlert;case"approval":return Wt.approvalAlert;case"browser":return Wt.browserNotifications;default:return!0}}const xf={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function mc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function pc(){return"Notification"in window&&Notification.permission==="granted"}let Jt=null;function bf(e){return e!==!1}async function gf(){if(Jt!==null)return Jt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Jt=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Jt=!!await e.pushManager.getSubscription(),Jt):(Jt=!1,!1)}catch{return Jt=!1,!1}}function ma(e,t,r){if(pc())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 yf(e,t={}){const r={...xf,...t},n=i.useRef(new Map),a=i.useRef(0),[o,c]=i.useState(null);i.useEffect(()=>{let d=!1;return gf().then(f=>{d||c(f)}),()=>{d=!0}},[]);const l=i.useCallback((d,f,u)=>{const p=Date.now();p-a.current<r.throttleMs||(a.current=p,ma(d,f,u))},[r.throttleMs]);i.useEffect(()=>{var d;if(!(!r.enabled||!pc())&&Js("browser")&&!bf(o)){if(document.hasFocus()){for(const f of e)n.current.set(f.id,yt(f.status,{activeModal:f.activeModal}));return}for(const f of e){const u=n.current.get(f.id),p=yt(f.status,{activeModal:f.activeModal}),m=f.name||f.id;if(r.onApproval&&Js("approval")&&p==="waiting_approval"&&u!=="waiting_approval"){const y=((d=f.activeModal)==null?void 0:d.message)||"Action requires your approval";l(`🔔 ${m} — Approval needed`,y.slice(0,120),`approval-${f.id}`)}r.onComplete&&Js("completion")&&cc(u)&&p==="idle"&&l(`✅ ${m} — Task complete`,"Agent has finished generating",`complete-${f.id}`),r.onError&&p==="error"&&u!=="error"&&l(`⚠️ ${m} — Error`,"Agent encountered an error",`error-${f.id}`),n.current.set(f.id,p)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,l])}const vf=/^(run|approve|accept|yes|allow|always)/,wf=/^(run|approve|accept|yes|allow|always|proceed|save)/,jf=/^(reject|deny|delete|remove|abort|cancel|no)/;function Fa(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function kf(e){const t=Fa(e).toLowerCase();return vf.test(t)?"primary":jf.test(t)?"danger":"default"}function Sf(e){return wf.test(Fa(e).toLowerCase())?"approve":"reject"}function Nf(e){return e.map((t,r)=>({label:Fa(t),variant:kf(t),action:Sf(t),button:t,buttonIndex:r}))}function Cf(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Tf(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 Mf{constructor(){Ye(this,"dedupMap",new Map);Ye(this,"DEDUP_WINDOW_MS",5e3);Ye(this,"DEDUP_MAX_SIZE",50);Ye(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ye(this,"toastCallbacks",[]);Ye(this,"resolveActionFn",null);Ye(this,"viewRequestRespondFn",null);Ye(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.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(c=>c.id===a&&c.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 N;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),o=n||t.daemonId||"",c=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),l=`${o}:${t.event}:${c}`;if(this.isDuplicate(l))return;const d=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,f=(d==null?void 0:d.type)||"";let u=at(f);const p=this.resolveOwningDaemon(t);if(p){const h=Ct(p,{fallbackId:p.id});h&&(u=!f||f==="adhdev-daemon"?h:`${h}/${u}`)}let m="",y="info";if(t.event==="agent:generating_completed"){const h=t.duration?` (${t.duration}s)`:"";m=`✅ ${u} agent task completed${h}`,y="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(m=`⚡ ${u} approval needed`,y="warning",(N=t.modalButtons)!=null&&N.length&&this.resolveActionFn){const h=this.resolveActionRouteTarget(t);if(!h)return;const j=this.resolveActionFn,x=Nf(t.modalButtons).map(A=>({label:A.label,variant:A.variant,onClick:()=>{j(h,"resolve_action",{action:A.action,button:A.button,buttonIndex:A.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),b=Cf(u,t.modalMessage,m),v=Date.now();this.emitToast({id:v,message:b,type:y,timestamp:v,targetKey:n||h,actions:x,duration:15e3}),m=""}}else if(t.event==="monitor:long_generating"){const h=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";m=`⚠️ ${u} agent is taking a long time${h}`,y="warning",Js("browser")&&!document.hasFocus()&&ma(`⚠️ ${u} — Long Running`,`Agent has been generating for over ${h.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const h=t.requesterName||"A team member",j=t.requestId,x=t.orgId;if(m=`👁️ ${h} wants to view your session`,y="warning",j&&x&&this.viewRequestRespondFn){const b=Date.now(),v=Tf(x,j,this.viewRequestRespondFn,(A,g)=>console.error(`[EventManager] ${A} view request failed:`,g));this.emitToast({id:b,message:m,type:y,timestamp:b,actions:v,duration:3e4}),m=""}Js("browser")&&!document.hasFocus()&&ma("👁️ View Request",`${h} wants to view your session`,`view-request-${j}`)}else t.event==="team:view_request_approved"?(m="✅ View request approved",y="success"):t.event==="team:view_request_rejected"&&(m=`❌ ${t.targetName||"Team member"} declined your view request`,y="warning");if(m){const h=Date.now();this.emitToast({id:h,message:m,type:y,timestamp:h,targetKey:n||t.daemonId,duration:5e3})}}}const rt=new Mf,Bo=new Map;function Xr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ks(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function fn(e){return Xr(e)?Xr(e.result)?e.result:e:null}function Af(e){const t=fn(e);return!t||!Xr(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function wr(e){const t=fn(e);return!t||!Xr(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function Os(e){const t=fn(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function jr(e){const t=fn(e);return!!t&&t.success===!1}function If(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";rt.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";rt.showToast(n.notification.body,a)}}}function Lf(e,t){return e&&ks(e.currentValue)?e.currentValue:t}function Rf(e,t){return ks(t)?ks(e)?typeof e=="string"&&e.trim()==="":!0:!1}function _f(e,t){var o,c;if((t.now??Date.now())<t.localOverrideUntil){const l=t.localValues[e];if(ks(l))return l}const n=(o=t.controlValues)==null?void 0:o[e];if(ks(n))return n;const a=(c=t.defaultValues)==null?void 0:c[e];return ks(a)?a:void 0}function Er(e,t){return e.options||t[e.id]||[]}const Pf={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 Df(e,t,r){var n;return((n=Pf[t])==null?void 0:n.has(r.id))===!0}function Ha(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Df(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function Cn(e,t){return{value:t}}function Ef(e,t,r){var a;return r?((a=Er(e,t).find(o=>o.value===r))==null?void 0:a.label)||r:""}const $f={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Bf({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:c}){const{sendCommand:l}=mt(),d=`${e}:${t||n}`,f=$f[n]||"#94a3b8",[u,p]=i.useState({}),m=i.useRef({}),y=i.useRef(c);m.current=u,y.current=c;const N=i.useRef(0),h={};for(const I of o||[])I.defaultValue!==void 0&&(h[I.id]=I.defaultValue);const j={...h,...c||{},...Date.now()<N.current?u:{}};i.useEffect(()=>{c&&Date.now()>N.current&&p({})},[c]);const[x,b]=i.useState(Bo.get(d)||{}),[v,A]=i.useState(null),[g,M]=i.useState(null),T=i.useCallback(async(I,W={})=>{const E={...W,...t&&{targetSessionId:t}};return await l(e,I,E)},[e,t,l]),k=i.useCallback(async(I,W={})=>{const E=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await T("invoke_provider_script",{...E,scriptName:I,...W})},[T,n,r,t]),w=i.useCallback((I,W,E)=>{const $=Lf(E,W);p(F=>({...F,[I.id]:$})),If(E==null?void 0:E.effects)},[]),K=i.useCallback((I,W)=>{p(E=>{const $={...E};return W===void 0?delete $[I.id]:$[I.id]=W,$}),N.current=0},[]);if(!o||o.length===0)return null;const R=Ha(o,{hostIdeType:r,providerType:n});if(R.length===0)return null;const S=async I=>{if(v===I.id){A(null);return}if(Er(I,x).length>0){A(I.id);return}if(I.dynamic&&I.listScript){M(I.id);try{const E=await k(I.listScript,{}),$=Af(E);if(!$){const he=Os(E);he&&rt.showToast(he,"warning");return}const F=$.options;b(he=>{const le={...he,[I.id]:F};return Bo.set(d,le),le});const J=_f(I.id,{localOverrideUntil:N.current,localValues:m.current,controlValues:y.current,defaultValues:h});if(Rf(J,$.currentValue)){const he=$.currentValue;p(le=>({...le,[I.id]:he}))}A(I.id)}catch(E){const $=E instanceof Error?E.message:`Could not load ${I.label}`;rt.showToast($,"warning")}finally{M(null)}}},O=async(I,W)=>{A(null);const E=(c==null?void 0:c[I.id])??h[I.id];p($=>({...$,[I.id]:W})),N.current=Date.now()+5e3;try{if(!I.setScript)return;const $=await k(I.setScript,Cn(I,W)),F=wr($);if(F&&!F.ok||jr($))throw new Error((F==null?void 0:F.error)||Os($)||`Could not update ${I.label}`);w(I,W,F)}catch($){K(I,E);const F=$ instanceof Error?$.message:`Could not update ${I.label}`;rt.showToast(F,"warning")}},U=async I=>{const W=Er(I,x).map(le=>le.value);if(W.length===0)return;const E=String(j[I.id]||""),F=(W.indexOf(E)+1)%W.length,J=W[F];if(typeof J!="string")return;const he=(c==null?void 0:c[I.id])??h[I.id];p(le=>({...le,[I.id]:J})),N.current=Date.now()+5e3;try{if(!I.setScript)return;const le=await k(I.setScript,Cn(I,J)),te=wr(le);if(te&&!te.ok||jr(le))throw new Error((te==null?void 0:te.error)||Os(le)||`Could not update ${I.label}`);w(I,J,te)}catch(le){K(I,he);const te=le instanceof Error?le.message:`Could not update ${I.label}`;rt.showToast(te,"warning")}},P=async I=>{const E=!j[I.id],$=(c==null?void 0:c[I.id])??h[I.id];p(F=>({...F,[I.id]:E})),N.current=Date.now()+5e3;try{if(!I.setScript)return;const F=await k(I.setScript,Cn(I,E)),J=wr(F);if(J&&!J.ok||jr(F))throw new Error((J==null?void 0:J.error)||Os(F)||`Could not update ${I.label}`);w(I,E,J)}catch(F){K(I,$);const J=F instanceof Error?F.message:`Could not update ${I.label}`;rt.showToast(J,"warning")}},C=async I=>{if(!I.invokeScript)return;if(I.confirmMessage){const E=[I.confirmTitle,I.confirmMessage,I.confirmLabel].filter(F=>typeof F=="string"&&F.trim().length>0);if(!window.confirm(E.join(`
27
+ `})]})}function ln(e,t={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=t,o=Date.now()-e,c=Math.floor(o/1e3);if(c<a)return n;const l=Math.floor(c/60);if(l<60)return`${l}m${r}`;const d=Math.floor(l/60);if(d<24)return`${d}h${r}`;const f=Math.floor(d/24);return f<7?`${f}d${r}`:new Date(e).toLocaleDateString()}const oc=e=>ln(e);function Vu(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 Ds(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 Gu(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...Vu(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 Yr(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 dn(e,t,r){const n=Yr(e,t),a=Ds(e),o=a.isReconnecting,c=a.isConnecting,l=a.isGenerating,d=a.isWaiting,f=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||d,u=n.inboxBucket==="working"||l,m=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:m,requiresAction:f,isWorking:u,isReconnecting:o,isConnecting:c,isGenerating:l,isWaiting:d,inboxBucket:f?"needs_attention":u?"working":m?"task_complete":"idle"}}function qu(e,t,r){return dn(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function ic({activeConv:e,onModalButton:t}){const[r,n]=i.useState(null);if(i.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Ds(e).isWaiting||!e.modalButtons)return null;const o=l=>{r||(n(l),t(l))},c=l=>l.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(nr,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,d)=>{const f=c(l).toLowerCase(),u=/^(run|approve|accept|yes|allow|always)/.test(f),p=/^(reject|deny|delete|remove|abort)/.test(f),m=r===l,y=r!==null;return s.jsx("button",{onClick:()=>o(l),disabled:y,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${u?"font-extrabold":p?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${y&&!m?"opacity-40":"opacity-100"} ${y?"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)"}:p?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:m?"⏳ ...":c(l)},d)})})]})]})}const Ka="adhdev_controls_bar_visible",ua="adhdev:controlsbarvisibilitychange";function Sn(e){if(!e)return!1;try{return e.getItem(Ka)==="1"}catch{return!1}}function Yu(e,t){if(t)try{t.setItem(Ka,e?"1":"0")}catch{}}function Xu(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(ua,{detail:{visible:e}}))}function Oa(){const[e,t]=i.useState(()=>typeof window>"u"?!1:Sn(window.localStorage)),r=i.useRef(e),n=i.useCallback((c,l=!0)=>{r.current=c,t(c),typeof window<"u"&&Yu(c,window.localStorage),l&&Xu(c)},[]);i.useEffect(()=>{const c=d=>{const f=d.detail,u=typeof(f==null?void 0:f.visible)=="boolean"?f.visible:Sn(window.localStorage);r.current=u,t(u)},l=d=>{if(d.key!==Ka)return;const f=Sn(window.localStorage);r.current=f,t(f)};return window.addEventListener(ua,c),window.addEventListener("storage",l),()=>{window.removeEventListener(ua,c),window.removeEventListener("storage",l)}},[]);const a=i.useCallback(c=>{n(c)},[n]),o=i.useCallback(()=>{n(!r.current)},[n]);return{isVisible:e,setVisibility:a,toggleVisibility:o}}var Ju=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Qu(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function yt(e,t){if(Qu(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":Ju.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 cc(e){return yt(e)==="generating"}function at(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function Zu(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 Nn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function un(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 ef(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 tf(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function sf(e){return ef(e.trim().replace(/\.local$/i,""))}function rf(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function lc(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(c=>typeof c=="string"&&c.trim().length>0&&!tf(c));if(r&&r!=="Unknown")return sf(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Ct(e,t={}){return rf(e)||lc(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 uc(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 fs(e,t){return dc(e).join(" · ")}function or(e){return e.transport==="pty"}function js(e){return e.transport==="acp"}function nf(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:at(e)}function Eo(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),c=at(r||"").trim().toLowerCase();return n===a||n===o||n===c}function af(e){return yt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function of(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),c=yt(n.status);if(!o){t.set(a,{...n,status:c});continue}const l=r.indexOf(o.status||"idle"),d=r.indexOf(c||"idle");d>=0&&(l<0||d<l)&&t.set(a,{...n,status:c})}return Array.from(t.values())}function cf(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 lf(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&&cf(t.receivedAt)||0}function df(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function fa(e){return Math.max(df(e),lf(e.activeChat))}function uf(e,t,r,n,a,o){const c=t-e;if(c!==0)return c;const l=r.localeCompare(n);return l!==0?l:a.localeCompare(o)}function Wa(e,t){return uf(fa(e),fa(t),Ct(e,{fallbackId:e.id}),Ct(t,{fallbackId:t.id}),e.id,t.id)}const fc="adhdev_notification_prefs",$o={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function ff(){try{const e=localStorage.getItem(fc);if(e){const t=JSON.parse(e);return{...$o,...t}}}catch{}return{...$o}}function mf(e){try{localStorage.setItem(fc,JSON.stringify(e))}catch{}}let Wt=ff(),Dr=[];function pf(){Dr.forEach(e=>e())}function hf(e){Wt={...Wt,...e},mf(Wt),pf()}function xf(){const[,e]=i.useState(0);i.useEffect(()=>{const r=()=>e(n=>n+1);return Dr.push(r),()=>{Dr=Dr.filter(n=>n!==r)}},[]);const t=i.useCallback(r=>{hf(r)},[]);return[{...Wt},t]}function Js(e){if(!Wt.globalEnabled)return!1;switch(e){case"disconnect":return Wt.disconnectAlert;case"completion":return Wt.completionAlert;case"approval":return Wt.approvalAlert;case"browser":return Wt.browserNotifications;default:return!0}}const bf={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function mc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function pc(){return"Notification"in window&&Notification.permission==="granted"}let Jt=null;function gf(e){return e!==!1}async function yf(){if(Jt!==null)return Jt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Jt=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Jt=!!await e.pushManager.getSubscription(),Jt):(Jt=!1,!1)}catch{return Jt=!1,!1}}function ma(e,t,r){if(pc())try{const n=new Notification(e,{body:t,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function vf(e,t={}){const r={...bf,...t},n=i.useRef(new Map),a=i.useRef(0),[o,c]=i.useState(null);i.useEffect(()=>{let d=!1;return yf().then(f=>{d||c(f)}),()=>{d=!0}},[]);const l=i.useCallback((d,f,u)=>{const p=Date.now();p-a.current<r.throttleMs||(a.current=p,ma(d,f,u))},[r.throttleMs]);i.useEffect(()=>{var d;if(!(!r.enabled||!pc())&&Js("browser")&&!gf(o)){if(document.hasFocus()){for(const f of e)n.current.set(f.id,yt(f.status,{activeModal:f.activeModal}));return}for(const f of e){const u=n.current.get(f.id),p=yt(f.status,{activeModal:f.activeModal}),m=f.name||f.id;if(r.onApproval&&Js("approval")&&p==="waiting_approval"&&u!=="waiting_approval"){const y=((d=f.activeModal)==null?void 0:d.message)||"Action requires your approval";l(`🔔 ${m} — Approval needed`,y.slice(0,120),`approval-${f.id}`)}r.onComplete&&Js("completion")&&cc(u)&&p==="idle"&&l(`✅ ${m} — Task complete`,"Agent has finished generating",`complete-${f.id}`),r.onError&&p==="error"&&u!=="error"&&l(`⚠️ ${m} — Error`,"Agent encountered an error",`error-${f.id}`),n.current.set(f.id,p)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,l])}const wf=/^(run|approve|accept|yes|allow|always)/,jf=/^(run|approve|accept|yes|allow|always|proceed|save)/,kf=/^(reject|deny|delete|remove|abort|cancel|no)/;function Fa(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Sf(e){const t=Fa(e).toLowerCase();return wf.test(t)?"primary":kf.test(t)?"danger":"default"}function Nf(e){return jf.test(Fa(e).toLowerCase())?"approve":"reject"}function Cf(e){return e.map((t,r)=>({label:Fa(t),variant:Sf(t),action:Nf(t),button:t,buttonIndex:r}))}function Tf(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Mf(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 Af{constructor(){Ye(this,"dedupMap",new Map);Ye(this,"DEDUP_WINDOW_MS",5e3);Ye(this,"DEDUP_MAX_SIZE",50);Ye(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ye(this,"toastCallbacks",[]);Ye(this,"resolveActionFn",null);Ye(this,"viewRequestRespondFn",null);Ye(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.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(c=>c.id===a&&c.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 N;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),o=n||t.daemonId||"",c=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),l=`${o}:${t.event}:${c}`;if(this.isDuplicate(l))return;const d=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,f=(d==null?void 0:d.type)||"";let u=at(f);const p=this.resolveOwningDaemon(t);if(p){const h=Ct(p,{fallbackId:p.id});h&&(u=!f||f==="adhdev-daemon"?h:`${h}/${u}`)}let m="",y="info";if(t.event==="agent:generating_completed"){const h=t.duration?` (${t.duration}s)`:"";m=`✅ ${u} agent task completed${h}`,y="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(m=`⚡ ${u} approval needed`,y="warning",(N=t.modalButtons)!=null&&N.length&&this.resolveActionFn){const h=this.resolveActionRouteTarget(t);if(!h)return;const j=this.resolveActionFn,x=Cf(t.modalButtons).map(A=>({label:A.label,variant:A.variant,onClick:()=>{j(h,"resolve_action",{action:A.action,button:A.button,buttonIndex:A.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),b=Tf(u,t.modalMessage,m),v=Date.now();this.emitToast({id:v,message:b,type:y,timestamp:v,targetKey:n||h,actions:x,duration:15e3}),m=""}}else if(t.event==="monitor:long_generating"){const h=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";m=`⚠️ ${u} agent is taking a long time${h}`,y="warning",Js("browser")&&!document.hasFocus()&&ma(`⚠️ ${u} — Long Running`,`Agent has been generating for over ${h.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const h=t.requesterName||"A team member",j=t.requestId,x=t.orgId;if(m=`👁️ ${h} wants to view your session`,y="warning",j&&x&&this.viewRequestRespondFn){const b=Date.now(),v=Mf(x,j,this.viewRequestRespondFn,(A,g)=>console.error(`[EventManager] ${A} view request failed:`,g));this.emitToast({id:b,message:m,type:y,timestamp:b,actions:v,duration:3e4}),m=""}Js("browser")&&!document.hasFocus()&&ma("👁️ View Request",`${h} wants to view your session`,`view-request-${j}`)}else t.event==="team:view_request_approved"?(m="✅ View request approved",y="success"):t.event==="team:view_request_rejected"&&(m=`❌ ${t.targetName||"Team member"} declined your view request`,y="warning");if(m){const h=Date.now();this.emitToast({id:h,message:m,type:y,timestamp:h,targetKey:n||t.daemonId,duration:5e3})}}}const rt=new Af,Bo=new Map;function Xr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ks(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function fn(e){return Xr(e)?Xr(e.result)?e.result:e:null}function If(e){const t=fn(e);return!t||!Xr(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function wr(e){const t=fn(e);return!t||!Xr(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function Os(e){const t=fn(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function jr(e){const t=fn(e);return!!t&&t.success===!1}function Lf(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";rt.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";rt.showToast(n.notification.body,a)}}}function Rf(e,t){return e&&ks(e.currentValue)?e.currentValue:t}function _f(e,t){return ks(t)?ks(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Pf(e,t){var o,c;if((t.now??Date.now())<t.localOverrideUntil){const l=t.localValues[e];if(ks(l))return l}const n=(o=t.controlValues)==null?void 0:o[e];if(ks(n))return n;const a=(c=t.defaultValues)==null?void 0:c[e];return ks(a)?a:void 0}function Er(e,t){return e.options||t[e.id]||[]}const Df={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 Ef(e,t,r){var n;return((n=Df[t])==null?void 0:n.has(r.id))===!0}function Ha(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Ef(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function Cn(e,t){return{value:t}}function $f(e,t,r){var a;return r?((a=Er(e,t).find(o=>o.value===r))==null?void 0:a.label)||r:""}const Bf={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Kf({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:c}){const{sendCommand:l}=mt(),d=`${e}:${t||n}`,f=Bf[n]||"#94a3b8",[u,p]=i.useState({}),m=i.useRef({}),y=i.useRef(c);m.current=u,y.current=c;const N=i.useRef(0),h={};for(const I of o||[])I.defaultValue!==void 0&&(h[I.id]=I.defaultValue);const j={...h,...c||{},...Date.now()<N.current?u:{}};i.useEffect(()=>{c&&Date.now()>N.current&&p({})},[c]);const[x,b]=i.useState(Bo.get(d)||{}),[v,A]=i.useState(null),[g,M]=i.useState(null),T=i.useCallback(async(I,W={})=>{const E={...W,...t&&{targetSessionId:t}};return await l(e,I,E)},[e,t,l]),k=i.useCallback(async(I,W={})=>{const E=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await T("invoke_provider_script",{...E,scriptName:I,...W})},[T,n,r,t]),w=i.useCallback((I,W,E)=>{const $=Rf(E,W);p(z=>({...z,[I.id]:$})),Lf(E==null?void 0:E.effects)},[]),K=i.useCallback((I,W)=>{p(E=>{const $={...E};return W===void 0?delete $[I.id]:$[I.id]=W,$}),N.current=0},[]);if(!o||o.length===0)return null;const R=Ha(o,{hostIdeType:r,providerType:n});if(R.length===0)return null;const S=async I=>{if(v===I.id){A(null);return}if(Er(I,x).length>0){A(I.id);return}if(I.dynamic&&I.listScript){M(I.id);try{const E=await k(I.listScript,{}),$=If(E);if(!$){const he=Os(E);he&&rt.showToast(he,"warning");return}const z=$.options;b(he=>{const ce={...he,[I.id]:z};return Bo.set(d,ce),ce});const J=Pf(I.id,{localOverrideUntil:N.current,localValues:m.current,controlValues:y.current,defaultValues:h});if(_f(J,$.currentValue)){const he=$.currentValue;p(ce=>({...ce,[I.id]:he}))}A(I.id)}catch(E){const $=E instanceof Error?E.message:`Could not load ${I.label}`;rt.showToast($,"warning")}finally{M(null)}}},O=async(I,W)=>{A(null);const E=(c==null?void 0:c[I.id])??h[I.id];p($=>({...$,[I.id]:W})),N.current=Date.now()+5e3;try{if(!I.setScript)return;const $=await k(I.setScript,Cn(I,W)),z=wr($);if(z&&!z.ok||jr($))throw new Error((z==null?void 0:z.error)||Os($)||`Could not update ${I.label}`);w(I,W,z)}catch($){K(I,E);const z=$ instanceof Error?$.message:`Could not update ${I.label}`;rt.showToast(z,"warning")}},H=async I=>{const W=Er(I,x).map(ce=>ce.value);if(W.length===0)return;const E=String(j[I.id]||""),z=(W.indexOf(E)+1)%W.length,J=W[z];if(typeof J!="string")return;const he=(c==null?void 0:c[I.id])??h[I.id];p(ce=>({...ce,[I.id]:J})),N.current=Date.now()+5e3;try{if(!I.setScript)return;const ce=await k(I.setScript,Cn(I,J)),te=wr(ce);if(te&&!te.ok||jr(ce))throw new Error((te==null?void 0:te.error)||Os(ce)||`Could not update ${I.label}`);w(I,J,te)}catch(ce){K(I,he);const te=ce instanceof Error?ce.message:`Could not update ${I.label}`;rt.showToast(te,"warning")}},P=async I=>{const E=!j[I.id],$=(c==null?void 0:c[I.id])??h[I.id];p(z=>({...z,[I.id]:E})),N.current=Date.now()+5e3;try{if(!I.setScript)return;const z=await k(I.setScript,Cn(I,E)),J=wr(z);if(J&&!J.ok||jr(z))throw new Error((J==null?void 0:J.error)||Os(z)||`Could not update ${I.label}`);w(I,E,J)}catch(z){K(I,$);const J=z instanceof Error?z.message:`Could not update ${I.label}`;rt.showToast(J,"warning")}},C=async I=>{if(!I.invokeScript)return;if(I.confirmMessage){const E=[I.confirmTitle,I.confirmMessage,I.confirmLabel].filter(z=>typeof z=="string"&&z.trim().length>0);if(!window.confirm(E.join(`
28
28
 
29
- `)))return}const W=(c==null?void 0:c[I.id])??h[I.id];try{const E=await k(I.invokeScript),$=wr(E);if($&&!$.ok||jr(E))throw new Error(($==null?void 0:$.error)||Os(E)||`Could not run ${I.label}`);$&&w(I,W??!0,$)}catch(E){K(I,W);const $=E instanceof Error?E.message:`Could not run ${I.label}`;rt.showToast($,"warning")}};return s.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${f}33`,background:`${f}12`,color:f},children:a}),R.map(I=>{const W=String(j[I.id]||""),E=Ef(I,x,W),$=v===I.id,F=g===I.id,J=Er(I,x),he="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(I.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${he} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:$?`${f}55`:"var(--border-default)",background:$?`${f}10`:"var(--surface-tertiary)",color:W?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void S(I),title:I.label,children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:F?"Loading…":E||I.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),$&&J.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>A(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:I.label}),J.map(le=>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:le.value===W?`${f}14`:"transparent",color:le.value===W?"var(--text-primary)":"var(--text-secondary)",borderLeft:le.value===W?`2px solid ${f}`:"2px solid transparent"},title:le.description||le.label,onMouseEnter:te=>{te.currentTarget.style.background=`${f}10`},onMouseLeave:te=>{te.currentTarget.style.background=le.value===W?`${f}14`:"transparent"},onClick:()=>void O(I,le.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:le.label}),le.value===W&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:f},children:"✓"})]},le.value))]})]})]},I.id);case"cycle":return s.jsxs("button",{type:"button",className:`${he} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:W?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void U(I),title:`Click to cycle: ${J.map(le=>le.label).join(" → ")}`,children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:E||I.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},I.id);case"toggle":return s.jsxs("button",{type:"button",className:`${he} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:W?`${f}44`:"var(--border-default)",background:W?`${f}14`:"var(--surface-tertiary)",color:W?f:"var(--text-muted)"},onClick:()=>void P(I),"aria-pressed":!!W,children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),I.label]},I.id);case"action":return s.jsxs("button",{type:"button",className:`${he} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void C(I),children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:I.resultDisplay==="inline"&&W?`${I.label}: ${W}`:I.label})]},I.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:W?"var(--text-primary)":"var(--text-muted)"},children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:W?`${I.label}: ${W}`:I.label})]},I.id);default:return null}})]})})}function Kf({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:c,controls:l,controlValues:d}){const{isVisible:f}=Oa(),u=Ha(l,{hostIdeType:a,providerType:o});return!e||t||u.length===0||!f?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(Bf,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:c,controls:u,controlValues:d})})}function Of({hasDraft:e,isBusy:t=!1}){return!e||t}const hc=i.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:o=null,onSend:c,isActive:l=!0,showControlsToggle:d=!1,animateVisibility:f=!0,onControlsToggle:u}){const p=i.useRef(null),[m,y]=i.useState(""),{isVisible:N,toggleVisibility:h}=Oa();i.useEffect(()=>{y("")},[t]),i.useEffect(()=>{var x;l&&((x=p.current)==null||x.focus({preventScroll:!0}))},[t,l]);const j=async()=>{const x=m.trim();if(!x||a)return;await c(x)!==!1&&y("")};return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",f?"transition-all duration-200 ease-out":""].filter(Boolean).join(" "),style:{borderTop:l?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:l?72:0,opacity:l?1:0,transform:l?"translateY(0)":"translateY(10px)",padding:l?"10px 12px":"0 12px",pointerEvents:l?"auto":"none"},"aria-hidden":!l,children:[s.jsxs("div",{className:"flex gap-2 items-center",title:l?`Send message to ${r}`:void 0,children:[d&&s.jsx("button",{type:"button",onClick:()=>{h(),u==null||u()},"aria-label":N?"Hide controls":"Show controls","aria-pressed":N,title:N?"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"})]})}),s.jsx("div",{className:"flex-1 relative",children:s.jsx("input",{ref:p,type:"text",placeholder:o||`Send message to ${r}...`,value:m,onChange:x=>y(x.target.value),onPaste:x=>{const b=x.clipboardData.getData("text");b&&y(v=>v+b),x.preventDefault()},onKeyDown:x=>{if(x.key==="Enter"){if(x.nativeEvent.isComposing){x.preventDefault();return}x.preventDefault(),j()}},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:()=>{j()},disabled:Of({hasDraft:!!m.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${m.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:m.trim()&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,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:m.trim()?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),o&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:o})]})}),et=e=>e.transport==="pty",Es=(e,t)=>et(e)?e.mode||"terminal":"chat",xc=(e,t)=>et(e)&&Es(e)==="terminal",Xe=e=>e.transport==="acp",Wf=180;function qt(e){return e.streamSource!=="agent-stream"}function xs(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function bc(e){return e.machineName||""}function $s(e){return xs(e)}function Bt(e){return e.agentType||""}function Jr(e){return e.hostIdeType||""}function Ua(e){return e.displayPrimary||e.agentName||"Agent"}function gc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function Ff(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function yc(e){const t=Ff(e),r=Kt(t==null?void 0:t.content),n=Kt(e.lastMessagePreview);return r||n||""}function Hf(e,t=Wf){const r=Kt(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 Uf(e){return Hf(yc(e)||e.displaySecondary||"")}function vc(e){return[e.displaySecondary,bc(e)].filter(Boolean)}function Ts(e){return e.agentName||at(Bt(e))}function zf(e){var t,r;if(!qt(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return at(Jr(e)||Bt(e))}function wc(e){return qt(e)?e.sessionId:e.nativeSessionId}function Ko(e){return qt(e)?"native":e.tabKey}function Vf(e){return e.sessionId}function Gf(e,t){if(t)return qt(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function qf(e,t){const r=Bt(e),n=qt(e),a=et(e)||Xe(e),o=n?a?Ts(e)||(t==null?void 0:t.cliName)||at(Jr(e)||r):t!=null&&t.type?at(t.type):at(Jr(e)||r):Ts(e);return{isNativeConversation:n,isCli:et(e),isAcp:Xe(e),isCliTerminal:xc(e),providerType:r,displayLabel:o,targetEntry:Gf(e,t)}}function ts(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:et(e)||Xe(e)?{agentType:Bt(e)}:e.streamSource==="agent-stream"?{agentType:Bt(e)}:t}function Ms(e){return e?$s(e):""}function Ws(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function za(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function Yf(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 jc(){return"select_session"}function Xf(){return"open_panel"}function Jf({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function Qf(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function Oo(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Qr(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Va(e){return e instanceof Error?e.message:String(e||"")}function Wo(e){const t=Va(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Fo(e,t){const r=Va(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function mn({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,o]=i.useState(!1),[c,l]=i.useState(!1),[d,f]=i.useState(null),u=i.useRef(!1),p=i.useRef(null);i.useEffect(()=>{f(null)},[t==null?void 0:t.tabKey]);const m=i.useCallback(async j=>{if(!t)return!1;const x=j.trim(),b=za(t);if(Jf({hasMessage:!!x,blockedMessage:b,sendInFlight:u.current}))return b&&f(b),!1;const v=Date.now(),A={tabKey:t.tabKey,message:x,timestamp:v};if(Qf(p.current,A))return f(null),!0;u.current=!0,l(!0),f(null),p.current=A;try{const g=Ms(t);if(!g)return p.current=Oo(p.current,A),f("Unable to send message right now."),!1;const M=await e(g,"send_chat",{message:x,...ts(t)}),T=Qr(M);if(T!=null&&T.deduplicated)return f(null),!0;if((T==null?void 0:T.sent)===!1)throw new Error((T==null?void 0:T.error)||"Send failed");if((T==null?void 0:T.success)===!1)throw new Error((T==null?void 0:T.error)||"Send failed");return f(null),!0}catch(g){const M=Va(g);return M.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",M):console.warn("Send blocked/failed",g),p.current=Oo(p.current,A),f(Yf(g)),!1}finally{u.current=!1,l(!1)}},[t,e]),y=i.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(j){console.error("Relaunch failed",j)}},[t,e]),N=i.useCallback(async j=>{if(t)try{const b=(t.modalButtons||[]).indexOf(j),v=j.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),A=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(v),g=Ms(t);if(!g)return;const M=await e(g,"resolve_action",{button:j,action:A?"approve":"reject",...b>=0&&{buttonIndex:b},...ts(t)}),T=Qr(M);T.success||r(k=>[...k,{routeId:t.tabKey,text:Fo(j,T==null?void 0:T.error),timestamp:Date.now()}])}catch(x){Wo(x)||console.error("[ModalButton] Error:",x),r(b=>[...b,{routeId:t.tabKey,text:Wo(x)?Fo(j,x):`❌ **${j}** error`,timestamp:Date.now()}])}},[t,e,r]),h=i.useCallback(async()=>{if(!(!t||a)){o(!0);try{await e(t.routeId,Xf(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(j){console.error("Focus agent failed",j)}finally{o(!1)}}},[t,a,e]);return{isSendingChat:c,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:m,handleRelaunch:y,handleModalButton:N,handleFocusAgent:h}}const Zf=10,em=8e3,tm=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function sm(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 pa(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(tm.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=sm(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=>pa(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,pa(a,n,r+1)]))}function kr(e,t){return Array.isArray(e)?e.slice(-t):[]}function rm(e,t=Date.now()){const r=e&&t-e.firstAt<=em,n=r?e.count+1:1;return n>=Zf?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function kc(e){var n;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:t.messages.length,visible:e.visibleMessages.length,history:((n=e.chatTailState.historyMessages)==null?void 0:n.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:kr(t.messages,10),visibleMessagesTail:kr(e.visibleMessages,5),historyMessagesTail:kr(e.chatTailState.historyMessages,5),actionLogsTail:kr(e.actionLogs.filter(a=>a.routeId===t.tabKey),20),controls:{visibleBarControlCount:e.visibleBarControlCount,definitions:e.controls||[],values:e.controlValues||{},visible:e.ui.controlsVisible},chatTail:{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 pa(r)}function Sc(e,t={}){const r=e&&typeof e=="object"?e:{},n=t.locatorCopied===!1?"locator copy failed":"locator copied";return r.delivery==="daemon_file"?`Chat debug signal sent${typeof r.bundleId=="string"&&r.bundleId.trim()?` (${r.bundleId})`:""}; saved on daemon, ${n}.`:`Chat debug signal sent; ${n}.`}function Nc(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(`
29
+ `)))return}const W=(c==null?void 0:c[I.id])??h[I.id];try{const E=await k(I.invokeScript),$=wr(E);if($&&!$.ok||jr(E))throw new Error(($==null?void 0:$.error)||Os(E)||`Could not run ${I.label}`);$&&w(I,W??!0,$)}catch(E){K(I,W);const $=E instanceof Error?E.message:`Could not run ${I.label}`;rt.showToast($,"warning")}};return s.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${f}33`,background:`${f}12`,color:f},children:a}),R.map(I=>{const W=String(j[I.id]||""),E=$f(I,x,W),$=v===I.id,z=g===I.id,J=Er(I,x),he="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(I.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${he} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:$?`${f}55`:"var(--border-default)",background:$?`${f}10`:"var(--surface-tertiary)",color:W?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void S(I),title:I.label,children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:z?"Loading…":E||I.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),$&&J.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>A(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:I.label}),J.map(ce=>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:ce.value===W?`${f}14`:"transparent",color:ce.value===W?"var(--text-primary)":"var(--text-secondary)",borderLeft:ce.value===W?`2px solid ${f}`:"2px solid transparent"},title:ce.description||ce.label,onMouseEnter:te=>{te.currentTarget.style.background=`${f}10`},onMouseLeave:te=>{te.currentTarget.style.background=ce.value===W?`${f}14`:"transparent"},onClick:()=>void O(I,ce.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:ce.label}),ce.value===W&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:f},children:"✓"})]},ce.value))]})]})]},I.id);case"cycle":return s.jsxs("button",{type:"button",className:`${he} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:W?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void H(I),title:`Click to cycle: ${J.map(ce=>ce.label).join(" → ")}`,children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:E||I.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},I.id);case"toggle":return s.jsxs("button",{type:"button",className:`${he} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:W?`${f}44`:"var(--border-default)",background:W?`${f}14`:"var(--surface-tertiary)",color:W?f:"var(--text-muted)"},onClick:()=>void P(I),"aria-pressed":!!W,children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),I.label]},I.id);case"action":return s.jsxs("button",{type:"button",className:`${he} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void C(I),children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:I.resultDisplay==="inline"&&W?`${I.label}: ${W}`:I.label})]},I.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:W?"var(--text-primary)":"var(--text-muted)"},children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:W?`${I.label}: ${W}`:I.label})]},I.id);default:return null}})]})})}function Of({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:c,controls:l,controlValues:d}){const{isVisible:f}=Oa(),u=Ha(l,{hostIdeType:a,providerType:o});return!e||t||u.length===0||!f?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(Kf,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:c,controls:u,controlValues:d})})}function Wf({hasDraft:e,isBusy:t=!1}){return!e||t}const hc=i.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:o=null,onSend:c,isActive:l=!0,showControlsToggle:d=!1,animateVisibility:f=!0,onControlsToggle:u}){const p=i.useRef(null),[m,y]=i.useState(""),{isVisible:N,toggleVisibility:h}=Oa();i.useEffect(()=>{y("")},[t]),i.useEffect(()=>{var x;l&&((x=p.current)==null||x.focus({preventScroll:!0}))},[t,l]);const j=async()=>{const x=m.trim();if(!x||a)return;await c(x)!==!1&&y("")};return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",f?"transition-all duration-200 ease-out":""].filter(Boolean).join(" "),style:{borderTop:l?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:l?72:0,opacity:l?1:0,transform:l?"translateY(0)":"translateY(10px)",padding:l?"10px 12px":"0 12px",pointerEvents:l?"auto":"none"},"aria-hidden":!l,children:[s.jsxs("div",{className:"flex gap-2 items-center",title:l?`Send message to ${r}`:void 0,children:[d&&s.jsx("button",{type:"button",onClick:()=>{h(),u==null||u()},"aria-label":N?"Hide controls":"Show controls","aria-pressed":N,title:N?"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"})]})}),s.jsx("div",{className:"flex-1 relative",children:s.jsx("input",{ref:p,type:"text",placeholder:o||`Send message to ${r}...`,value:m,onChange:x=>y(x.target.value),onPaste:x=>{const b=x.clipboardData.getData("text");b&&y(v=>v+b),x.preventDefault()},onKeyDown:x=>{if(x.key==="Enter"){if(x.nativeEvent.isComposing){x.preventDefault();return}x.preventDefault(),j()}},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:()=>{j()},disabled:Wf({hasDraft:!!m.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${m.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:m.trim()&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,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:m.trim()?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),o&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:o})]})}),et=e=>e.transport==="pty",Es=(e,t)=>et(e)?e.mode||"terminal":"chat",xc=(e,t)=>et(e)&&Es(e)==="terminal",Xe=e=>e.transport==="acp",Ff=180;function qt(e){return e.streamSource!=="agent-stream"}function xs(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function bc(e){return e.machineName||""}function $s(e){return xs(e)}function Bt(e){return e.agentType||""}function Jr(e){return e.hostIdeType||""}function Ua(e){return e.displayPrimary||e.agentName||"Agent"}function gc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function Hf(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function yc(e){const t=Hf(e),r=Kt(t==null?void 0:t.content),n=Kt(e.lastMessagePreview);return r||n||""}function Uf(e,t=Ff){const r=Kt(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 zf(e){return Uf(yc(e)||e.displaySecondary||"")}function vc(e){return[e.displaySecondary,bc(e)].filter(Boolean)}function Ts(e){return e.agentName||at(Bt(e))}function Vf(e){var t,r;if(!qt(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return at(Jr(e)||Bt(e))}function wc(e){return qt(e)?e.sessionId:e.nativeSessionId}function Ko(e){return qt(e)?"native":e.tabKey}function Gf(e){return e.sessionId}function qf(e,t){if(t)return qt(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function Yf(e,t){const r=Bt(e),n=qt(e),a=et(e)||Xe(e),o=n?a?Ts(e)||(t==null?void 0:t.cliName)||at(Jr(e)||r):t!=null&&t.type?at(t.type):at(Jr(e)||r):Ts(e);return{isNativeConversation:n,isCli:et(e),isAcp:Xe(e),isCliTerminal:xc(e),providerType:r,displayLabel:o,targetEntry:qf(e,t)}}function ts(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:et(e)||Xe(e)?{agentType:Bt(e)}:e.streamSource==="agent-stream"?{agentType:Bt(e)}:t}function Ms(e){return e?$s(e):""}function Ws(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function za(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function Xf(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 jc(){return"select_session"}function Jf(){return"open_panel"}function Qf({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function Zf(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function Oo(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Qr(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Va(e){return e instanceof Error?e.message:String(e||"")}function Wo(e){const t=Va(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Fo(e,t){const r=Va(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function mn({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,o]=i.useState(!1),[c,l]=i.useState(!1),[d,f]=i.useState(null),u=i.useRef(!1),p=i.useRef(null);i.useEffect(()=>{f(null)},[t==null?void 0:t.tabKey]);const m=i.useCallback(async j=>{if(!t)return!1;const x=j.trim(),b=za(t);if(Qf({hasMessage:!!x,blockedMessage:b,sendInFlight:u.current}))return b&&f(b),!1;const v=Date.now(),A={tabKey:t.tabKey,message:x,timestamp:v};if(Zf(p.current,A))return f(null),!0;u.current=!0,l(!0),f(null),p.current=A;try{const g=Ms(t);if(!g)return p.current=Oo(p.current,A),f("Unable to send message right now."),!1;const M=await e(g,"send_chat",{message:x,...ts(t)}),T=Qr(M);if(T!=null&&T.deduplicated)return f(null),!0;if((T==null?void 0:T.sent)===!1)throw new Error((T==null?void 0:T.error)||"Send failed");if((T==null?void 0:T.success)===!1)throw new Error((T==null?void 0:T.error)||"Send failed");return f(null),!0}catch(g){const M=Va(g);return M.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",M):console.warn("Send blocked/failed",g),p.current=Oo(p.current,A),f(Xf(g)),!1}finally{u.current=!1,l(!1)}},[t,e]),y=i.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(j){console.error("Relaunch failed",j)}},[t,e]),N=i.useCallback(async j=>{if(t)try{const b=(t.modalButtons||[]).indexOf(j),v=j.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),A=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(v),g=Ms(t);if(!g)return;const M=await e(g,"resolve_action",{button:j,action:A?"approve":"reject",...b>=0&&{buttonIndex:b},...ts(t)}),T=Qr(M);T.success||r(k=>[...k,{routeId:t.tabKey,text:Fo(j,T==null?void 0:T.error),timestamp:Date.now()}])}catch(x){Wo(x)||console.error("[ModalButton] Error:",x),r(b=>[...b,{routeId:t.tabKey,text:Wo(x)?Fo(j,x):`❌ **${j}** error`,timestamp:Date.now()}])}},[t,e,r]),h=i.useCallback(async()=>{if(!(!t||a)){o(!0);try{await e(t.routeId,Jf(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(j){console.error("Focus agent failed",j)}finally{o(!1)}}},[t,a,e]);return{isSendingChat:c,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:m,handleRelaunch:y,handleModalButton:N,handleFocusAgent:h}}const em=10,tm=8e3,sm=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function rm(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 pa(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(sm.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=rm(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=>pa(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,pa(a,n,r+1)]))}function kr(e,t){return Array.isArray(e)?e.slice(-t):[]}function nm(e,t=Date.now()){const r=e&&t-e.firstAt<=tm,n=r?e.count+1:1;return n>=em?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function kc(e){var n;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:t.messages.length,visible:e.visibleMessages.length,history:((n=e.chatTailState.historyMessages)==null?void 0:n.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:kr(t.messages,10),visibleMessagesTail:kr(e.visibleMessages,5),historyMessagesTail:kr(e.chatTailState.historyMessages,5),actionLogsTail:kr(e.actionLogs.filter(a=>a.routeId===t.tabKey),20),controls:{visibleBarControlCount:e.visibleBarControlCount,definitions:e.controls||[],values:e.controlValues||{},visible:e.ui.controlsVisible},chatTail:{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 pa(r)}function Sc(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 Nc(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 Cc(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(`
30
30
  `)}return typeof t.text=="string"?t.text:t.bundle&&typeof t.bundle=="object"?`# ADHDev Chat Debug Bundle
31
31
 
32
32
  \`\`\`json
@@ -35,9 +35,9 @@ ${JSON.stringify(t.bundle,null,2)}
35
35
 
36
36
  \`\`\`json
37
37
  ${JSON.stringify(t,null,2)}
38
- \`\`\``}function vt(e){return(typeof e=="string"?e.trim():"")||void 0}function Ft(e,t){const r=vt(t);return r?`${e}:${r}`:void 0}function Gt(e,t,r){const n=Ft(t,r),a=vt(r);n&&e.push(n),a&&e.push(a)}function ws(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function Cc(e){return vt(e.providerSessionId)||vt(e.sessionId)||vt(e.tabKey)||vt(e.routeId)}function Ga(e){return ws([vt(e.providerSessionId),vt(e.sessionId)])}function Ss(e){const t=[];return Gt(t,"provider",e.providerSessionId),Gt(t,"session",e.sessionId),Gt(t,"tab",e.tabKey),Gt(t,"route",e.routeId),ws(t)}function nm(e){const t=[];return vt(e.providerSessionId)?(Gt(t,"provider",e.providerSessionId),ws(t)):vt(e.sessionId)?(Gt(t,"session",e.sessionId),ws(t)):vt(e.tabKey)?(Gt(t,"tab",e.tabKey),ws(t)):vt(e.routeId)?(Gt(t,"route",e.routeId),ws(t)):[]}function qa(e){return Ft("provider",e.providerSessionId)||Ft("session",e.sessionId)||Ft("tab",e.tabKey)||Ft("route",e.routeId)||"unknown:"}function ur(e){return Ga(e)[0]}function am(e){const t=vt(e.providerSessionId),r=vt(e.sessionId),n=vt(e.tabKey),a=vt(e.routeId),o=[Ft("provider",t),Ft("session",r),Ft("tab",n),Ft("route",a)].filter(d=>typeof d=="string"),c=Ss({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),l=qa({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:Cc({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:ur({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:c}}function ha(e,t){const r=am(e);return nm(t).some(n=>r.lookupKeys.includes(n))}function Ho(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 ss(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=Ho(t==null?void 0:t.receivedAt)||Ho(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function xa(e,t=0){return ss(e)||e.lastUpdated||t||0}function Tc(e){return ss(e)||e.lastUpdated||0}function Mc(e,t,r=Tc){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 c=e.displaySecondary.localeCompare(t.displaySecondary);return c!==0?c:e.tabKey.localeCompare(t.tabKey)}function ba(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 om(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!ba(e)&&!e.title.trim()}function im(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(ba(r))-Number(ba(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:Mc(t,r)})[0]||null}function Pt(e,t){const r=e.filter(c=>c.routeId===t);if(r.length===0)return null;const n=r.find(c=>c.streamSource==="native")||null,a=r.filter(c=>c.streamSource==="agent-stream"),o=im(a);return n?o&&om(n)?o:n:o||r[0]||null}function Yt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Ya(e){return ur(e)||e.tabKey||e.routeId||null}function Ac(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"";if(t)return t;const r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"";if(r)return r;const n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"";if(!n)return null;const a=Pt(e.conversations,n)||e.conversations.find(o=>o.routeId===n);return a?Ya(a):null}function Ic({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const o=Ps(),c=xs(e),l=bc(e),d=e.transport==="cdp-page"||e.transport==="cdp-webview",f=e.streamSource==="agent-stream"&&!!e.agentName,u=!f&&(e.transport==="pty"||e.transport==="acp"),p=Ts(e),m=zf(e),y=i.useCallback(()=>{if(n){n();return}c&&o("/dashboard",{state:{openMachineId:c}})},[c,o,n]),N=i.useCallback(()=>{if(r){r();return}const h=Ya(e);h&&o(Yt(h))},[e,o,r]);return s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:N,title:m,children:[s.jsx(Tt,{size:12}),s.jsx("span",{children:m})]}):s.jsxs("span",{className:"conversation-meta-chip",title:m,children:[s.jsx(Tt,{size:12}),s.jsx("span",{children:m})]})),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:p,children:[s.jsx(ar,{size:12}),s.jsx("span",{children:p})]}),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:p,children:[s.jsx(ar,{size:12}),s.jsx("span",{children:p})]}),l&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:y,title:l,children:[s.jsx(us,{size:12}),s.jsx("span",{children:l})]}):s.jsxs("span",{className:"conversation-meta-chip",title:l,children:[s.jsx(us,{size:12}),s.jsx("span",{children:l})]}))]})}function Tn(e,t){return`${e}:${t}`}function cm(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Fs(e,t){cm()&&console.debug(`[subscription-manager] ${e}`,t)}class lm{constructor(){Ye(this,"active",new Map);Ye(this,"retryTimers",new Map)}subscribe(t,r,n,a,o){var u;const c=Tn(n.topic,n.key),l=this.active.get(c);let d=!0;if(l)l.handlers.add(a),l.lastUpdate&&a(l.lastUpdate);else{const p={daemonId:r,request:n,handlers:new Set([a])};this.active.set(c,p),Fs("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(c,t,o.retryIntervalMs)}const f=()=>{var y;this.clearRetry(c);const p=this.active.get(c);if(!p||(p.handlers.delete(a),p.handlers.size>0))return;this.active.delete(c);const m={type:"unsubscribe",topic:n.topic,key:n.key};Fs("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(y=t.sendData)==null||y.call(t,r,m)};return f.initialSendAccepted=d,f}publish(t){const r=Tn(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,Ns.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),Ns.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=Tn(t,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(t){var r;Fs("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);Fs("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 l;this.retryTimers.delete(t);const o=this.active.get(t);if(!o)return;const c=((l=r.sendData)==null?void 0:l.call(r,o.daemonId,o.request))??!1;Fs("subscribe_retry",{id:t,accepted:c,topic:o.request.topic,key:o.request.key}),c||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 Ht=new lm;function dm(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});for(const o of n.childSessions||[]){if(!(o!=null&&o.id))continue;const c=r.get(o.id)||{};r.set(o.id,{...c,...o})}}return r}function um(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 Zr(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:o,timestamp:c}=t,l=c||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:f,childrenByParent:u}=um(d),p=dm(o,n),m=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,y=f.filter(j=>j.kind==="workspace"&&j.transport==="cdp-page"),N=f.filter(j=>j.kind==="agent"&&j.transport==="pty"),h=f.filter(j=>j.kind==="agent"&&j.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...m&&{machine:m,platform:m.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:y.some(j=>!!j.cdpConnected)});for(const j of y){const x=p.get(j.id),b=qs(j,x),v=(u.get(j.id)||[]).map(A=>qs(A,p.get(A.id)));r.push({id:`${n}:ide:${j.id}`,sessionId:j.id,providerSessionId:j.providerSessionId??(x==null?void 0:x.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,status:b.cdpConnected?"online":"detected",daemonId:n,instanceId:j.id,workspace:b.workspace,terminals:0,childSessions:v,agents:v.map(A=>({id:A.id,name:A.providerName||A.providerType,type:A.providerType,status:A.status})),activeChat:b.activeChat,chats:[],cdpConnected:b.cdpConnected,...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l})}for(const j of N){const x=p.get(j.id),b=qs(j,x);r.push({id:`${n}:cli:${j.id}`,sessionId:j.id,providerSessionId:j.providerSessionId??(x==null?void 0:x.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:n,instanceId:j.id,cliName:b.providerName||b.providerType,mode:b.mode||(x==null?void 0:x.mode)||"terminal",workspace:b.workspace||"",activeChat:b.activeChat,...b.resume!==void 0&&{resume:b.resume},...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l,_isCli:!0})}for(const j of h){const x=p.get(j.id),b=qs(j,x);r.push({id:`${n}:acp:${j.id}`,sessionId:j.id,providerSessionId:j.providerSessionId??(x==null?void 0:x.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:n,instanceId:j.id,cliName:b.providerName||b.providerType,mode:"chat",workspace:b.workspace||"",activeChat:b.activeChat,...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const fm=15e3,mm=15e3,pm=6e4,hm=1200,Uo=12,xm=8e3,bm=4e3,Mn=new Map,An=new Map,Sr=new Set,Qs=new Map;function gm(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 zo(e,t){const r=Qs.get(e);!r||r.size===0||(Qs.delete(e),r.forEach(n=>n(t)))}function ym(e,t){return new Promise(r=>{const n=Qs.get(e)||new Set;Qs.set(e,n);const a=c=>{clearTimeout(o),n.delete(a),n.size===0&&Qs.delete(e),r(c)},o=setTimeout(()=>a(!1),t);n.add(a)})}function fr(){const{sendCommand:e,sendData:t}=mt(),{injectEntries:r,getIdes:n}=rr();return i.useCallback(async(a,o)=>{if(!a)return;const c=(o==null?void 0:o.minFreshMs)??pm,l=An.get(a)||0;if(!(o!=null&&o.force)&&Sr.has(a)&&l>0||!(o!=null&&o.force)&&l>0&&Date.now()-l<c)return;const d=Mn.get(a);if(d)return d;const f=(async()=>{if(t&&!Sr.has(a)){const h=Ht.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},j=>{const x=n(),b=x.find(A=>A.id===a),v=Zr(j.status,{daemonId:a,existingDaemon:b,existingEntries:x,timestamp:j.timestamp});v.length>0&&r(v),An.set(a,Date.now()),zo(a,!0)});if(h.initialSendAccepted?Sr.add(a):Sr.delete(a),!(o!=null&&o.force)&&h.initialSendAccepted&&await ym(a,hm))return}const u=await e(a,"get_status_metadata"),p=gm(u);if(!p)return;const m=n(),y=m.find(h=>h.id===a),N=Zr(p,{daemonId:a,existingDaemon:y,existingEntries:m,timestamp:p.timestamp||Date.now()});N.length>0&&r(N,{authoritativeDaemonIds:[a]}),An.set(a,Date.now()),zo(a,!0)})().finally(()=>{Mn.delete(a)});return Mn.set(a,f),f},[n,r,e,t])}function ir(e){if(!e||typeof e!="object")return[];const t=String(e.role||"");return[typeof e.providerUnitKey=="string"&&e.providerUnitKey.trim()?`${t}:providerUnitKey:${e.providerUnitKey.trim()}`:"",typeof e.bubbleId=="string"&&e.bubbleId.trim()?`${t}:bubbleId:${e.bubbleId.trim()}`:"",typeof e.id=="string"&&e.id.trim()?`${t}:id:${e.id.trim()}`:"",typeof e._localId=="string"&&e._localId.trim()?`${t}:localId:${e._localId.trim()}`:""].filter(Boolean)}function zt(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}function vm(e,t){if(!e||!t)return!1;if(e===t||e.id&&t.id&&String(e.id)===String(t.id)||e._localId&&t._localId&&String(e._localId)===String(t._localId))return!0;const r=String(e.role||"").toLowerCase(),n=String(t.role||"").toLowerCase();if(r!==n)return!1;const a=Kt(e.content),o=Kt(t.content);if(!a||!o||!(a===o||ya(a,o)||ya(o,a)))return!1;const l=zt(e),d=zt(t);return l&&d?Math.abs(l-d)<=15e3:!!e._localId!=!!t._localId}function ga(e){return Kt(e==null?void 0:e.content)}function ya(e,t){if(!e||!t||e.length<=t.length)return!1;const r=Math.max(12,Math.min(80,Math.floor(e.length*.4)));return t.length<r?!1:e.startsWith(t)||e.includes(t)}function Vo(e){if(!e)return[];const t=[],r=l=>{l&&t.push(l)};e.id&&r(`id:${String(e.id)}`),e._localId&&r(`local:${String(e._localId)}`),e._turnKey&&r(`turn:${String(e._turnKey)}`);const n=String(e.role||"").toLowerCase(),a=ga(e),o=zt(e),c=o?Math.round(o/15e3):0;return n&&a&&(r(`content:${n}:${a}`),r(`preview:${n}:${a.slice(0,120)}:${c}`)),t}function wm(e,t,r=vm){const n=new Map,a=o=>{for(const c of Vo(o)){const l=n.get(c);l?l.push(o):n.set(c,[o])}};return t.forEach(a),e.filter(o=>{const c=ga(o),l=String((o==null?void 0:o.role)||"").toLowerCase(),d=zt(o),f=new Set;for(const p of Vo(o)){const m=n.get(p);m&&m.forEach(y=>f.add(y))}return!(f.size>0?Array.from(f):t).some(p=>{if(r(o,p))return!0;const m=String((p==null?void 0:p.role)||"").toLowerCase();if(!c||!l||l!==m)return!1;const y=ga(p);if(!ya(y,c)&&y!==c)return!1;const N=zt(p);return d&&N?Math.abs(d-N)<=15e3:!0})})}const jm=60,km=1e3;function Lc(e={}){return e.isCliLike?km:jm}function Sm(e={}){return Lc(e)}const mr=60,Nm=1e3,Xa=12e4,Cm=new Set(["generating","waiting_approval","starting","streaming","working"]),Go=new Map;function Ja(e,t){return`${e}::${t}`}function va(e=mr){return{liveMessages:[],cursor:Rc([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function $r(e){return Vi(e)}function Rc(e,t=mr){return{knownMessageCount:e.length,lastMessageSignature:$r(e[e.length-1]),tailLimit:t}}function Nr(e,t){const r=e[e.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function qo(e){let t=0;for(const r of e){const n=zt(r);n>t&&(t=n)}return t}function Tm(e,t){if(t.length===0)return!1;if(e.length===0)return!0;const r=qo(e),n=qo(t);return!(r>0&&n<=0||r>0&&n>0&&n<r||r>0&&n===r&&t.length<e.length)}function Mm(e,t){if(t.length===0)return e;const r=[...e],n=new Map,a=(o,c)=>{for(const l of ir(o))n.set(l,c)};r.forEach(a);for(const o of t){const l=ir(o).map(d=>n.get(d)).find(d=>d!==void 0);if(l!==void 0){r[l]=o,a(o,l);continue}r.push(o),a(o,r.length-1)}return r}function Am(e,t){const r=Array.isArray(t.messages)?t.messages:[];switch(t.syncMode){case"noop":return e;case"append":return Mm(e,r);case"replace_tail":{const n=Math.max(0,Math.min(Number(t.replaceFrom??e.length),e.length));return[...e.slice(0,n),...r]}case"full":return r;default:return r}}class Im{constructor(t){Ye(this,"manager");Ye(this,"sendData");Ye(this,"daemonId");Ye(this,"sessionId");Ye(this,"historySessionId");Ye(this,"subscriptionKey");Ye(this,"snapshot");Ye(this,"transportSubscription",null);Ye(this,"listeners",new Set);Ye(this,"retainCount",0);Ye(this,"loadHistoryPromise",null);Ye(this,"pendingDisconnectTimer",null);this.manager=t.manager||Ht,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.snapshot=va(Math.max(0,t.tailLimit??mr))}updateOptions(t){if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.tailLimit!==void 0){const r=Math.max(0,t.tailLimit);if(r!==this.snapshot.cursor.tailLimit){const n=r>this.snapshot.cursor.tailLimit,a=n?0:Math.min(this.snapshot.cursor.knownMessageCount,this.snapshot.liveMessages.length),o=n?"":this.snapshot.cursor.lastMessageSignature;this.snapshot={...this.snapshot,cursor:{knownMessageCount:a,lastMessageSignature:o,tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect())}}}getSnapshot(){return this.snapshot}hydrateLiveMessages(t){const r=Array.isArray(t)?t:[];if(!Tm(this.snapshot.liveMessages,r))return;const n=r,a=Rc(n,this.snapshot.cursor.tailLimit);Nr(this.snapshot.liveMessages)===Nr(n)&&this.snapshot.cursor.knownMessageCount===a.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===a.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:n,cursor:a},this.emit())}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=await t({offset:this.snapshot.historyOffset,excludeRecentCount:this.snapshot.liveMessages.length}),a=Array.isArray(n.messages)?n.messages:[],o=wm(a,this.snapshot.liveMessages);this.snapshot={...this.snapshot,historyMessages:[...o,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+a.length,hasMoreHistory:n.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}:{},knownMessageCount:this.snapshot.cursor.knownMessageCount,lastMessageSignature:this.snapshot.cursor.lastMessageSignature,...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:Nm}))}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=typeof t.lastMessageSignature=="string"?t.lastMessageSignature:"",n=$r(this.snapshot.liveMessages[this.snapshot.liveMessages.length-1]),a=Array.isArray(t.messages)?t.messages:[];if(t.syncMode!=="full"&&r&&n===r&&a.length===0){const m={knownMessageCount:Math.max(this.snapshot.cursor.knownMessageCount,Number(t.totalMessages||0)),lastMessageSignature:r,tailLimit:this.snapshot.cursor.tailLimit};this.snapshot.cursor.knownMessageCount===m.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===m.lastMessageSignature||(this.snapshot={...this.snapshot,cursor:m},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:m.knownMessageCount,lastMessageSignature:m.lastMessageSignature}));return}const o=Am(this.snapshot.liveMessages,t),c=r||$r(o[o.length-1]),l=!!r&&$r(o[o.length-1])===r,f={knownMessageCount:t.syncMode!=="full"&&l&&Number(t.totalMessages||0)>o.length?Math.max(o.length,Number(t.totalMessages||0)):o.length,lastMessageSignature:c,tailLimit:this.snapshot.cursor.tailLimit};Nr(this.snapshot.liveMessages)===Nr(o)&&this.snapshot.cursor.knownMessageCount===f.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===f.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:o,cursor:f},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:f.knownMessageCount,lastMessageSignature:f.lastMessageSignature}),this.emit())}}function _c(e){const t=Ja(e.daemonId,e.sessionId),r=Go.get(t);if(r)return r.updateOptions(e),r;const n=new Im(e);return Go.set(t,n),n}function Lm(e,t){return{...e,loadHistoryPage:t}}function Rm(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function _m(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Cm.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??Xa)),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 Pm(e=Xa){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Dm(e,t={}){const r=new Set,n=[];for(const a of e){if(!_m(a,t))continue;const o=$s(a),c=a.sessionId||"";if(!o||!c)continue;const l=Ja(o,c);if(r.has(l))continue;r.add(l);const d=ur(a);n.push({daemonId:o,sessionId:c,historySessionId:d||c,subscriptionKey:`daemon:${o}:session:${c}`})}return n.sort(Rm),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Em(e,t){const{sendData:r,sendCommand:n}=mt(),a=(t==null?void 0:t.enabled)!==!1,o=$s(e),c=e.sessionId||"",l=ur(e)||c,d=`daemon:${o}:session:${c}`,f=Math.max(0,(t==null?void 0:t.tailLimit)??mr),u=i.useMemo(()=>!a||!o||!c?null:_c({daemonId:o,sessionId:c,historySessionId:l,subscriptionKey:d,sendData:r,tailLimit:f}),[o,a,l,r,c,d,f]),[p,m]=i.useState(()=>(u==null?void 0:u.getSnapshot())||va(f));i.useEffect(()=>{if(!u){m(va(f));return}u.retain(),m(u.getSnapshot());const N=u.subscribe(h=>{m(h)});return()=>{N(),u.release()}},[u,f]),i.useEffect(()=>{u&&(u.hydrateLiveMessages(e.messages),m(u.getSnapshot()))},[e.messages,u]);const y=i.useCallback(async()=>{!u||!o||!c||await u.loadHistoryPage(async({offset:N,excludeRecentCount:h})=>{const j=e.agentType,x=await n(o,"chat_history",{agentType:j,offset:N,limit:30,targetSessionId:c,historySessionId:l,excludeRecentCount:h}),b=x&&typeof x=="object"&&"result"in x?x.result||{}:x||{};return{messages:Array.isArray(b.messages)?b.messages:[],hasMore:b.hasMore===!0}})},[e.agentType,u,o,l,n,c]);return i.useMemo(()=>Lm(p,y),[y,p])}function $m(e,t){const{sendData:r}=mt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??mr),o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Xa)),c=Pm(o),[l,d]=i.useState(0),[f,u]=i.useState(()=>new Map);i.useEffect(()=>{if(!n||e.length===0)return;const m=setInterval(()=>{d(y=>y+1)},c);return()=>{clearInterval(m)}},[e.length,n,c]);const p=i.useMemo(()=>Dm(e,{recentActivityMs:o}),[e,o,l]);return i.useEffect(()=>{if(!n||!r||p.descriptors.length===0){u(j=>j.size===0?j:new Map);return}const m=p.descriptors.map(j=>({key:Ja(j.daemonId,j.sessionId),controller:_c({...j,sendData:r,tailLimit:a})})),y=new Set(m.map(({key:j})=>j)),N=(j,x)=>{u(b=>{const v=new Map(b);for(const A of v.keys())y.has(A)||v.delete(A);return v.set(j,x),v})},h=m.map(({key:j,controller:x})=>(x.retain(),N(j,x.getSnapshot()),x.subscribe(b=>N(j,b))));return()=>{h.forEach(j=>j()),m.forEach(({controller:j})=>j.release())}},[p.signature,n,r,a]),f}function Yo(e,t){const r=e[e.length-1];if(!r)return`empty:${t||""}`;let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return[t||"",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function en(e){for(let t=e.length-1;t>=0;t-=1){const r=zt(e[t]);if(r>0)return r}return 0}function Bm(e){const t=$s(e),r=e.sessionId||"";return t&&r?`${t}::${r}`:""}function Km(e){const t=new Set;for(const r of e)for(const n of ir(r)){if(t.has(n))return!0;t.add(n)}return!1}function Om(e,t){const r=new Set(ir(e));return r.size===0?!1:ir(t).some(n=>r.has(n))}function Pc(e,t){return t.length===0||e.length<=t.length||!Km(e)?!1:Om(e[e.length-1],t[t.length-1])}function Wm(e,t){if(t.length===0)return!1;const r=Array.isArray(e.messages)?e.messages:[];if(r.length===0)return!0;const n=en(r),a=en(t);if(n>0&&a===n&&Pc(r,t))return!0;if(n<=0||a<=n)return!1;const o=Yo(r,e.status),c=Yo(t,e.status);return o!==c}function Fm(e,t){const r=t[t.length-1],n=zt(r),a=Kt(r==null?void 0:r.content);return{...e,messages:t,...a?{lastMessagePreview:a}:{},...n>0?{lastMessageAt:n}:{}}}function Hm(e,t){const r=Array.isArray(e.messages)?e.messages:[],n=(t==null?void 0:t.liveMessages)||[];if(n.length===0)return r;if(r.length===0)return n;const a=en(r),o=en(n);if(a>0&&(o<=0||a>o))return r;if(a>0&&a===o){if(Pc(r,n))return n;if(r.length>=n.length)return r}return n}function Um(e){const{historyMessages:t,liveMessages:r,visibleLiveCount:n}=e,o=Math.max(0,r.length-n)>0?r.slice(-n):r;return t.length===0?o:[...t,...o]}function Xo(e,t){if(t.size===0||e.length===0)return e;let r=!1;const n=e.map(a=>{var l;const o=Bm(a);if(!o)return a;const c=((l=t.get(o))==null?void 0:l.liveMessages)||[];return Wm(a,c)?(r=!0,Fm(a,c)):a});return r?n:e}function zm(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Vm(e){return zm(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}function Gm(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function qm(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function Ym(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Dc(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function Ec(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 Xm(e){return Dc(e)?!1:e.inboxBucket==="task_complete"&&Ec(e).length>0}function Jo(e){return e.branch||"detached HEAD"}function Jm(e){if(e.error)return`${Jo(e)} · Git error: ${e.error}`;const t=[Jo(e)];return e.changedFiles>0?t.push(Gm(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 Qm(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${Jm(t)}`}function Zm(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function ep(e,t={}){if(t.enabled===!1)return[];if(!Ym(e))return[];const r=Dc(e)?"working":Xm(e)?"complete":null;if(!r)return[];const n=r==="complete"?Ec(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${qm(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:Qm(r,e.git),timestamp:Zm(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 tp=60;function wa({activeConv:e,ideEntry:t,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:o,isFocusingAgent:c,actionLogs:l,userName:d,showMetaChips:f=!1,scrollToBottomRequestNonce:u,isInputActive:p=!0,isVisible:m=!0}){var ge,ee,de,we,ue,xe,se;const y=i.useRef(new Map),N=i.useRef(void 0),h=fr(),{sendCommand:j}=mt(),{isVisible:x}=Oa();dr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const b=kt.useMemo(()=>Ds(e),[e.status,e.connectionState]),v=i.useMemo(()=>qf(e,t),[e,t]),A=i.useMemo(()=>{var ie;return Ha((ie=v.targetEntry)==null?void 0:ie.providerControls,{hostIdeType:e.hostIdeType,providerType:v.providerType})},[e.hostIdeType,v.providerType,(ge=v.targetEntry)==null?void 0:ge.providerControls]),g=Lc({isCliLike:v.isCli||v.isAcp}),M=Sm({isCliLike:v.isCli||v.isAcp}),T=Em(e,{enabled:m&&!!e.sessionId,tailLimit:M}),[k,w]=i.useState(g),K=e.tabKey,R=T.historyMessages,S=T.hasMoreHistory,O=T.historyError,U=Hm(e,T);i.useEffect(()=>{w(g)},[g,K]);const P=Math.max(0,U.length-k),C=Ua(e),I=$s(e),W=Vm(e),E=za(e),$=a||E,F=!!E,[J,he]=i.useState(!1);i.useEffect(()=>{const ie=v.targetEntry;I&&(!ie||ie.providerControls===void 0||ie.controlValues===void 0)&&h(I,{minFreshMs:3e4}).catch(()=>{})},[I,v.isAcp,(ee=v.targetEntry)==null?void 0:ee.providerControls,(de=v.targetEntry)==null?void 0:de.controlValues,h]);const le=i.useCallback(async()=>{if(!J){if(U.length>k){w(ie=>Math.min(U.length,ie+tp));return}he(!0);try{await T.loadHistoryPage()}finally{he(!1)}}},[T,J,U.length,k]),{allMessages:te,receivedAtMap:ye}=i.useMemo(()=>{const ie=Um({historyMessages:R,liveMessages:U,visibleLiveCount:k}),re=ep(e),q=re.length>0?[...ie,...re]:ie,Y={};return q.forEach((ce,ke)=>{const Z=`${e.tabKey}:${qr(ce,ke)}`;let Se=zt(ce)||y.current.get(Z)||0;Se||(Se=Date.now(),y.current.set(Z,Se)),Y[qr(ce,ke)]=Se}),{allMessages:q,receivedAtMap:Y}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,P,R,U,k]),fe=i.useMemo(()=>l.filter(ie=>ie.routeId===e.tabKey).sort((ie,re)=>ie.timestamp-re.timestamp),[l,e.tabKey]),be=i.useCallback(async()=>{var ke,Z,Se;if(!I)return;const ie=kc({activeConv:e,visibleMessages:te,actionLogs:l,controls:(ke=v.targetEntry)==null?void 0:ke.providerControls,controlValues:(Z=v.targetEntry)==null?void 0:Z.controlValues,visibleBarControlCount:A.length,chatTailState:{hasMoreHistory:S,historyError:O,historyMessages:R},ui:{controlsVisible:x,visibleLiveCount:k,hiddenLiveCount:P,isInputActive:p,isVisible:m}}),re=await j(I,"get_chat_debug_bundle",{agentType:v.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:ie}),q=Qr(re),Y=Nc(q);let ce=!1;if((Se=navigator.clipboard)!=null&&Se.writeText&&window.isSecureContext)try{await navigator.clipboard.writeText(Y),ce=!0}catch(Me){console.warn("[chat-debug-bundle] clipboard API failed, trying execCommand fallback",Me)}if(!ce){let Me=null;try{Me=document.createElement("textarea"),Me.value=Y,Me.setAttribute("readonly","true"),Me.style.cssText="position:fixed;left:-9999px;top:0",document.body.appendChild(Me),Me.focus(),Me.select(),ce=document.execCommand("copy")}catch{}finally{Me==null||Me.remove()}}ce||console.warn("[chat-debug-bundle] failed to copy debug bundle locator to clipboard"),rt.showToast(Sc(q,{locatorCopied:ce}),ce?"success":"warning")},[e,l,te,x,v.providerType,(we=v.targetEntry)==null?void 0:we.controlValues,(ue=v.targetEntry)==null?void 0:ue.providerControls,I,S,P,R,p,m,O,j,A.length,k]),X=i.useCallback(()=>{const ie=rm(N.current);N.current=ie.state,ie.shouldCollect&&be().catch(re=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",re),rt.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[be]),ae=i.useMemo(()=>{if(U.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((b.isGenerating||e.status==="streaming")&&he(!1),e.status==="not_monitored"&&W)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(ar,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),s.jsx("button",{onClick:o,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Cs,{size:14})," Open ",C," 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"&&W)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(Ji,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),s.jsx("button",{onClick:o,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Cs,{size:14})," Open ",C," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!J)return 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,W,o,c,J,U.length,C,b.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[f&&s.jsx(Ic,{conversation:e,className:"chat-pane-meta-row"}),s.jsx(Eu,{messages:te,actionLogs:fe,agentName:Ts(e)||C||"Agent",userName:d,isCliMode:v.isCli||v.isAcp,isWorking:b.isGenerating,contextKey:e.tabKey,receivedAtMap:ye,lastMessageHash:e.lastMessageHash,onLoadMore:le,isLoadingMore:J,hasMoreHistory:S,hiddenLiveCount:P,loadError:O??void 0,emptyState:ae,scrollToBottomRequestNonce:u,isVisible:m}),s.jsx(Kf,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:v.providerType,displayLabel:v.displayLabel,controls:(xe=v.targetEntry)==null?void 0:xe.providerControls,controlValues:(se=v.targetEntry)==null?void 0:se.controlValues,isActive:p,isCliTerminal:v.isCliTerminal}),!v.isCliTerminal&&s.jsx(hc,{contextKey:e.tabKey,panelLabel:C,isSending:n,isBusy:F,statusMessage:$,onSend:r,isActive:p,showControlsToggle:A.length>0,onControlsToggle:X})]})}let $c=ds;function Bc(){return $c()}class sp{constructor(){Ye(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 Kc=new sp;class rp{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 ot=new rp;function np(e){e.dashboardWS&&(Kc=e.dashboardWS),e.connectionManager&&(ot=e.connectionManager),e.useDaemonsHook&&($c=e.useDaemonsHook)}const ap=.5,op=1.25;function it(e){return Ua(e)}function As(e){return vc(e).join(" · ")}function Oc(e){const t=yc(e);return t||(e.title?e.title:As(e)||"No messages yet")}function Wc(e,t){const{isReconnecting:r,isConnecting:n}=Ds(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function ip(e,t){const r=["Chat",...vc(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function rs(e){return Wc(e)||As(e)}function cp(e){return`${it(e)} · ${Oc(e)}`}function lp(e){const t=Jr(e),r=t?at(t):Ts(e);return`${it(e)} — ${r||"Agent"}`}function dp(e){return Ts(e)||"CLI"}function Fc(e){return gc(e)}function Hc(e){return e?`Remote · ${it(e)||e.workspaceName||"Session"}`:"Remote"}function up({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:c=!0,isInputActive:l=!0}){var G;ds();const{sendPtyInput:d}=mt(),[f,u]=i.useState(!1),p=i.useRef(!1);p.current=f;const[m,y]=i.useState("Runtime terminal unavailable"),[N,h]=i.useState(!1),[j,x]=i.useState(null),[b,v]=i.useState(!1),[A,g]=i.useState(!1),[M,T]=i.useState(1),[k,w]=i.useState(!1),[K,R]=i.useState({width:0,height:0}),[S,O]=i.useState({width:0,height:0}),[U,P]=i.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[C,I]=i.useState(null),W=i.useRef(null),E=i.useRef(null),$=i.useRef(!1),F=i.useRef(!1),J=i.useRef(c),he=i.useRef(0),le=i.useRef(!1),te=i.useRef(""),ye=i.useRef(null),fe=i.useRef(!1),be=i.useRef(!1),X=i.useRef(null),ae=i.useRef(null),ge=i.useRef(null),ee=32*1024,de=()=>{var _,z,Q,ne;return((z=(_=W.current)==null?void 0:_.ownerDocument)==null?void 0:z.defaultView)||((ne=(Q=E.current)==null?void 0:Q.ownerDocument)==null?void 0:ne.defaultView)||window},we=_=>{const z=de();return{ownerWindow:z,frameId:z.requestAnimationFrame(_)}},ue=()=>{const _=X.current;if(_){try{_.ownerWindow.cancelAnimationFrame(_.frameId)}catch{}X.current=null}},xe=()=>{const _=ae.current;if(_){try{_.ownerWindow.clearTimeout(_.timeoutId)}catch{}ae.current=null}},se=()=>{const _=ge.current;if(_){try{_.ownerWindow.clearTimeout(_.timeoutId)}catch{}ge.current=null}},ie=()=>{c&&X.current===null&&(X.current=we(()=>{Qe()}))},re=e.tabKey,q=e.sessionId||"",Y=e.daemonId||((G=e.routeId)==null?void 0:G.split(":")[0])||e.routeId||"",ce=za(e),ke=f?o||ce:m,Z=ap,Se=op,Me=.05,We=()=>{const _=S.width,z=S.height;if(!Number.isFinite(K.width)||K.width<=0||!Number.isFinite(K.height)||K.height<=0||!Number.isFinite(_)||_<=0||!Number.isFinite(z)||z<=0)return 1;const Q=K.width/_,ne=K.height/z;return Number(Math.min(Se,Math.max(Z,Math.min(Q,ne))).toFixed(2))},Fe=We(),D=$.current&&M>Fe,Ne=Number.isFinite(S.width)&&S.width>0?Math.max(K.width,Math.round(S.width*M)):K.width,Ie=Number.isFinite(S.height)&&S.height>0?Math.max(K.height,Math.round(S.height*M)):K.height,Re=()=>{we(()=>{const _=E.current;_&&(_.scrollLeft=0,_.scrollTop=_.scrollHeight-_.clientHeight)})},De=()=>{var _,z;he.current=0,le.current=!1,te.current="",ye.current=null,fe.current=!1,be.current=!1,$.current||(F.current=!1,T(1)),X.current!==null&&ue(),u(!1),y("Runtime terminal unavailable"),se(),xe(),x(null),I(null),w(!1),h(!1),v(!1),g(!1),(z=(_=r.current)==null?void 0:_.reset)==null||z.call(_)},He=()=>{var _,z;he.current=0,le.current=!1,te.current="",ye.current=null,fe.current=!1,be.current=!1,X.current!==null&&ue(),u(!0),y(""),se(),xe(),x(null),I(null),w(!1),h(!1),v(!1),g(!1),(z=(_=r.current)==null?void 0:_.reset)==null||z.call(_)},Ue=()=>{be.current&&(be.current=!1,we(()=>{var _,z;(z=(_=r.current)==null?void 0:_.scrollToTop)==null||z.call(_)}))},Qe=()=>{if(X.current=null,!c)return;const _=te.current;if(!_)return;const z=_.slice(0,ee);te.current=_.slice(z.length);const Q=r.current;if(!Q){te.current=z+te.current,ie();return}Q.write(z,()=>{if(te.current.length>0){ie();return}Ue()})},lt=_=>{_&&(te.current+=_,ie())},dt=(_,z=0,Q,ne,ve={})=>{var Pe,Ce,Ee,Be;const Ae=!!ve.force;!Ae&&z>0&&he.current>=z||!Ae&&z===0&&le.current||(he.current=z,z>0&&v(!0),u(!0),y(""),typeof Q=="number"&&typeof ne=="number"&&Q>0&&ne>0&&((Ce=(Pe=r.current)==null?void 0:Pe.resize)==null||Ce.call(Pe,Q,ne)),te.current="",(Be=(Ee=r.current)==null?void 0:Ee.reset)==null||Be.call(Ee),_?lt(_):Ue())};i.useEffect(()=>{De()},[q]),i.useEffect(()=>{var z;if(!q)return;const _=((z=ot.onRuntimeEvent)==null?void 0:z.call(ot,q,Q=>{if(!(!Q||Q.sessionId!==q)){if(Q.type==="runtime_snapshot"){if(!c){ye.current={text:Q.text||"",seq:Q.seq||0,cols:Q.cols,rows:Q.rows,force:!!Q.force};return}dt(Q.text||"",Q.seq||0,Q.cols,Q.rows,{force:!!Q.force});return}if(Q.type==="session_output"){le.current=!0,typeof Q.seq=="number"&&(he.current=Math.max(he.current,Q.seq),Q.seq>0&&v(!0)),p.current||u(!0),p.current||y(""),typeof Q.data=="string"&&lt(Q.data);return}if(Q.type==="session_cleared"){if(!c){fe.current=!0,te.current="",ye.current=null;return}He();return}if(Q.type==="session_io_error"){const ne=typeof Q.error=="string"&&Q.error?Q.error:typeof Q.reason=="string"&&Q.reason?Q.reason:"unknown error";u(!1),y(`Runtime input failed: ${ne}`);return}}},Y))||(()=>{});return()=>{_()}},[Y,q,r,c]);const ut=async(_={})=>{var z;if(!Y||!q)return{success:!1,error:"daemonId and sessionId are required"};_.preserveStatus||y(_.loadingMessage||"Loading runtime terminal...");try{const Q=await((z=ot.requestRuntimeSnapshot)==null?void 0:z.call(ot,Y,q,{sinceSeq:_.sinceSeq,force:_.force}));return Q&&Q.success===!1?(_.preserveStatus||(u(!1),y(`Runtime terminal unavailable: ${Q.error}`)),Q):Q||{success:!0}}catch(Q){const ne=(Q==null?void 0:Q.message)||String(Q);return _.preserveStatus||(u(!1),y(`Runtime terminal unavailable: ${ne}`)),{success:!1,error:ne}}},Te=async _=>{var Ae,Pe;const z=((Ae=W.current)==null?void 0:Ae.ownerDocument)||document,Q=z.defaultView||window,ne=(Pe=Q.navigator)==null?void 0:Pe.clipboard;if(ne!=null&&ne.writeText&&Q.isSecureContext)try{return await ne.writeText(_),!0}catch{}let ve=null;try{return ve=z.createElement("textarea"),ve.value=_,ve.setAttribute("readonly","true"),ve.style.position="fixed",ve.style.left="-9999px",ve.style.top="0",z.body.appendChild(ve),ve.focus(),ve.select(),z.execCommand("copy")}catch{return!1}finally{ve==null||ve.remove()}},Ge=_=>{xe(),I(_);const z=de();ae.current={ownerWindow:z,timeoutId:z.setTimeout(()=>{ae.current=null,I(Q=>Q===_?null:Q)},2200)}},Ze=_=>{se(),x(_);const z=de();ge.current={ownerWindow:z,timeoutId:z.setTimeout(()=>{ge.current=null,x(Q=>Q===_?null:Q)},2200)}},qe=async()=>{var ve,Ae,Pe,Ce;const _=((Ae=(ve=r.current)==null?void 0:ve.getSelection)==null?void 0:Ae.call(ve))||"",z=((Ce=(Pe=r.current)==null?void 0:Pe.getVisibleText)==null?void 0:Ce.call(Pe))||"",Q=_.trimEnd()||z.trimEnd();if(!Q){Ge("Nothing to copy");return}if(!await Te(Q)){Ge("Copy failed");return}Ge(_.trimEnd()?"Copied selection":"Copied visible terminal")},tt=_=>{if(!f||!c)return;((d==null?void 0:d(Y,q,_))??!1)||Ge("Terminal input failed")},H=async()=>{if(N)return;h(!0),x("Loading older terminal output..."),be.current=!0;const _=await ut({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:f});if(h(!1),(_==null?void 0:_.success)===!1){be.current=!1,x(`Older terminal output unavailable: ${_.error}`);return}g(!0),Ze("Older terminal output loaded"),we(()=>{var z;(z=r.current)==null||z.bumpResize()})};i.useEffect(()=>{var z,Q;if(!q)return;Y&&((z=ot.getState)==null?void 0:z.call(ot,Y))==="connected"&&ut();const _=(Q=ot.onStateChange)==null?void 0:Q.call(ot,(ne,ve)=>{ne!==Y||ve!=="connected"||ut()});return()=>{_==null||_()}},[Y,q,r]),i.useEffect(()=>{t&&De()},[t,re,r]),i.useEffect(()=>{var ne,ve;const _=W.current,z=(ve=(ne=_==null?void 0:_.ownerDocument)==null?void 0:ne.defaultView)==null?void 0:ve.ResizeObserver;if(!_||!z)return;const Q=new z(Ae=>{const Pe=Ae[0];if(!Pe)return;const{width:Ce,height:Ee}=Pe.contentRect;R(Be=>{const _e=Math.round(Ce),ze=Math.round(Ee);return Be.width===_e&&Be.height===ze?Be:{width:_e,height:ze}})});return Q.observe(_),()=>Q.disconnect()},[]),i.useEffect(()=>{if($.current)return;const _=We();!Number.isFinite(_)||_<=0||T(z=>F.current?_<z-Me?_:z:(F.current=!0,_))},[S.height,S.width,K.height,K.width]),i.useEffect(()=>{D&&Re()},[D,Ie,Ne]),i.useEffect(()=>{var Q;const _=J.current;if(J.current=c,!c)return;_||g(!1),fe.current&&(fe.current=!1,He());const z=ye.current;z&&(ye.current=null,dt(z.text,z.seq,z.cols,z.rows,{force:!!z.force})),Y&&q&&((Q=ot.getState)==null?void 0:Q.call(ot,Y))==="connected"&&ut(),te.current&&X.current===null&&ie(),we(()=>{var ne;(ne=r.current)==null||ne.bumpResize()})},[Y,c,q]),i.useEffect(()=>()=>{X.current!==null&&ue(),xe(),se()},[]),i.useEffect(()=>{const _=ne=>{var Ae;const ve=ne.detail;ve!=null&&ve.sessionId&&ve.sessionId!==q||f&&((Ae=r.current)==null||Ae.bumpResize())},z=de(),Q=z===window?[window]:[window,z];for(const ne of Q)ne.addEventListener("adhdev:fit-cli-terminal",_);return()=>{for(const ne of Q)ne.removeEventListener("adhdev:fit-cli-terminal",_)}},[f,q,r]);const L=f&&b&&!A&&(U.atTop||!U.canScroll)||N||!!j;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:W,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[L&&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:()=>{H()},disabled:!q||N,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:N?"Loading older...":"Load older terminal output"}),j&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:j})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[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:()=>{qe()},disabled:!f,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(_=>!_),disabled:!f,"aria-label":"Open terminal control keys","aria-expanded":k,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),k&&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:()=>tt("\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:()=>tt(" "),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:()=>tt("\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:()=>tt("\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:()=>tt("\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:()=>tt("\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:()=>tt("\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:()=>tt(""),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:()=>tt(""),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:()=>tt(""),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:()=>{$.current=!0,T(_=>{const z=Math.max(Fe,Number((_-.1).toFixed(2)));return z>Fe&&Re(),z})},title:"Shrink terminal viewport",children:"-"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{$.current=!0,T(_=>{const z=Math.min(Se,Number((_+.1).toFixed(2)));return z>Fe&&Re(),z})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:E,className:D?"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:Ne>0?`${Ne}px`:"100%",height:Ie>0?`${Ie}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:S.width>0?`${S.width}px`:"100%",height:S.height>0?`${S.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:M},children:s.jsx(nc,{ref:r,readOnly:!f||!c,sizingMode:"measured",onViewportMetrics:O,onScrollMetrics:P,onInput:_=>{!f||(d==null||d(Y,q,_))}})})})}),!f&&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:m})]}),s.jsx(hc,{contextKey:e.tabKey,panelLabel:it(e),isSending:a,isBusy:!!ce,statusMessage:ke,onSend:async _=>ce?!1:n(_),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const fp=5e3,mp=12e3;function pp(e){return e==="disconnected"||e==="reconnecting"}function hp({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=fp,reconnectActionDelayMs:o=mp}){const c=pp(e),[l,d]=i.useState(()=>!c||a<=0),[f,u]=i.useState(()=>!c||o<=0),p=i.useRef(!1);i.useEffect(()=>{if(!c){d(!1);return}if(p.current=!1,a<=0){p.current=!0,d(!0);return}d(!1);const g=setTimeout(()=>{p.current=!0,d(!0)},a);return()=>clearTimeout(g)},[a,c]),i.useEffect(()=>{if(!c){u(!1);return}if(o<=0){u(!0);return}u(!1);const g=setTimeout(()=>{u(!0)},o);return()=>clearTimeout(g)},[o,c]);const m=c?l:e==="offline"||e==="auth_failed",y=!!(n&&e!=="auth_failed"&&(!c||f)),N=i.useMemo(()=>!t||e!=="connected"?!1:a<=0||p.current,[a,t,e]),h=e==="auth_failed"?"red":e==="offline"?"orange":"accent",j={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},x={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},b={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},v="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",A={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[m&&s.jsx("div",{className:v,style:A,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:j[h],border:x[h],color:b[h]},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.")]}),y&&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"})]})}),N&&s.jsx("div",{className:v,style:A,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 xp({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,c]=i.useState(!1);if(i.useEffect(()=>{if(!a){c(!1);return}try{c(localStorage.getItem(a)==="1")}catch{c(!1)}},[a]),!t||!e||e.backend!=="xterm"||o)return null;const l=(r==null?void 0:r.trim())||"This machine",d=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}c(!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:[l," 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 Qa({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(Ea,{size:n}):s.jsx(Ut,{size:n})})}const Et="New session",Uc="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 bp(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 gp(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 yp(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 Is({git:e,className:t="",compact:r=!1}){const n=bp(e),a=gp(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 ${yp(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 vp({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(l=>l==="connected").length,c=a.filter(l=>l==="connecting"||l==="new"||l==="checking").length;return r>0&&c>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 Qo({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Zo({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const c=ln(e.updatedAt),l=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${l?"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",c].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?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 wp({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:d,onHideConversation:f,hiddenConversations:u=[],onShowConversation:p,onShowAllHidden:m,onResetPanelsToMain:y,inboxOpen:N,onInboxOpenChange:h,hiddenOpen:j,onHiddenOpenChange:x,onOpenNewSession:b,onOpenDashboardGuide:v,guideNudgeVisible:A=!1,actionShortcuts:g,notifications:M,notificationUnreadCount:T,onOpenNotification:k,onMarkNotificationRead:w,onMarkNotificationUnread:K,onDeleteNotification:R,onOpenGitDialog:S}){const{ides:O,p2pStates:U={}}=ds(),P=!!e&&et(e)&&!Xe(e),C=!!e&&Xe(e),I=l||(e?xc(e)?"terminal":"chat":null),[W,E]=i.useState(!1),$=i.useRef(null),F=i.useRef(null),J=O.filter(ee=>ee.type==="adhdev-daemon"),he=vp({wsStatus:t,isConnected:r,daemonCount:J.length,p2pStates:U}),le=he.subtitle,te=he.tone==="connected"?"#22c55e":he.tone==="limited"?"#eab308":"#ef4444",ye=he.tone==="connected"?"0 0 4px #22c55e80":he.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",fe=i.useMemo(()=>M.filter(ee=>!ee.readAt),[M]),be=i.useMemo(()=>M.filter(ee=>!!ee.readAt),[M]),X=i.useMemo(()=>fe.slice(0,9),[fe]),ae=T;i.useEffect(()=>{if(!N)return;const ee=de=>{var we;(we=$.current)!=null&&we.contains(de.target)||h(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[N,h]),i.useEffect(()=>{if(!j)return;const ee=de=>{var we;(we=F.current)!=null&&we.contains(de.target)||x(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[j,x]),i.useEffect(()=>{if(!j&&!N)return;const ee=de=>{if(!de.altKey)return;const we=de.code.match(/^Digit([1-9])$/);if(!we)return;const ue=Number(we[1])-1,xe=j?u[ue]:void 0,se=N?X[ue]:void 0;if(!(!xe&&!se)){if(de.preventDefault(),de.stopPropagation(),xe){p==null||p(xe),x(!1);return}se&&(k(se),h(!1))}};return window.addEventListener("keydown",ee,!0),()=>window.removeEventListener("keydown",ee,!0)},[u,j,N,X,x,h,k,p]);const ge=ee=>{if(!ee)return;const de=n.find(we=>we.tabKey===ee);de&&(f==null||f(de))};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(Ut,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?it(e):"Dashboard"}),s.jsx("span",{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:te,boxShadow:ye}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[s.jsx("span",{title:he.title,className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:te,boxShadow:ye}}),le&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",le]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:`${Et}${g!=null&&g.openNewSession?` (${g.openNewSession})`:""}`,"aria-label":Et,children:s.jsx(Zi,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[v&&s.jsxs("button",{type:"button",onClick:v,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:"Dashboard guide","aria-label":"Open dashboard guide",children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),A&&s.jsx("span",{children:"Guide"})]}),e&&(P||C||!Xe(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:As(e)||it(e),children:it(e)}),S&&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:()=>S(e.daemonId,e.workspacePath),children:s.jsx(Is,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Is,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(P||C)&&c&&s.jsxs(s.Fragment,{children:[P&&d&&I&&s.jsx(Qa,{mode:I,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>c(e),className:"btn btn-secondary btn-sm",title:C?"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(St,{size:14})})]}),!Xe(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(Pa,{size:14})}),!P&&!Xe(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(Tt,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:$,children:[s.jsxs("div",{className:`dashboard-header-hidden${W?" is-drop-target":""}`,ref:F,onDragEnter:ee=>{ee.dataTransfer.types.includes("text/tab-key")&&(ee.preventDefault(),E(!0))},onDragOver:ee=>{ee.dataTransfer.types.includes("text/tab-key")&&(ee.preventDefault(),ee.dataTransfer.dropEffect="move",E(!0))},onDragLeave:ee=>{ee.currentTarget.contains(ee.relatedTarget)||E(!1)},onDrop:ee=>{const de=ee.dataTransfer.getData("text/tab-key");ee.preventDefault(),E(!1),ge(de)},children:[s.jsxs("button",{type:"button",onClick:()=>x(!j),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${g!=null&&g.toggleHiddenTabs?` (${g.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(Da,{size:16}),u.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:u.length})]}),j&&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(Qo,{value:g==null?void 0:g.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[y&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:y,children:"Reset panels"}),u.length>0&&m&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{m(),x(!1)},children:"Restore all"})]})]}),e&&f&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>f(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(Qo,{value:g==null?void 0:g.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:it(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:()=>{p==null||p(ee),x(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:it(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,As(ee)]})]},ee.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>h(!N),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(cn,{size:16}),ae>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:ae})]}),N&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[fe.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),fe.map(ee=>s.jsx(Zo,{notification:ee,shortcutIndex:X.indexOf(ee)>=0?X.indexOf(ee)+1:void 0,onOpen:()=>k(ee),onMarkRead:()=>w(ee.id),onMarkUnread:()=>K(ee.id),onDelete:()=>R(ee.id)},ee.id))]}),be.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),be.map(ee=>s.jsx(Zo,{notification:ee,onOpen:()=>k(ee),onMarkRead:()=>w(ee.id),onMarkUnread:()=>K(ee.id),onDelete:()=>R(ee.id)},ee.id))]}),M.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function xt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function jp(e,t){return String(e||"")!==String(t||"")}function kp(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(c=>!(o&&!c.canResume||r&&![c.title,c.preview].map(d=>String(d||"").toLowerCase()).join(`
38
+ \`\`\``}function vt(e){return(typeof e=="string"?e.trim():"")||void 0}function Ft(e,t){const r=vt(t);return r?`${e}:${r}`:void 0}function Gt(e,t,r){const n=Ft(t,r),a=vt(r);n&&e.push(n),a&&e.push(a)}function ws(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function Tc(e){return vt(e.providerSessionId)||vt(e.sessionId)||vt(e.tabKey)||vt(e.routeId)}function Ga(e){return ws([vt(e.providerSessionId),vt(e.sessionId)])}function Ss(e){const t=[];return Gt(t,"provider",e.providerSessionId),Gt(t,"session",e.sessionId),Gt(t,"tab",e.tabKey),Gt(t,"route",e.routeId),ws(t)}function am(e){const t=[];return vt(e.providerSessionId)?(Gt(t,"provider",e.providerSessionId),ws(t)):vt(e.sessionId)?(Gt(t,"session",e.sessionId),ws(t)):vt(e.tabKey)?(Gt(t,"tab",e.tabKey),ws(t)):vt(e.routeId)?(Gt(t,"route",e.routeId),ws(t)):[]}function qa(e){return Ft("provider",e.providerSessionId)||Ft("session",e.sessionId)||Ft("tab",e.tabKey)||Ft("route",e.routeId)||"unknown:"}function ur(e){return Ga(e)[0]}function om(e){const t=vt(e.providerSessionId),r=vt(e.sessionId),n=vt(e.tabKey),a=vt(e.routeId),o=[Ft("provider",t),Ft("session",r),Ft("tab",n),Ft("route",a)].filter(d=>typeof d=="string"),c=Ss({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),l=qa({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:Tc({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:ur({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:c}}function ha(e,t){const r=om(e);return am(t).some(n=>r.lookupKeys.includes(n))}function Ho(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 ss(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=Ho(t==null?void 0:t.receivedAt)||Ho(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function xa(e,t=0){return ss(e)||e.lastUpdated||t||0}function Mc(e){return ss(e)||e.lastUpdated||0}function Ac(e,t,r=Mc){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 c=e.displaySecondary.localeCompare(t.displaySecondary);return c!==0?c:e.tabKey.localeCompare(t.tabKey)}function ba(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 im(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!ba(e)&&!e.title.trim()}function cm(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(ba(r))-Number(ba(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:Ac(t,r)})[0]||null}function Pt(e,t){const r=e.filter(c=>c.routeId===t);if(r.length===0)return null;const n=r.find(c=>c.streamSource==="native")||null,a=r.filter(c=>c.streamSource==="agent-stream"),o=cm(a);return n?o&&im(n)?o:n:o||r[0]||null}function Yt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Ya(e){return ur(e)||e.tabKey||e.routeId||null}function Ic(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"";if(t)return t;const r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"";if(r)return r;const n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"";if(!n)return null;const a=Pt(e.conversations,n)||e.conversations.find(o=>o.routeId===n);return a?Ya(a):null}function Lc({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const o=Ps(),c=xs(e),l=bc(e),d=e.transport==="cdp-page"||e.transport==="cdp-webview",f=e.streamSource==="agent-stream"&&!!e.agentName,u=!f&&(e.transport==="pty"||e.transport==="acp"),p=Ts(e),m=Vf(e),y=i.useCallback(()=>{if(n){n();return}c&&o("/dashboard",{state:{openMachineId:c}})},[c,o,n]),N=i.useCallback(()=>{if(r){r();return}const h=Ya(e);h&&o(Yt(h))},[e,o,r]);return s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:N,title:m,children:[s.jsx(Tt,{size:12}),s.jsx("span",{children:m})]}):s.jsxs("span",{className:"conversation-meta-chip",title:m,children:[s.jsx(Tt,{size:12}),s.jsx("span",{children:m})]})),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:p,children:[s.jsx(ar,{size:12}),s.jsx("span",{children:p})]}),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:p,children:[s.jsx(ar,{size:12}),s.jsx("span",{children:p})]}),l&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:y,title:l,children:[s.jsx(us,{size:12}),s.jsx("span",{children:l})]}):s.jsxs("span",{className:"conversation-meta-chip",title:l,children:[s.jsx(us,{size:12}),s.jsx("span",{children:l})]}))]})}function Tn(e,t){return`${e}:${t}`}function lm(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Fs(e,t){lm()&&console.debug(`[subscription-manager] ${e}`,t)}class dm{constructor(){Ye(this,"active",new Map);Ye(this,"retryTimers",new Map)}subscribe(t,r,n,a,o){var u;const c=Tn(n.topic,n.key),l=this.active.get(c);let d=!0;if(l)l.handlers.add(a),l.lastUpdate&&a(l.lastUpdate);else{const p={daemonId:r,request:n,handlers:new Set([a])};this.active.set(c,p),Fs("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(c,t,o.retryIntervalMs)}const f=()=>{var y;this.clearRetry(c);const p=this.active.get(c);if(!p||(p.handlers.delete(a),p.handlers.size>0))return;this.active.delete(c);const m={type:"unsubscribe",topic:n.topic,key:n.key};Fs("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(y=t.sendData)==null||y.call(t,r,m)};return f.initialSendAccepted=d,f}publish(t){const r=Tn(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,Ns.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),Ns.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=Tn(t,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(t){var r;Fs("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);Fs("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 l;this.retryTimers.delete(t);const o=this.active.get(t);if(!o)return;const c=((l=r.sendData)==null?void 0:l.call(r,o.daemonId,o.request))??!1;Fs("subscribe_retry",{id:t,accepted:c,topic:o.request.topic,key:o.request.key}),c||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 Ht=new dm;function um(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});for(const o of n.childSessions||[]){if(!(o!=null&&o.id))continue;const c=r.get(o.id)||{};r.set(o.id,{...c,...o})}}return r}function fm(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 Zr(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:o,timestamp:c}=t,l=c||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:f,childrenByParent:u}=fm(d),p=um(o,n),m=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,y=f.filter(j=>j.kind==="workspace"&&j.transport==="cdp-page"),N=f.filter(j=>j.kind==="agent"&&j.transport==="pty"),h=f.filter(j=>j.kind==="agent"&&j.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...m&&{machine:m,platform:m.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:y.some(j=>!!j.cdpConnected)});for(const j of y){const x=p.get(j.id),b=qs(j,x),v=(u.get(j.id)||[]).map(A=>qs(A,p.get(A.id)));r.push({id:`${n}:ide:${j.id}`,sessionId:j.id,providerSessionId:j.providerSessionId??(x==null?void 0:x.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,status:b.cdpConnected?"online":"detected",daemonId:n,instanceId:j.id,workspace:b.workspace,terminals:0,childSessions:v,agents:v.map(A=>({id:A.id,name:A.providerName||A.providerType,type:A.providerType,status:A.status})),activeChat:b.activeChat,chats:[],cdpConnected:b.cdpConnected,...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l})}for(const j of N){const x=p.get(j.id),b=qs(j,x);r.push({id:`${n}:cli:${j.id}`,sessionId:j.id,providerSessionId:j.providerSessionId??(x==null?void 0:x.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:n,instanceId:j.id,cliName:b.providerName||b.providerType,mode:b.mode||(x==null?void 0:x.mode)||"terminal",workspace:b.workspace||"",activeChat:b.activeChat,...b.resume!==void 0&&{resume:b.resume},...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l,_isCli:!0})}for(const j of h){const x=p.get(j.id),b=qs(j,x);r.push({id:`${n}:acp:${j.id}`,sessionId:j.id,providerSessionId:j.providerSessionId??(x==null?void 0:x.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:n,instanceId:j.id,cliName:b.providerName||b.providerType,mode:"chat",workspace:b.workspace||"",activeChat:b.activeChat,...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const mm=15e3,pm=15e3,hm=6e4,xm=1200,Uo=12,bm=8e3,gm=4e3,Mn=new Map,An=new Map,Sr=new Set,Qs=new Map;function ym(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 zo(e,t){const r=Qs.get(e);!r||r.size===0||(Qs.delete(e),r.forEach(n=>n(t)))}function vm(e,t){return new Promise(r=>{const n=Qs.get(e)||new Set;Qs.set(e,n);const a=c=>{clearTimeout(o),n.delete(a),n.size===0&&Qs.delete(e),r(c)},o=setTimeout(()=>a(!1),t);n.add(a)})}function fr(){const{sendCommand:e,sendData:t}=mt(),{injectEntries:r,getIdes:n}=rr();return i.useCallback(async(a,o)=>{if(!a)return;const c=(o==null?void 0:o.minFreshMs)??hm,l=An.get(a)||0;if(!(o!=null&&o.force)&&Sr.has(a)&&l>0||!(o!=null&&o.force)&&l>0&&Date.now()-l<c)return;const d=Mn.get(a);if(d)return d;const f=(async()=>{if(t&&!Sr.has(a)){const h=Ht.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},j=>{const x=n(),b=x.find(A=>A.id===a),v=Zr(j.status,{daemonId:a,existingDaemon:b,existingEntries:x,timestamp:j.timestamp});v.length>0&&r(v),An.set(a,Date.now()),zo(a,!0)});if(h.initialSendAccepted?Sr.add(a):Sr.delete(a),!(o!=null&&o.force)&&h.initialSendAccepted&&await vm(a,xm))return}const u=await e(a,"get_status_metadata"),p=ym(u);if(!p)return;const m=n(),y=m.find(h=>h.id===a),N=Zr(p,{daemonId:a,existingDaemon:y,existingEntries:m,timestamp:p.timestamp||Date.now()});N.length>0&&r(N,{authoritativeDaemonIds:[a]}),An.set(a,Date.now()),zo(a,!0)})().finally(()=>{Mn.delete(a)});return Mn.set(a,f),f},[n,r,e,t])}function ir(e){if(!e||typeof e!="object")return[];const t=String(e.role||"");return[typeof e.providerUnitKey=="string"&&e.providerUnitKey.trim()?`${t}:providerUnitKey:${e.providerUnitKey.trim()}`:"",typeof e.bubbleId=="string"&&e.bubbleId.trim()?`${t}:bubbleId:${e.bubbleId.trim()}`:"",typeof e.id=="string"&&e.id.trim()?`${t}:id:${e.id.trim()}`:"",typeof e._localId=="string"&&e._localId.trim()?`${t}:localId:${e._localId.trim()}`:""].filter(Boolean)}function zt(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}function wm(e,t){if(!e||!t)return!1;if(e===t||e.id&&t.id&&String(e.id)===String(t.id)||e._localId&&t._localId&&String(e._localId)===String(t._localId))return!0;const r=String(e.role||"").toLowerCase(),n=String(t.role||"").toLowerCase();if(r!==n)return!1;const a=Kt(e.content),o=Kt(t.content);if(!a||!o||!(a===o||ya(a,o)||ya(o,a)))return!1;const l=zt(e),d=zt(t);return l&&d?Math.abs(l-d)<=15e3:!!e._localId!=!!t._localId}function ga(e){return Kt(e==null?void 0:e.content)}function ya(e,t){if(!e||!t||e.length<=t.length)return!1;const r=Math.max(12,Math.min(80,Math.floor(e.length*.4)));return t.length<r?!1:e.startsWith(t)||e.includes(t)}function Vo(e){if(!e)return[];const t=[],r=l=>{l&&t.push(l)};e.id&&r(`id:${String(e.id)}`),e._localId&&r(`local:${String(e._localId)}`),e._turnKey&&r(`turn:${String(e._turnKey)}`);const n=String(e.role||"").toLowerCase(),a=ga(e),o=zt(e),c=o?Math.round(o/15e3):0;return n&&a&&(r(`content:${n}:${a}`),r(`preview:${n}:${a.slice(0,120)}:${c}`)),t}function jm(e,t,r=wm){const n=new Map,a=o=>{for(const c of Vo(o)){const l=n.get(c);l?l.push(o):n.set(c,[o])}};return t.forEach(a),e.filter(o=>{const c=ga(o),l=String((o==null?void 0:o.role)||"").toLowerCase(),d=zt(o),f=new Set;for(const p of Vo(o)){const m=n.get(p);m&&m.forEach(y=>f.add(y))}return!(f.size>0?Array.from(f):t).some(p=>{if(r(o,p))return!0;const m=String((p==null?void 0:p.role)||"").toLowerCase();if(!c||!l||l!==m)return!1;const y=ga(p);if(!ya(y,c)&&y!==c)return!1;const N=zt(p);return d&&N?Math.abs(d-N)<=15e3:!0})})}const km=60,Sm=1e3;function Rc(e={}){return e.isCliLike?Sm:km}function Nm(e={}){return Rc(e)}const mr=60,Cm=1e3,Xa=12e4,Tm=new Set(["generating","waiting_approval","starting","streaming","working"]),Go=new Map;function Ja(e,t){return`${e}::${t}`}function va(e=mr){return{liveMessages:[],cursor:_c([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function $r(e){return Vi(e)}function _c(e,t=mr){return{knownMessageCount:e.length,lastMessageSignature:$r(e[e.length-1]),tailLimit:t}}function Nr(e,t){const r=e[e.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function qo(e){let t=0;for(const r of e){const n=zt(r);n>t&&(t=n)}return t}function Mm(e,t){if(t.length===0)return!1;if(e.length===0)return!0;const r=qo(e),n=qo(t);return!(r>0&&n<=0||r>0&&n>0&&n<r||r>0&&n===r&&t.length<e.length)}function Am(e,t){if(t.length===0)return e;const r=[...e],n=new Map,a=(o,c)=>{for(const l of ir(o))n.set(l,c)};r.forEach(a);for(const o of t){const l=ir(o).map(d=>n.get(d)).find(d=>d!==void 0);if(l!==void 0){r[l]=o,a(o,l);continue}r.push(o),a(o,r.length-1)}return r}function Im(e,t){const r=Array.isArray(t.messages)?t.messages:[];switch(t.syncMode){case"noop":return e;case"append":return Am(e,r);case"replace_tail":{const n=Math.max(0,Math.min(Number(t.replaceFrom??e.length),e.length));return[...e.slice(0,n),...r]}case"full":return r;default:return r}}class Lm{constructor(t){Ye(this,"manager");Ye(this,"sendData");Ye(this,"daemonId");Ye(this,"sessionId");Ye(this,"historySessionId");Ye(this,"subscriptionKey");Ye(this,"snapshot");Ye(this,"transportSubscription",null);Ye(this,"listeners",new Set);Ye(this,"retainCount",0);Ye(this,"loadHistoryPromise",null);Ye(this,"pendingDisconnectTimer",null);this.manager=t.manager||Ht,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.snapshot=va(Math.max(0,t.tailLimit??mr))}updateOptions(t){if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.tailLimit!==void 0){const r=Math.max(0,t.tailLimit);if(r!==this.snapshot.cursor.tailLimit){const n=r>this.snapshot.cursor.tailLimit,a=n?0:Math.min(this.snapshot.cursor.knownMessageCount,this.snapshot.liveMessages.length),o=n?"":this.snapshot.cursor.lastMessageSignature;this.snapshot={...this.snapshot,cursor:{knownMessageCount:a,lastMessageSignature:o,tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect())}}}getSnapshot(){return this.snapshot}hydrateLiveMessages(t){const r=Array.isArray(t)?t:[];if(!Mm(this.snapshot.liveMessages,r))return;const n=r,a=_c(n,this.snapshot.cursor.tailLimit);Nr(this.snapshot.liveMessages)===Nr(n)&&this.snapshot.cursor.knownMessageCount===a.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===a.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:n,cursor:a},this.emit())}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=await t({offset:this.snapshot.historyOffset,excludeRecentCount:this.snapshot.liveMessages.length}),a=Array.isArray(n.messages)?n.messages:[],o=jm(a,this.snapshot.liveMessages);this.snapshot={...this.snapshot,historyMessages:[...o,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+a.length,hasMoreHistory:n.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}:{},knownMessageCount:this.snapshot.cursor.knownMessageCount,lastMessageSignature:this.snapshot.cursor.lastMessageSignature,...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:Cm}))}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=typeof t.lastMessageSignature=="string"?t.lastMessageSignature:"",n=$r(this.snapshot.liveMessages[this.snapshot.liveMessages.length-1]),a=Array.isArray(t.messages)?t.messages:[];if(t.syncMode!=="full"&&r&&n===r&&a.length===0){const m={knownMessageCount:Math.max(this.snapshot.cursor.knownMessageCount,Number(t.totalMessages||0)),lastMessageSignature:r,tailLimit:this.snapshot.cursor.tailLimit};this.snapshot.cursor.knownMessageCount===m.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===m.lastMessageSignature||(this.snapshot={...this.snapshot,cursor:m},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:m.knownMessageCount,lastMessageSignature:m.lastMessageSignature}));return}const o=Im(this.snapshot.liveMessages,t),c=r||$r(o[o.length-1]),l=!!r&&$r(o[o.length-1])===r,f={knownMessageCount:t.syncMode!=="full"&&l&&Number(t.totalMessages||0)>o.length?Math.max(o.length,Number(t.totalMessages||0)):o.length,lastMessageSignature:c,tailLimit:this.snapshot.cursor.tailLimit};Nr(this.snapshot.liveMessages)===Nr(o)&&this.snapshot.cursor.knownMessageCount===f.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===f.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:o,cursor:f},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:f.knownMessageCount,lastMessageSignature:f.lastMessageSignature}),this.emit())}}function Pc(e){const t=Ja(e.daemonId,e.sessionId),r=Go.get(t);if(r)return r.updateOptions(e),r;const n=new Lm(e);return Go.set(t,n),n}function Rm(e,t){return{...e,loadHistoryPage:t}}function _m(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function Pm(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Tm.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??Xa)),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 Dm(e=Xa){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Em(e,t={}){const r=new Set,n=[];for(const a of e){if(!Pm(a,t))continue;const o=$s(a),c=a.sessionId||"";if(!o||!c)continue;const l=Ja(o,c);if(r.has(l))continue;r.add(l);const d=ur(a);n.push({daemonId:o,sessionId:c,historySessionId:d||c,subscriptionKey:`daemon:${o}:session:${c}`})}return n.sort(_m),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function $m(e,t){const{sendData:r,sendCommand:n}=mt(),a=(t==null?void 0:t.enabled)!==!1,o=$s(e),c=e.sessionId||"",l=ur(e)||c,d=`daemon:${o}:session:${c}`,f=Math.max(0,(t==null?void 0:t.tailLimit)??mr),u=i.useMemo(()=>!a||!o||!c?null:Pc({daemonId:o,sessionId:c,historySessionId:l,subscriptionKey:d,sendData:r,tailLimit:f}),[o,a,l,r,c,d,f]),[p,m]=i.useState(()=>(u==null?void 0:u.getSnapshot())||va(f));i.useEffect(()=>{if(!u){m(va(f));return}u.retain(),m(u.getSnapshot());const N=u.subscribe(h=>{m(h)});return()=>{N(),u.release()}},[u,f]),i.useEffect(()=>{u&&(u.hydrateLiveMessages(e.messages),m(u.getSnapshot()))},[e.messages,u]);const y=i.useCallback(async()=>{!u||!o||!c||await u.loadHistoryPage(async({offset:N,excludeRecentCount:h})=>{const j=e.agentType,x=await n(o,"chat_history",{agentType:j,offset:N,limit:30,targetSessionId:c,historySessionId:l,excludeRecentCount:h}),b=x&&typeof x=="object"&&"result"in x?x.result||{}:x||{};return{messages:Array.isArray(b.messages)?b.messages:[],hasMore:b.hasMore===!0}})},[e.agentType,u,o,l,n,c]);return i.useMemo(()=>Rm(p,y),[y,p])}function Bm(e,t){const{sendData:r}=mt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??mr),o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Xa)),c=Dm(o),[l,d]=i.useState(0),[f,u]=i.useState(()=>new Map);i.useEffect(()=>{if(!n||e.length===0)return;const m=setInterval(()=>{d(y=>y+1)},c);return()=>{clearInterval(m)}},[e.length,n,c]);const p=i.useMemo(()=>Em(e,{recentActivityMs:o}),[e,o,l]);return i.useEffect(()=>{if(!n||!r||p.descriptors.length===0){u(j=>j.size===0?j:new Map);return}const m=p.descriptors.map(j=>({key:Ja(j.daemonId,j.sessionId),controller:Pc({...j,sendData:r,tailLimit:a})})),y=new Set(m.map(({key:j})=>j)),N=(j,x)=>{u(b=>{const v=new Map(b);for(const A of v.keys())y.has(A)||v.delete(A);return v.set(j,x),v})},h=m.map(({key:j,controller:x})=>(x.retain(),N(j,x.getSnapshot()),x.subscribe(b=>N(j,b))));return()=>{h.forEach(j=>j()),m.forEach(({controller:j})=>j.release())}},[p.signature,n,r,a]),f}function Yo(e,t){const r=e[e.length-1];if(!r)return`empty:${t||""}`;let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return[t||"",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function en(e){for(let t=e.length-1;t>=0;t-=1){const r=zt(e[t]);if(r>0)return r}return 0}function Km(e){const t=$s(e),r=e.sessionId||"";return t&&r?`${t}::${r}`:""}function Om(e){const t=new Set;for(const r of e)for(const n of ir(r)){if(t.has(n))return!0;t.add(n)}return!1}function Wm(e,t){const r=new Set(ir(e));return r.size===0?!1:ir(t).some(n=>r.has(n))}function Dc(e,t){return t.length===0||e.length<=t.length||!Om(e)?!1:Wm(e[e.length-1],t[t.length-1])}function Fm(e,t){if(t.length===0)return!1;const r=Array.isArray(e.messages)?e.messages:[];if(r.length===0)return!0;const n=en(r),a=en(t);if(n>0&&a===n&&Dc(r,t))return!0;if(n<=0||a<=n)return!1;const o=Yo(r,e.status),c=Yo(t,e.status);return o!==c}function Hm(e,t){const r=t[t.length-1],n=zt(r),a=Kt(r==null?void 0:r.content);return{...e,messages:t,...a?{lastMessagePreview:a}:{},...n>0?{lastMessageAt:n}:{}}}function Um(e,t){const r=Array.isArray(e.messages)?e.messages:[],n=(t==null?void 0:t.liveMessages)||[];if(n.length===0)return r;if(r.length===0)return n;const a=en(r),o=en(n);if(a>0&&(o<=0||a>o))return r;if(a>0&&a===o){if(Dc(r,n))return n;if(r.length>=n.length)return r}return n}function zm(e){const{historyMessages:t,liveMessages:r,visibleLiveCount:n}=e,o=Math.max(0,r.length-n)>0?r.slice(-n):r;return t.length===0?o:[...t,...o]}function Xo(e,t){if(t.size===0||e.length===0)return e;let r=!1;const n=e.map(a=>{var l;const o=Km(a);if(!o)return a;const c=((l=t.get(o))==null?void 0:l.liveMessages)||[];return Fm(a,c)?(r=!0,Hm(a,c)):a});return r?n:e}function Vm(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Gm(e){return Vm(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}function qm(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function Ym(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function Xm(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Ec(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function $c(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 Jm(e){return Ec(e)?!1:e.inboxBucket==="task_complete"&&$c(e).length>0}function Jo(e){return e.branch||"detached HEAD"}function Qm(e){if(e.error)return`${Jo(e)} · Git error: ${e.error}`;const t=[Jo(e)];return e.changedFiles>0?t.push(qm(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 Zm(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${Qm(t)}`}function ep(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function tp(e,t={}){if(t.enabled===!1)return[];if(!Xm(e))return[];const r=Ec(e)?"working":Jm(e)?"complete":null;if(!r)return[];const n=r==="complete"?$c(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${Ym(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:Zm(r,e.git),timestamp:ep(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 sp=60;function wa({activeConv:e,ideEntry:t,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:o,isFocusingAgent:c,actionLogs:l,userName:d,showMetaChips:f=!1,scrollToBottomRequestNonce:u,isInputActive:p=!0,isVisible:m=!0}){var ge,ee,de,we,ue,xe,se;const y=i.useRef(new Map),N=i.useRef(void 0),h=fr(),{sendCommand:j}=mt(),{isVisible:x}=Oa();dr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const b=kt.useMemo(()=>Ds(e),[e.status,e.connectionState]),v=i.useMemo(()=>Yf(e,t),[e,t]),A=i.useMemo(()=>{var ie;return Ha((ie=v.targetEntry)==null?void 0:ie.providerControls,{hostIdeType:e.hostIdeType,providerType:v.providerType})},[e.hostIdeType,v.providerType,(ge=v.targetEntry)==null?void 0:ge.providerControls]),g=Rc({isCliLike:v.isCli||v.isAcp}),M=Nm({isCliLike:v.isCli||v.isAcp}),T=$m(e,{enabled:m&&!!e.sessionId,tailLimit:M}),[k,w]=i.useState(g),K=e.tabKey,R=T.historyMessages,S=T.hasMoreHistory,O=T.historyError,H=Um(e,T);i.useEffect(()=>{w(g)},[g,K]);const P=Math.max(0,H.length-k),C=Ua(e),I=$s(e),W=Gm(e),E=za(e),$=a||E,z=!!E,[J,he]=i.useState(!1);i.useEffect(()=>{const ie=v.targetEntry;I&&(!ie||ie.providerControls===void 0||ie.controlValues===void 0)&&h(I,{minFreshMs:3e4}).catch(()=>{})},[I,v.isAcp,(ee=v.targetEntry)==null?void 0:ee.providerControls,(de=v.targetEntry)==null?void 0:de.controlValues,h]);const ce=i.useCallback(async()=>{if(!J){if(H.length>k){w(ie=>Math.min(H.length,ie+sp));return}he(!0);try{await T.loadHistoryPage()}finally{he(!1)}}},[T,J,H.length,k]),{allMessages:te,receivedAtMap:ye}=i.useMemo(()=>{const ie=zm({historyMessages:R,liveMessages:H,visibleLiveCount:k}),re=tp(e),q=re.length>0?[...ie,...re]:ie,Y={};return q.forEach((le,ke)=>{const Z=`${e.tabKey}:${qr(le,ke)}`;let Ce=zt(le)||y.current.get(Z)||0;Ce||(Ce=Date.now(),y.current.set(Z,Ce)),Y[qr(le,ke)]=Ce}),{allMessages:q,receivedAtMap:Y}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,P,R,H,k]),fe=i.useMemo(()=>l.filter(ie=>ie.routeId===e.tabKey).sort((ie,re)=>ie.timestamp-re.timestamp),[l,e.tabKey]),be=i.useCallback(async()=>{var ke,Z;if(!I)return;const ie=kc({activeConv:e,visibleMessages:te,actionLogs:l,controls:(ke=v.targetEntry)==null?void 0:ke.providerControls,controlValues:(Z=v.targetEntry)==null?void 0:Z.controlValues,visibleBarControlCount:A.length,chatTailState:{hasMoreHistory:S,historyError:O,historyMessages:R},ui:{controlsVisible:x,visibleLiveCount:k,hiddenLiveCount:P,isInputActive:p,isVisible:m}}),re=await j(I,"get_chat_debug_bundle",{agentType:v.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:ie}),q=Qr(re),Y=Cc(q),le=await Nc(Y);le==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),rt.showToast(Sc(q,{locatorCopyStatus:le}),le==="failed"?"warning":"success")},[e,l,te,x,v.providerType,(we=v.targetEntry)==null?void 0:we.controlValues,(ue=v.targetEntry)==null?void 0:ue.providerControls,I,S,P,R,p,m,O,j,A.length,k]),X=i.useCallback(()=>{const ie=nm(N.current);N.current=ie.state,ie.shouldCollect&&be().catch(re=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",re),rt.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[be]),ae=i.useMemo(()=>{if(H.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((b.isGenerating||e.status==="streaming")&&he(!1),e.status==="not_monitored"&&W)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(ar,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),s.jsx("button",{onClick:o,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Cs,{size:14})," Open ",C," 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"&&W)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(Ji,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),s.jsx("button",{onClick:o,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Cs,{size:14})," Open ",C," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!J)return 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,W,o,c,J,H.length,C,b.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[f&&s.jsx(Lc,{conversation:e,className:"chat-pane-meta-row"}),s.jsx($u,{messages:te,actionLogs:fe,agentName:Ts(e)||C||"Agent",userName:d,isCliMode:v.isCli||v.isAcp,isWorking:b.isGenerating,contextKey:e.tabKey,receivedAtMap:ye,lastMessageHash:e.lastMessageHash,onLoadMore:ce,isLoadingMore:J,hasMoreHistory:S,hiddenLiveCount:P,loadError:O??void 0,emptyState:ae,scrollToBottomRequestNonce:u,isVisible:m}),s.jsx(Of,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:v.providerType,displayLabel:v.displayLabel,controls:(xe=v.targetEntry)==null?void 0:xe.providerControls,controlValues:(se=v.targetEntry)==null?void 0:se.controlValues,isActive:p,isCliTerminal:v.isCliTerminal}),!v.isCliTerminal&&s.jsx(hc,{contextKey:e.tabKey,panelLabel:C,isSending:n,isBusy:z,statusMessage:$,onSend:r,isActive:p,showControlsToggle:A.length>0,onControlsToggle:X})]})}let Bc=ds;function Kc(){return Bc()}class rp{constructor(){Ye(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 Oc=new rp;class np{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 ot=new np;function ap(e){e.dashboardWS&&(Oc=e.dashboardWS),e.connectionManager&&(ot=e.connectionManager),e.useDaemonsHook&&(Bc=e.useDaemonsHook)}const op=.5,ip=1.25;function it(e){return Ua(e)}function As(e){return vc(e).join(" · ")}function Wc(e){const t=yc(e);return t||(e.title?e.title:As(e)||"No messages yet")}function Fc(e,t){const{isReconnecting:r,isConnecting:n}=Ds(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function cp(e,t){const r=["Chat",...vc(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function rs(e){return Fc(e)||As(e)}function lp(e){return`${it(e)} · ${Wc(e)}`}function dp(e){const t=Jr(e),r=t?at(t):Ts(e);return`${it(e)} — ${r||"Agent"}`}function up(e){return Ts(e)||"CLI"}function Hc(e){return gc(e)}function Uc(e){return e?`Remote · ${it(e)||e.workspaceName||"Session"}`:"Remote"}function fp({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:c=!0,isInputActive:l=!0}){var G;ds();const{sendPtyInput:d}=mt(),[f,u]=i.useState(!1),p=i.useRef(!1);p.current=f;const[m,y]=i.useState("Runtime terminal unavailable"),[N,h]=i.useState(!1),[j,x]=i.useState(null),[b,v]=i.useState(!1),[A,g]=i.useState(!1),[M,T]=i.useState(1),[k,w]=i.useState(!1),[K,R]=i.useState({width:0,height:0}),[S,O]=i.useState({width:0,height:0}),[H,P]=i.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[C,I]=i.useState(null),W=i.useRef(null),E=i.useRef(null),$=i.useRef(!1),z=i.useRef(!1),J=i.useRef(c),he=i.useRef(0),ce=i.useRef(!1),te=i.useRef(""),ye=i.useRef(null),fe=i.useRef(!1),be=i.useRef(!1),X=i.useRef(null),ae=i.useRef(null),ge=i.useRef(null),ee=32*1024,de=()=>{var _,U,Q,ne;return((U=(_=W.current)==null?void 0:_.ownerDocument)==null?void 0:U.defaultView)||((ne=(Q=E.current)==null?void 0:Q.ownerDocument)==null?void 0:ne.defaultView)||window},we=_=>{const U=de();return{ownerWindow:U,frameId:U.requestAnimationFrame(_)}},ue=()=>{const _=X.current;if(_){try{_.ownerWindow.cancelAnimationFrame(_.frameId)}catch{}X.current=null}},xe=()=>{const _=ae.current;if(_){try{_.ownerWindow.clearTimeout(_.timeoutId)}catch{}ae.current=null}},se=()=>{const _=ge.current;if(_){try{_.ownerWindow.clearTimeout(_.timeoutId)}catch{}ge.current=null}},ie=()=>{c&&X.current===null&&(X.current=we(()=>{Qe()}))},re=e.tabKey,q=e.sessionId||"",Y=e.daemonId||((G=e.routeId)==null?void 0:G.split(":")[0])||e.routeId||"",le=za(e),ke=f?o||le:m,Z=op,Ce=ip,Ee=.05,We=()=>{const _=S.width,U=S.height;if(!Number.isFinite(K.width)||K.width<=0||!Number.isFinite(K.height)||K.height<=0||!Number.isFinite(_)||_<=0||!Number.isFinite(U)||U<=0)return 1;const Q=K.width/_,ne=K.height/U;return Number(Math.min(Ce,Math.max(Z,Math.min(Q,ne))).toFixed(2))},Fe=We(),D=$.current&&M>Fe,Se=Number.isFinite(S.width)&&S.width>0?Math.max(K.width,Math.round(S.width*M)):K.width,Ae=Number.isFinite(S.height)&&S.height>0?Math.max(K.height,Math.round(S.height*M)):K.height,Le=()=>{we(()=>{const _=E.current;_&&(_.scrollLeft=0,_.scrollTop=_.scrollHeight-_.clientHeight)})},Pe=()=>{var _,U;he.current=0,ce.current=!1,te.current="",ye.current=null,fe.current=!1,be.current=!1,$.current||(z.current=!1,T(1)),X.current!==null&&ue(),u(!1),y("Runtime terminal unavailable"),se(),xe(),x(null),I(null),w(!1),h(!1),v(!1),g(!1),(U=(_=r.current)==null?void 0:_.reset)==null||U.call(_)},He=()=>{var _,U;he.current=0,ce.current=!1,te.current="",ye.current=null,fe.current=!1,be.current=!1,X.current!==null&&ue(),u(!0),y(""),se(),xe(),x(null),I(null),w(!1),h(!1),v(!1),g(!1),(U=(_=r.current)==null?void 0:_.reset)==null||U.call(_)},Ue=()=>{be.current&&(be.current=!1,we(()=>{var _,U;(U=(_=r.current)==null?void 0:_.scrollToTop)==null||U.call(_)}))},Qe=()=>{if(X.current=null,!c)return;const _=te.current;if(!_)return;const U=_.slice(0,ee);te.current=_.slice(U.length);const Q=r.current;if(!Q){te.current=U+te.current,ie();return}Q.write(U,()=>{if(te.current.length>0){ie();return}Ue()})},lt=_=>{_&&(te.current+=_,ie())},dt=(_,U=0,Q,ne,ve={})=>{var _e,Ne,De,Be;const Me=!!ve.force;!Me&&U>0&&he.current>=U||!Me&&U===0&&ce.current||(he.current=U,U>0&&v(!0),u(!0),y(""),typeof Q=="number"&&typeof ne=="number"&&Q>0&&ne>0&&((Ne=(_e=r.current)==null?void 0:_e.resize)==null||Ne.call(_e,Q,ne)),te.current="",(Be=(De=r.current)==null?void 0:De.reset)==null||Be.call(De),_?lt(_):Ue())};i.useEffect(()=>{Pe()},[q]),i.useEffect(()=>{var U;if(!q)return;const _=((U=ot.onRuntimeEvent)==null?void 0:U.call(ot,q,Q=>{if(!(!Q||Q.sessionId!==q)){if(Q.type==="runtime_snapshot"){if(!c){ye.current={text:Q.text||"",seq:Q.seq||0,cols:Q.cols,rows:Q.rows,force:!!Q.force};return}dt(Q.text||"",Q.seq||0,Q.cols,Q.rows,{force:!!Q.force});return}if(Q.type==="session_output"){ce.current=!0,typeof Q.seq=="number"&&(he.current=Math.max(he.current,Q.seq),Q.seq>0&&v(!0)),p.current||u(!0),p.current||y(""),typeof Q.data=="string"&&lt(Q.data);return}if(Q.type==="session_cleared"){if(!c){fe.current=!0,te.current="",ye.current=null;return}He();return}if(Q.type==="session_io_error"){const ne=typeof Q.error=="string"&&Q.error?Q.error:typeof Q.reason=="string"&&Q.reason?Q.reason:"unknown error";u(!1),y(`Runtime input failed: ${ne}`);return}}},Y))||(()=>{});return()=>{_()}},[Y,q,r,c]);const ut=async(_={})=>{var U;if(!Y||!q)return{success:!1,error:"daemonId and sessionId are required"};_.preserveStatus||y(_.loadingMessage||"Loading runtime terminal...");try{const Q=await((U=ot.requestRuntimeSnapshot)==null?void 0:U.call(ot,Y,q,{sinceSeq:_.sinceSeq,force:_.force}));return Q&&Q.success===!1?(_.preserveStatus||(u(!1),y(`Runtime terminal unavailable: ${Q.error}`)),Q):Q||{success:!0}}catch(Q){const ne=(Q==null?void 0:Q.message)||String(Q);return _.preserveStatus||(u(!1),y(`Runtime terminal unavailable: ${ne}`)),{success:!1,error:ne}}},Te=async _=>{var Me,_e;const U=((Me=W.current)==null?void 0:Me.ownerDocument)||document,Q=U.defaultView||window,ne=(_e=Q.navigator)==null?void 0:_e.clipboard;if(ne!=null&&ne.writeText&&Q.isSecureContext)try{return await ne.writeText(_),!0}catch{}let ve=null;try{return ve=U.createElement("textarea"),ve.value=_,ve.setAttribute("readonly","true"),ve.style.position="fixed",ve.style.left="-9999px",ve.style.top="0",U.body.appendChild(ve),ve.focus(),ve.select(),U.execCommand("copy")}catch{return!1}finally{ve==null||ve.remove()}},Ge=_=>{xe(),I(_);const U=de();ae.current={ownerWindow:U,timeoutId:U.setTimeout(()=>{ae.current=null,I(Q=>Q===_?null:Q)},2200)}},Ze=_=>{se(),x(_);const U=de();ge.current={ownerWindow:U,timeoutId:U.setTimeout(()=>{ge.current=null,x(Q=>Q===_?null:Q)},2200)}},qe=async()=>{var ve,Me,_e,Ne;const _=((Me=(ve=r.current)==null?void 0:ve.getSelection)==null?void 0:Me.call(ve))||"",U=((Ne=(_e=r.current)==null?void 0:_e.getVisibleText)==null?void 0:Ne.call(_e))||"",Q=_.trimEnd()||U.trimEnd();if(!Q){Ge("Nothing to copy");return}if(!await Te(Q)){Ge("Copy failed");return}Ge(_.trimEnd()?"Copied selection":"Copied visible terminal")},tt=_=>{if(!f||!c)return;((d==null?void 0:d(Y,q,_))??!1)||Ge("Terminal input failed")},F=async()=>{if(N)return;h(!0),x("Loading older terminal output..."),be.current=!0;const _=await ut({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:f});if(h(!1),(_==null?void 0:_.success)===!1){be.current=!1,x(`Older terminal output unavailable: ${_.error}`);return}g(!0),Ze("Older terminal output loaded"),we(()=>{var U;(U=r.current)==null||U.bumpResize()})};i.useEffect(()=>{var U,Q;if(!q)return;Y&&((U=ot.getState)==null?void 0:U.call(ot,Y))==="connected"&&ut();const _=(Q=ot.onStateChange)==null?void 0:Q.call(ot,(ne,ve)=>{ne!==Y||ve!=="connected"||ut()});return()=>{_==null||_()}},[Y,q,r]),i.useEffect(()=>{t&&Pe()},[t,re,r]),i.useEffect(()=>{var ne,ve;const _=W.current,U=(ve=(ne=_==null?void 0:_.ownerDocument)==null?void 0:ne.defaultView)==null?void 0:ve.ResizeObserver;if(!_||!U)return;const Q=new U(Me=>{const _e=Me[0];if(!_e)return;const{width:Ne,height:De}=_e.contentRect;R(Be=>{const Re=Math.round(Ne),ze=Math.round(De);return Be.width===Re&&Be.height===ze?Be:{width:Re,height:ze}})});return Q.observe(_),()=>Q.disconnect()},[]),i.useEffect(()=>{if($.current)return;const _=We();!Number.isFinite(_)||_<=0||T(U=>z.current?_<U-Ee?_:U:(z.current=!0,_))},[S.height,S.width,K.height,K.width]),i.useEffect(()=>{D&&Le()},[D,Ae,Se]),i.useEffect(()=>{var Q;const _=J.current;if(J.current=c,!c)return;_||g(!1),fe.current&&(fe.current=!1,He());const U=ye.current;U&&(ye.current=null,dt(U.text,U.seq,U.cols,U.rows,{force:!!U.force})),Y&&q&&((Q=ot.getState)==null?void 0:Q.call(ot,Y))==="connected"&&ut(),te.current&&X.current===null&&ie(),we(()=>{var ne;(ne=r.current)==null||ne.bumpResize()})},[Y,c,q]),i.useEffect(()=>()=>{X.current!==null&&ue(),xe(),se()},[]),i.useEffect(()=>{const _=ne=>{var Me;const ve=ne.detail;ve!=null&&ve.sessionId&&ve.sessionId!==q||f&&((Me=r.current)==null||Me.bumpResize())},U=de(),Q=U===window?[window]:[window,U];for(const ne of Q)ne.addEventListener("adhdev:fit-cli-terminal",_);return()=>{for(const ne of Q)ne.removeEventListener("adhdev:fit-cli-terminal",_)}},[f,q,r]);const L=f&&b&&!A&&(H.atTop||!H.canScroll)||N||!!j;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:W,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[L&&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:()=>{F()},disabled:!q||N,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:N?"Loading older...":"Load older terminal output"}),j&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:j})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[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:()=>{qe()},disabled:!f,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(_=>!_),disabled:!f,"aria-label":"Open terminal control keys","aria-expanded":k,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),k&&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:()=>tt("\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:()=>tt(" "),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:()=>tt("\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:()=>tt("\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:()=>tt("\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:()=>tt("\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:()=>tt("\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:()=>tt(""),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:()=>tt(""),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:()=>tt(""),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:()=>{$.current=!0,T(_=>{const U=Math.max(Fe,Number((_-.1).toFixed(2)));return U>Fe&&Le(),U})},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:()=>{$.current=!0,T(_=>{const U=Math.min(Ce,Number((_+.1).toFixed(2)));return U>Fe&&Le(),U})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:E,className:D?"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:Se>0?`${Se}px`:"100%",height:Ae>0?`${Ae}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:S.width>0?`${S.width}px`:"100%",height:S.height>0?`${S.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:M},children:s.jsx(nc,{ref:r,readOnly:!f||!c,sizingMode:"measured",onViewportMetrics:O,onScrollMetrics:P,onInput:_=>{!f||(d==null||d(Y,q,_))}})})})}),!f&&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:m})]}),s.jsx(hc,{contextKey:e.tabKey,panelLabel:it(e),isSending:a,isBusy:!!le,statusMessage:ke,onSend:async _=>le?!1:n(_),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const mp=5e3,pp=12e3;function hp(e){return e==="disconnected"||e==="reconnecting"}function xp({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=mp,reconnectActionDelayMs:o=pp}){const c=hp(e),[l,d]=i.useState(()=>!c||a<=0),[f,u]=i.useState(()=>!c||o<=0),p=i.useRef(!1);i.useEffect(()=>{if(!c){d(!1);return}if(p.current=!1,a<=0){p.current=!0,d(!0);return}d(!1);const g=setTimeout(()=>{p.current=!0,d(!0)},a);return()=>clearTimeout(g)},[a,c]),i.useEffect(()=>{if(!c){u(!1);return}if(o<=0){u(!0);return}u(!1);const g=setTimeout(()=>{u(!0)},o);return()=>clearTimeout(g)},[o,c]);const m=c?l:e==="offline"||e==="auth_failed",y=!!(n&&e!=="auth_failed"&&(!c||f)),N=i.useMemo(()=>!t||e!=="connected"?!1:a<=0||p.current,[a,t,e]),h=e==="auth_failed"?"red":e==="offline"?"orange":"accent",j={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},x={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},b={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},v="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",A={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[m&&s.jsx("div",{className:v,style:A,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:j[h],border:x[h],color:b[h]},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.")]}),y&&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"})]})}),N&&s.jsx("div",{className:v,style:A,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 bp({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,c]=i.useState(!1);if(i.useEffect(()=>{if(!a){c(!1);return}try{c(localStorage.getItem(a)==="1")}catch{c(!1)}},[a]),!t||!e||e.backend!=="xterm"||o)return null;const l=(r==null?void 0:r.trim())||"This machine",d=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}c(!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:[l," 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 Qa({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(Ea,{size:n}):s.jsx(Ut,{size:n})})}const Et="New session",zc="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 gp(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 yp(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 vp(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 Is({git:e,className:t="",compact:r=!1}){const n=gp(e),a=yp(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 ${vp(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 wp({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(l=>l==="connected").length,c=a.filter(l=>l==="connecting"||l==="new"||l==="checking").length;return r>0&&c>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 Qo({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Zo({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const c=ln(e.updatedAt),l=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${l?"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",c].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?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 jp({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:d,onHideConversation:f,hiddenConversations:u=[],onShowConversation:p,onShowAllHidden:m,onResetPanelsToMain:y,inboxOpen:N,onInboxOpenChange:h,hiddenOpen:j,onHiddenOpenChange:x,onOpenNewSession:b,onOpenDashboardGuide:v,guideNudgeVisible:A=!1,actionShortcuts:g,notifications:M,notificationUnreadCount:T,onOpenNotification:k,onMarkNotificationRead:w,onMarkNotificationUnread:K,onDeleteNotification:R,onOpenGitDialog:S}){const{ides:O,p2pStates:H={}}=ds(),P=!!e&&et(e)&&!Xe(e),C=!!e&&Xe(e),I=l||(e?xc(e)?"terminal":"chat":null),[W,E]=i.useState(!1),$=i.useRef(null),z=i.useRef(null),J=O.filter(ee=>ee.type==="adhdev-daemon"),he=wp({wsStatus:t,isConnected:r,daemonCount:J.length,p2pStates:H}),ce=he.subtitle,te=he.tone==="connected"?"#22c55e":he.tone==="limited"?"#eab308":"#ef4444",ye=he.tone==="connected"?"0 0 4px #22c55e80":he.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",fe=i.useMemo(()=>M.filter(ee=>!ee.readAt),[M]),be=i.useMemo(()=>M.filter(ee=>!!ee.readAt),[M]),X=i.useMemo(()=>fe.slice(0,9),[fe]),ae=T;i.useEffect(()=>{if(!N)return;const ee=de=>{var we;(we=$.current)!=null&&we.contains(de.target)||h(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[N,h]),i.useEffect(()=>{if(!j)return;const ee=de=>{var we;(we=z.current)!=null&&we.contains(de.target)||x(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[j,x]),i.useEffect(()=>{if(!j&&!N)return;const ee=de=>{if(!de.altKey)return;const we=de.code.match(/^Digit([1-9])$/);if(!we)return;const ue=Number(we[1])-1,xe=j?u[ue]:void 0,se=N?X[ue]:void 0;if(!(!xe&&!se)){if(de.preventDefault(),de.stopPropagation(),xe){p==null||p(xe),x(!1);return}se&&(k(se),h(!1))}};return window.addEventListener("keydown",ee,!0),()=>window.removeEventListener("keydown",ee,!0)},[u,j,N,X,x,h,k,p]);const ge=ee=>{if(!ee)return;const de=n.find(we=>we.tabKey===ee);de&&(f==null||f(de))};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(Ut,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?it(e):"Dashboard"}),s.jsx("span",{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:te,boxShadow:ye}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[s.jsx("span",{title:he.title,className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:te,boxShadow:ye}}),ce&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",ce]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:`${Et}${g!=null&&g.openNewSession?` (${g.openNewSession})`:""}`,"aria-label":Et,children:s.jsx(Zi,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[v&&s.jsxs("button",{type:"button",onClick:v,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:"Dashboard guide","aria-label":"Open dashboard guide",children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),A&&s.jsx("span",{children:"Guide"})]}),e&&(P||C||!Xe(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:As(e)||it(e),children:it(e)}),S&&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:()=>S(e.daemonId,e.workspacePath),children:s.jsx(Is,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Is,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(P||C)&&c&&s.jsxs(s.Fragment,{children:[P&&d&&I&&s.jsx(Qa,{mode:I,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>c(e),className:"btn btn-secondary btn-sm",title:C?"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(St,{size:14})})]}),!Xe(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(Pa,{size:14})}),!P&&!Xe(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(Tt,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:$,children:[s.jsxs("div",{className:`dashboard-header-hidden${W?" is-drop-target":""}`,ref:z,onDragEnter:ee=>{ee.dataTransfer.types.includes("text/tab-key")&&(ee.preventDefault(),E(!0))},onDragOver:ee=>{ee.dataTransfer.types.includes("text/tab-key")&&(ee.preventDefault(),ee.dataTransfer.dropEffect="move",E(!0))},onDragLeave:ee=>{ee.currentTarget.contains(ee.relatedTarget)||E(!1)},onDrop:ee=>{const de=ee.dataTransfer.getData("text/tab-key");ee.preventDefault(),E(!1),ge(de)},children:[s.jsxs("button",{type:"button",onClick:()=>x(!j),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${g!=null&&g.toggleHiddenTabs?` (${g.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(Da,{size:16}),u.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:u.length})]}),j&&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(Qo,{value:g==null?void 0:g.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[y&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:y,children:"Reset panels"}),u.length>0&&m&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{m(),x(!1)},children:"Restore all"})]})]}),e&&f&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>f(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(Qo,{value:g==null?void 0:g.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:it(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:()=>{p==null||p(ee),x(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:it(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,As(ee)]})]},ee.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>h(!N),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(cn,{size:16}),ae>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:ae})]}),N&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[fe.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),fe.map(ee=>s.jsx(Zo,{notification:ee,shortcutIndex:X.indexOf(ee)>=0?X.indexOf(ee)+1:void 0,onOpen:()=>k(ee),onMarkRead:()=>w(ee.id),onMarkUnread:()=>K(ee.id),onDelete:()=>R(ee.id)},ee.id))]}),be.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),be.map(ee=>s.jsx(Zo,{notification:ee,onOpen:()=>k(ee),onMarkRead:()=>w(ee.id),onMarkUnread:()=>K(ee.id),onDelete:()=>R(ee.id)},ee.id))]}),M.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function xt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function kp(e,t){return String(e||"")!==String(t||"")}function Sp(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(c=>!(o&&!c.canResume||r&&![c.title,c.preview].map(d=>String(d||"").toLowerCase()).join(`
39
39
  `).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!dc(c.summaryMetadata).map(d=>d.toLowerCase()).join(`
40
- `).includes(a)))}function Sp(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 zc(e,t={}){return Sp(kp(e,t),t.sortMode||"recent")}function tn(e){return e?"Resume saved history":"Start fresh"}function Za(e){return e?"Resuming saved history…":"Starting fresh…"}function Np(){return"Start fresh"}function Vc(e,t=!1){return e==="cli"?tn(t):e==="ide"?"Start IDE":"Start ACP session"}function Gc(e,t=!1){return e==="cli"?Za(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Cp(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Tp(){return"Open saved history"}function Mp(){return"Saved History"}function eo(){return"Use saved history when you want continuity in the same provider conversation."}function Ap(){return"No saved history found yet."}function Ip(){return"Refresh saved history"}function Lp(){return"Refreshing saved history…"}function ns(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function as(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 Ls(e){return e==="start-fresh"?"Start fresh":"Restart"}function Rs(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function to(e){return`Resume saved history with ${e}?`}function so(){return"Review or change the target workspace before resuming saved history."}function Rp(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 ro({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:f,onClose:u,onNewChat:p,onSwitchSession:m,onRefreshHistory:y,onResumeSavedSession:N}){var R;const h=t.find(S=>S.id===e.routeId),j=(h==null?void 0:h.chats)||[],x=(R=h==null?void 0:h.activeChat)==null?void 0:R.id,b=et(e)&&!Xe(e),[v,A]=i.useState(()=>xt()),g=l||v,M=String(d||"").trim(),T=S=>{if(f){f(S);return}A(S)},k=i.useMemo(()=>a.map(S=>{const O=String(S.workspace||"").trim();return S.canResume||O||!M?S:{...S,workspace:M,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[M,a]),w=i.useMemo(()=>zc(k,{textQuery:g.textQuery,workspaceQuery:g.workspaceQuery,modelQuery:g.modelQuery,resumableOnly:g.resumableOnly,sortMode:g.sortMode}),[k,g.modelQuery,g.resumableOnly,g.sortMode,g.textQuery,g.workspaceQuery]),K=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:b?Mp():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:lp(e)}),b&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:eo()})]}),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(St,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!b&&s.jsx("button",{onClick:p,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),b?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:g.textQuery,onChange:S=>T({...g,textQuery:S.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:g.workspaceQuery,onChange:S=>T({...g,workspaceQuery:S.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:g.modelQuery,onChange:S=>T({...g,modelQuery:S.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:g.sortMode,onChange:S=>T({...g,sortMode:S.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:g.resumableOnly,onChange:S=>T({...g,resumableOnly:S.target.checked})}),"Resume-ready only"]})]}),w.map(S=>{const O=e.providerSessionId===S.providerSessionId,U=O||!S.canResume||!!c,P=S.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{U||!N||N(S)},disabled:U,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${O?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${U?"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 ${O?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:S.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:S.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Rp(S.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:S.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:[S.workspace||"Workspace unknown",P?" · selected workspace":"",fs(S.summaryMetadata)?` · ${fs(S.summaryMetadata)}`:"",S.messageCount>0?` · ${S.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:O?"ACTIVE":S.canResume?P?"RESUME IN SELECTED WORKSPACE":c===S.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},S.id)})]}):j.map(S=>s.jsxs("div",{onClick:()=>{m(e.routeId,S.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${x===S.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${x===S.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:S.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:[S.id.substring(0,12),"..."]}),x===S.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},S.id)),(b&&!o&&w.length===0||!b&&j.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(lu,{size:32})}),s.jsx("div",{className:"text-[13px]",children:b?a.length>0?"No saved history matches these filters.":Ap():"No recent chat sessions found."})]}),b&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Lp()})})]}),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:y,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(lr,{size:13})," ",b?Ip():"Refresh History"]})})})]})]});return typeof document>"u"?K:sr.createPortal(K,document.body)}const ei={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 qc({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=ei[n.type]||ei.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(St,{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,c)=>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:l=>{l.stopPropagation(),o.onClick(),t(n.id)},children:o.label},c))})]})]},n.id)})})}const _p=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Pp(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function Dp(e){return e.sessionId||e.instanceId||e.agentType}function In(e,t){return e||t}function Yc(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Ct(r,{fallbackId:r.id}));return t}function Xc(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 no(e,t={}){return Ep(e,Xc(e,t))}function Ep(e,t={}){var p,m,y,N,h,j;const r=[],n=t.machineName,a=t.connectionState,o=Pp(e),c=e.workspace||"",l=rf(e.type,{agentName:e.cliName}),d=et(e)||Xe(e)?l:at(e.type),f=Array.isArray(e.childSessions)?e.childSessions.map(x=>{var b,v;return{sessionId:x.id,instanceId:x.id,providerSessionId:x.providerSessionId,transport:x.transport,sessionCapabilities:x.capabilities,agentType:x.providerType,agentName:x.providerName||at(x.providerType),status:x.status,title:x.title,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,messages:((b=x.activeChat)==null?void 0:b.messages)||[],activeModal:((v=x.activeChat)==null?void 0:v.activeModal)||void 0,unread:x.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,surfaceHidden:x.surfaceHidden,git:x.git}}):[],u=_p(e);if(u){const x=e.sessionId||e.instanceId,b=l,v=(p=e.activeChat)==null?void 0:p.activeModal,A=v&&Array.isArray(v.buttons)&&v.buttons.length>0,g=yt((m=e.activeChat)==null?void 0:m.status,{activeModal:(y=e.activeChat)==null?void 0:y.activeModal})||yt((h=(N=e.agents)==null?void 0:N[0])==null?void 0:h.status)||"idle",M=e.activeChat||{title:"",messages:[]};let T=M.title&&String(M.title).trim()?String(M.title).trim():"";const k=(j=e.activeChat)==null?void 0:j.id,w=e.chats;if(k&&Array.isArray(w)&&w.length>0){const O=w.find(U=>U.id===k||U.id&&String(U.id)===String(k));O!=null&&O.title&&String(O.title).trim()&&(T=String(O.title).trim())}const K=(et(e)||Xe(e),e.type),R=(et(e)||Xe(e))&&Eo(T,b,K)?"":T,S=M.messages||[];r.push({routeId:e.id,sessionId:x,providerSessionId:e.providerSessionId,nativeSessionId:x,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:et(e)?e.mode||"terminal":"chat",agentName:b,agentType:K,status:g,title:R,messages:S,resume:e.resume,hostIdeType:!et(e)&&!Xe(e)?e.type:void 0,workspaceName:o,workspacePath:c,git:e.git,displayPrimary:R||o||(et(e)?e.mode==="chat"?b:"Terminal":b),displaySecondary: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?v.buttons:void 0,modalMessage:A?v.message:void 0,streamSource:"native",tabKey:In(x,e.id),machineName:n,connectionState:a})}if(u&&(et(e)||Xe(e)))return r;for(const x of f){const b=x.activeModal&&Array.isArray(x.activeModal.buttons)&&x.activeModal.buttons.length>0,v=nf(x),A=Dp(x),g=`${e.id}:${A}`,M=x.title&&String(x.title).trim()||"",T=Eo(M,x.agentName,x.agentType)?"":M,k=x.messages||[];(x.transport==="cdp-webview"||x.sessionId||x.providerSessionId||k.length>0||b||T||!["idle","panel_hidden","disconnected","not_monitored"].includes(v))&&r.push({routeId:e.id,sessionId:x.sessionId||x.instanceId,providerSessionId:x.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:x.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:x.sessionCapabilities,mode:"chat",agentName:x.agentName,agentType:x.agentType,status:v,title:T,messages:k,hostIdeType:e.type,workspaceName:o,workspacePath:c,git:x.git||e.git,displayPrimary:T||o||x.agentName||d,displaySecondary:`${d} · ${x.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,lastUpdated:x.lastUpdated||e.lastUpdated,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,modalButtons:b?x.activeModal.buttons:void 0,modalMessage:b?x.activeModal.message:void 0,streamSource:"agent-stream",tabKey:In(x.sessionId||x.instanceId,g),machineName:n,connectionState:a})}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:l,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:c,git:e.git,displayPrimary:o||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:In(e.sessionId||e.instanceId,e.id),connectionState:a}),r}function $p(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 Jc(e,t){const r=$p(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Qc=[{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:"🏄"}],Zc=[{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:"🧩"}],el=[{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:"🟠"}],Bp=Qc,Kp=Zc,Op=el;function ms(...e){return kd(Sd(e))}function Wp({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:ms("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 tl({icon:e,title:t,subtitle:r,badge:n,actions:a,widthClassName:o="max-w-6xl",contentClassName:c,children:l}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(Wp,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:ms("mx-auto flex w-full flex-col gap-4",o,c),children:l})})]})}const ja="adhdev:themechange";function Fp(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function ys(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function vs(e){return e==="system"?Fp():e}function sl(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Br(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(ja,{detail:{preference:e,theme:t}}))}function Hp(){const e=ys(),t=vs(e);sl(t),Br(e,t)}function ao(){const[e,t]=i.useState(ys),[r,n]=i.useState(()=>vs(ys()));i.useEffect(()=>{sl(r)},[r]),i.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=d=>{if(e==="system"){const f=d.matches?"light":"dark";n(f),Br("system",f)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),i.useEffect(()=>{const c=d=>{const f=d.detail||{},u=f.preference,p=f.theme;t(u==="dark"||u==="light"||u==="system"?u:ys()),n(p==="dark"||p==="light"?p:vs(ys()))},l=d=>{if(d.key!=="theme")return;const f=ys(),u=vs(f);t(f),n(u)};return window.addEventListener(ja,c),window.addEventListener("storage",l),()=>{window.removeEventListener(ja,c),window.removeEventListener("storage",l)}},[]);const a=i.useCallback(c=>{const l=vs(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Br(c,l)},[]),o=i.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",d=vs(l);n(d);try{localStorage.setItem("theme",l)}catch{}return Br(l,d),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const ti={dark:"Dark",light:"Light",system:"System"};function Up({collapsed:e}){const{preference:t,cycleTheme:r}=ao(),n=t==="dark"?s.jsx(uu,{size:16}):t==="light"?s.jsx(du,{size:16}):s.jsx(fu,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${ti[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:ti[t]})]})}function Ln(e,t){return e?typeof e=="function"?e(t):e:null}function zp({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:c,preMainContent:l,collapsedStorageKey:d="sidebar-collapsed"}){const[f,u]=i.useState(!1),[p,m]=i.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),y=()=>u(!0),N=()=>u(!1),h=()=>{m(v=>{const A=!v;try{localStorage.setItem(d,A?"1":"0")}catch{}return A})},j=i.useMemo(()=>({collapsed:p,mobileMenuOpen:f,openMobileMenu:y,closeMobileMenu:N,toggleCollapsed:h}),[p,f]),x=v=>`nav-item${v.active?" active":""} cursor-pointer ${p?"justify-center py-2.5 px-0":""}${v.className?` ${v.className}`:""}`,b=v=>s.jsxs("div",{className:x(v),id:`nav-${v.id}`,onClick:()=>{v.onSelect(),N()},title:p?v.title??(typeof v.label=="string"?v.label:void 0):v.title,children:[s.jsx("span",{className:"nav-icon",children:v.icon}),!p&&v.label]},v.id);return s.jsxs("div",{className:`app-layout${f?" mobile-menu-open":""}${p?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:y,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),f&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:N,onKeyDown:v=>v.key==="Escape"&&N()}),s.jsxs("aside",{className:`sidebar ${f?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${p?"justify-center gap-0":""}`,children:Ln(t,j)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:N,children:s.jsx(St,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(b)}),n.map(v=>s.jsxs("div",{className:v.className??"border-t border-border-subtle pt-2 mt-2",children:[!p&&v.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:v.title}):null,v.items.map(b)]},v.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(b),Ln(o,j),s.jsx(Up,{collapsed:p}),Ln(c,j)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function Nt({title:e,icon:t,description:r,accentColor:n,className:a,children:o}){return s.jsxs("div",{className:ms("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 rl({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:ms("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 Vp={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"},Gp={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Cr({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:ms("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Vp[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Gp[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:"✕"})]})}const qp={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"},Yp={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Xp({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:ms("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",qp[e],r),children:[s.jsx("span",{className:ms("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Yp[e])}),n]})}function Zt({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 Jp({onPrefChange:e}){const[t,r]=hf(),[n,a]=i.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);i.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const o=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(cn,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:c=>o("globalEnabled",c)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Tt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:c=>o("browserNotifications",c)}),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:()=>{mc().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(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(mu,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>o("completionAlert",c)}),s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(pu,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>o("approvalAlert",c)}),s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ar,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:c=>o("disconnectAlert",c)})]}),!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 sn(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Qp(e,t){const r=sn(e),n=sn(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 nl(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function Zs(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||Qp(r,t)>=0)return!1;const n=sn(r),a=sn(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Zp(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Rn(e,t){return e instanceof Error?e.message:t}function eh({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const o=e.filter(c=>c.type==="adhdev-daemon");return o.length===0?s.jsx(rl,{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(c=>s.jsx(sh,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function si({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:o}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return sr.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:l=>l.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 ${c}`,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 th(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Bp,...Kp,...Op].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 sh({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var U,P;const[o,c]=i.useState("idle"),[l,d]=i.useState(""),[f,u]=i.useState(null),[p,m]=i.useState("idle"),[y,N]=i.useState(""),h=e.version||null,j=((U=e.machine)==null?void 0:U.platform)||((P=e.system)==null?void 0:P.platform)||"",x=Ct(e,{fallbackId:e.id}),b=j==="win32"?"🪟":j==="darwin"?"🍎":"🐧",v=t.filter(C=>C.daemonId===e.id&&C.transport==="cdp-page"),A=t.filter(C=>C.daemonId===e.id&&C.transport==="pty"),g=t.filter(C=>C.daemonId===e.id&&C.transport==="acp"),M=e.p2p,T=async()=>{if(r){c("upgrading"),d("Starting upgrade...");try{const C=Zp(await r(e.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),d(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),d(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),d(C.error||"Upgrade failed"))}catch(C){c("error"),d(Rn(C,"Connection lost during upgrade"))}}},k=async()=>{if(u(null),!!n){m("loading");try{await n(e.id),m("done"),N("Machine disconnected.")}catch(C){m("error"),N(Rn(C,"Failed to disconnect"))}}},w=async()=>{if(u(null),!!a){m("loading");try{await a(e.id),m("done"),N("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(C){m("error"),N(Rn(C,"Failed to revoke token"))}}},K="0.9.59",R=nl(e,K),S=Zs(e,K),O=v.length+A.length+g.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:b}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:x}),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),"…"]}),h&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${R?"":"bg-bg-secondary"}`,style:R?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",h,!R&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&R&&s.jsx("button",{onClick:T,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${K}`,children:o==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${S?"↑ Update now":`↑ Update${` to v${K}`}`}`}),n&&s.jsx("button",{onClick:()=>u("disconnect"),disabled:p==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>u("revoke"),disabled:p==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(Xp,{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:[M&&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 ${M.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${M.state==="connecting"||M.state==="new"?"animate-pulse":""}`,style:M.state==="connecting"||M.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",M.state==="connected"?"connected":M.state==="connecting"||M.state==="new"?"connecting...":M.state||"off"]}),M.peers!==void 0&&M.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",M.peers," peer",M.peers!==1?"s":"",")"]})]}),M&&O>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),O>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[v.map(C=>{const I=th(C.type),W=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:I.icon}),s.jsx("span",{children:I.name}),W!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${W?"bg-green-400":"animate-pulse"}`,style:W?void 0:{background:"var(--status-warning)"},title:W?"CDP connected":"CDP connecting..."})]},C.id)}),A.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)),g.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"})]}),(l||y)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||p==="error"?"text-red-400":o==="done"||p==="done"?"text-green-400":"text-text-muted"}`,children:y||l})]}),f==="disconnect"&&s.jsx(si,{title:"🔌 Disconnect Machine",message:`Disconnect "${x}" from ADHDev?
40
+ `).includes(a)))}function Np(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 Vc(e,t={}){return Np(Sp(e,t),t.sortMode||"recent")}function tn(e){return e?"Resume saved history":"Start fresh"}function Za(e){return e?"Resuming saved history…":"Starting fresh…"}function Cp(){return"Start fresh"}function Gc(e,t=!1){return e==="cli"?tn(t):e==="ide"?"Start IDE":"Start ACP session"}function qc(e,t=!1){return e==="cli"?Za(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Tp(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Mp(){return"Open saved history"}function Ap(){return"Saved History"}function eo(){return"Use saved history when you want continuity in the same provider conversation."}function Ip(){return"No saved history found yet."}function Lp(){return"Refresh saved history"}function Rp(){return"Refreshing saved history…"}function ns(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function as(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 Ls(e){return e==="start-fresh"?"Start fresh":"Restart"}function Rs(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function to(e){return`Resume saved history with ${e}?`}function so(){return"Review or change the target workspace before resuming saved history."}function _p(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 ro({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:f,onClose:u,onNewChat:p,onSwitchSession:m,onRefreshHistory:y,onResumeSavedSession:N}){var R;const h=t.find(S=>S.id===e.routeId),j=(h==null?void 0:h.chats)||[],x=(R=h==null?void 0:h.activeChat)==null?void 0:R.id,b=et(e)&&!Xe(e),[v,A]=i.useState(()=>xt()),g=l||v,M=String(d||"").trim(),T=S=>{if(f){f(S);return}A(S)},k=i.useMemo(()=>a.map(S=>{const O=String(S.workspace||"").trim();return S.canResume||O||!M?S:{...S,workspace:M,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[M,a]),w=i.useMemo(()=>Vc(k,{textQuery:g.textQuery,workspaceQuery:g.workspaceQuery,modelQuery:g.modelQuery,resumableOnly:g.resumableOnly,sortMode:g.sortMode}),[k,g.modelQuery,g.resumableOnly,g.sortMode,g.textQuery,g.workspaceQuery]),K=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:b?Ap():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:dp(e)}),b&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:eo()})]}),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(St,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!b&&s.jsx("button",{onClick:p,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),b?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:g.textQuery,onChange:S=>T({...g,textQuery:S.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:g.workspaceQuery,onChange:S=>T({...g,workspaceQuery:S.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:g.modelQuery,onChange:S=>T({...g,modelQuery:S.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:g.sortMode,onChange:S=>T({...g,sortMode:S.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:g.resumableOnly,onChange:S=>T({...g,resumableOnly:S.target.checked})}),"Resume-ready only"]})]}),w.map(S=>{const O=e.providerSessionId===S.providerSessionId,H=O||!S.canResume||!!c,P=S.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{H||!N||N(S)},disabled:H,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${O?"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 ${O?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:S.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:S.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:_p(S.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:S.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:[S.workspace||"Workspace unknown",P?" · selected workspace":"",fs(S.summaryMetadata)?` · ${fs(S.summaryMetadata)}`:"",S.messageCount>0?` · ${S.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:O?"ACTIVE":S.canResume?P?"RESUME IN SELECTED WORKSPACE":c===S.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},S.id)})]}):j.map(S=>s.jsxs("div",{onClick:()=>{m(e.routeId,S.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${x===S.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${x===S.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:S.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:[S.id.substring(0,12),"..."]}),x===S.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},S.id)),(b&&!o&&w.length===0||!b&&j.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(du,{size:32})}),s.jsx("div",{className:"text-[13px]",children:b?a.length>0?"No saved history matches these filters.":Ip():"No recent chat sessions found."})]}),b&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Rp()})})]}),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:y,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(lr,{size:13})," ",b?Lp():"Refresh History"]})})})]})]});return typeof document>"u"?K:sr.createPortal(K,document.body)}const ei={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 Yc({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=ei[n.type]||ei.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(St,{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,c)=>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:l=>{l.stopPropagation(),o.onClick(),t(n.id)},children:o.label},c))})]})]},n.id)})})}const Pp=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Dp(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function Ep(e){return e.sessionId||e.instanceId||e.agentType}function In(e,t){return e||t}function Xc(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Ct(r,{fallbackId:r.id}));return t}function Jc(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 no(e,t={}){return $p(e,Jc(e,t))}function $p(e,t={}){var p,m,y,N,h,j;const r=[],n=t.machineName,a=t.connectionState,o=Dp(e),c=e.workspace||"",l=nf(e.type,{agentName:e.cliName}),d=et(e)||Xe(e)?l:at(e.type),f=Array.isArray(e.childSessions)?e.childSessions.map(x=>{var b,v;return{sessionId:x.id,instanceId:x.id,providerSessionId:x.providerSessionId,transport:x.transport,sessionCapabilities:x.capabilities,agentType:x.providerType,agentName:x.providerName||at(x.providerType),status:x.status,title:x.title,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,messages:((b=x.activeChat)==null?void 0:b.messages)||[],activeModal:((v=x.activeChat)==null?void 0:v.activeModal)||void 0,unread:x.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,surfaceHidden:x.surfaceHidden,git:x.git}}):[],u=Pp(e);if(u){const x=e.sessionId||e.instanceId,b=l,v=(p=e.activeChat)==null?void 0:p.activeModal,A=v&&Array.isArray(v.buttons)&&v.buttons.length>0,g=yt((m=e.activeChat)==null?void 0:m.status,{activeModal:(y=e.activeChat)==null?void 0:y.activeModal})||yt((h=(N=e.agents)==null?void 0:N[0])==null?void 0:h.status)||"idle",M=e.activeChat||{title:"",messages:[]};let T=M.title&&String(M.title).trim()?String(M.title).trim():"";const k=(j=e.activeChat)==null?void 0:j.id,w=e.chats;if(k&&Array.isArray(w)&&w.length>0){const O=w.find(H=>H.id===k||H.id&&String(H.id)===String(k));O!=null&&O.title&&String(O.title).trim()&&(T=String(O.title).trim())}const K=(et(e)||Xe(e),e.type),R=(et(e)||Xe(e))&&Eo(T,b,K)?"":T,S=M.messages||[];r.push({routeId:e.id,sessionId:x,providerSessionId:e.providerSessionId,nativeSessionId:x,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:et(e)?e.mode||"terminal":"chat",agentName:b,agentType:K,status:g,title:R,messages:S,resume:e.resume,hostIdeType:!et(e)&&!Xe(e)?e.type:void 0,workspaceName:o,workspacePath:c,git:e.git,displayPrimary:R||o||(et(e)?e.mode==="chat"?b:"Terminal":b),displaySecondary: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?v.buttons:void 0,modalMessage:A?v.message:void 0,streamSource:"native",tabKey:In(x,e.id),machineName:n,connectionState:a})}if(u&&(et(e)||Xe(e)))return r;for(const x of f){const b=x.activeModal&&Array.isArray(x.activeModal.buttons)&&x.activeModal.buttons.length>0,v=af(x),A=Ep(x),g=`${e.id}:${A}`,M=x.title&&String(x.title).trim()||"",T=Eo(M,x.agentName,x.agentType)?"":M,k=x.messages||[];(x.transport==="cdp-webview"||x.sessionId||x.providerSessionId||k.length>0||b||T||!["idle","panel_hidden","disconnected","not_monitored"].includes(v))&&r.push({routeId:e.id,sessionId:x.sessionId||x.instanceId,providerSessionId:x.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:x.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:x.sessionCapabilities,mode:"chat",agentName:x.agentName,agentType:x.agentType,status:v,title:T,messages:k,hostIdeType:e.type,workspaceName:o,workspacePath:c,git:x.git||e.git,displayPrimary:T||o||x.agentName||d,displaySecondary:`${d} · ${x.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,lastUpdated:x.lastUpdated||e.lastUpdated,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,modalButtons:b?x.activeModal.buttons:void 0,modalMessage:b?x.activeModal.message:void 0,streamSource:"agent-stream",tabKey:In(x.sessionId||x.instanceId,g),machineName:n,connectionState:a})}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:l,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:c,git:e.git,displayPrimary:o||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:In(e.sessionId||e.instanceId,e.id),connectionState:a}),r}function Bp(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 Qc(e,t){const r=Bp(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Zc=[{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:"🏄"}],el=[{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:"🧩"}],tl=[{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:"🟠"}],Kp=Zc,Op=el,Wp=tl;function ms(...e){return Sd(Nd(e))}function Fp({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:ms("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 sl({icon:e,title:t,subtitle:r,badge:n,actions:a,widthClassName:o="max-w-6xl",contentClassName:c,children:l}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(Fp,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:ms("mx-auto flex w-full flex-col gap-4",o,c),children:l})})]})}const ja="adhdev:themechange";function Hp(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function ys(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function vs(e){return e==="system"?Hp():e}function rl(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Br(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(ja,{detail:{preference:e,theme:t}}))}function Up(){const e=ys(),t=vs(e);rl(t),Br(e,t)}function ao(){const[e,t]=i.useState(ys),[r,n]=i.useState(()=>vs(ys()));i.useEffect(()=>{rl(r)},[r]),i.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=d=>{if(e==="system"){const f=d.matches?"light":"dark";n(f),Br("system",f)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),i.useEffect(()=>{const c=d=>{const f=d.detail||{},u=f.preference,p=f.theme;t(u==="dark"||u==="light"||u==="system"?u:ys()),n(p==="dark"||p==="light"?p:vs(ys()))},l=d=>{if(d.key!=="theme")return;const f=ys(),u=vs(f);t(f),n(u)};return window.addEventListener(ja,c),window.addEventListener("storage",l),()=>{window.removeEventListener(ja,c),window.removeEventListener("storage",l)}},[]);const a=i.useCallback(c=>{const l=vs(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Br(c,l)},[]),o=i.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",d=vs(l);n(d);try{localStorage.setItem("theme",l)}catch{}return Br(l,d),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const ti={dark:"Dark",light:"Light",system:"System"};function zp({collapsed:e}){const{preference:t,cycleTheme:r}=ao(),n=t==="dark"?s.jsx(fu,{size:16}):t==="light"?s.jsx(uu,{size:16}):s.jsx(mu,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${ti[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:ti[t]})]})}function Ln(e,t){return e?typeof e=="function"?e(t):e:null}function Vp({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:c,preMainContent:l,collapsedStorageKey:d="sidebar-collapsed"}){const[f,u]=i.useState(!1),[p,m]=i.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),y=()=>u(!0),N=()=>u(!1),h=()=>{m(v=>{const A=!v;try{localStorage.setItem(d,A?"1":"0")}catch{}return A})},j=i.useMemo(()=>({collapsed:p,mobileMenuOpen:f,openMobileMenu:y,closeMobileMenu:N,toggleCollapsed:h}),[p,f]),x=v=>`nav-item${v.active?" active":""} cursor-pointer ${p?"justify-center py-2.5 px-0":""}${v.className?` ${v.className}`:""}`,b=v=>s.jsxs("div",{className:x(v),id:`nav-${v.id}`,onClick:()=>{v.onSelect(),N()},title:p?v.title??(typeof v.label=="string"?v.label:void 0):v.title,children:[s.jsx("span",{className:"nav-icon",children:v.icon}),!p&&v.label]},v.id);return s.jsxs("div",{className:`app-layout${f?" mobile-menu-open":""}${p?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:y,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),f&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:N,onKeyDown:v=>v.key==="Escape"&&N()}),s.jsxs("aside",{className:`sidebar ${f?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${p?"justify-center gap-0":""}`,children:Ln(t,j)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:N,children:s.jsx(St,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(b)}),n.map(v=>s.jsxs("div",{className:v.className??"border-t border-border-subtle pt-2 mt-2",children:[!p&&v.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:v.title}):null,v.items.map(b)]},v.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(b),Ln(o,j),s.jsx(zp,{collapsed:p}),Ln(c,j)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function Nt({title:e,icon:t,description:r,accentColor:n,className:a,children:o}){return s.jsxs("div",{className:ms("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 nl({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:ms("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 Gp={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"},qp={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Cr({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:ms("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Gp[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:qp[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:"✕"})]})}const Yp={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"},Xp={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Jp({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:ms("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Yp[e],r),children:[s.jsx("span",{className:ms("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Xp[e])}),n]})}function Zt({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 Qp({onPrefChange:e}){const[t,r]=xf(),[n,a]=i.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);i.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const o=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(cn,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:c=>o("globalEnabled",c)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Tt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:c=>o("browserNotifications",c)}),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:()=>{mc().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(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(pu,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>o("completionAlert",c)}),s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(hu,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>o("approvalAlert",c)}),s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ar,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:c=>o("disconnectAlert",c)})]}),!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 sn(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Zp(e,t){const r=sn(e),n=sn(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 al(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function Zs(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||Zp(r,t)>=0)return!1;const n=sn(r),a=sn(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function eh(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Rn(e,t){return e instanceof Error?e.message:t}function th({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const o=e.filter(c=>c.type==="adhdev-daemon");return o.length===0?s.jsx(nl,{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(c=>s.jsx(rh,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function si({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:o}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return sr.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:l=>l.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 ${c}`,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 sh(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Kp,...Op,...Wp].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 rh({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var H,P;const[o,c]=i.useState("idle"),[l,d]=i.useState(""),[f,u]=i.useState(null),[p,m]=i.useState("idle"),[y,N]=i.useState(""),h=e.version||null,j=((H=e.machine)==null?void 0:H.platform)||((P=e.system)==null?void 0:P.platform)||"",x=Ct(e,{fallbackId:e.id}),b=j==="win32"?"🪟":j==="darwin"?"🍎":"🐧",v=t.filter(C=>C.daemonId===e.id&&C.transport==="cdp-page"),A=t.filter(C=>C.daemonId===e.id&&C.transport==="pty"),g=t.filter(C=>C.daemonId===e.id&&C.transport==="acp"),M=e.p2p,T=async()=>{if(r){c("upgrading"),d("Starting upgrade...");try{const C=eh(await r(e.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),d(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),d(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),d(C.error||"Upgrade failed"))}catch(C){c("error"),d(Rn(C,"Connection lost during upgrade"))}}},k=async()=>{if(u(null),!!n){m("loading");try{await n(e.id),m("done"),N("Machine disconnected.")}catch(C){m("error"),N(Rn(C,"Failed to disconnect"))}}},w=async()=>{if(u(null),!!a){m("loading");try{await a(e.id),m("done"),N("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(C){m("error"),N(Rn(C,"Failed to revoke token"))}}},K="0.9.60",R=al(e,K),S=Zs(e,K),O=v.length+A.length+g.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:b}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:x}),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),"…"]}),h&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${R?"":"bg-bg-secondary"}`,style:R?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",h,!R&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&R&&s.jsx("button",{onClick:T,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${K}`,children:o==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${S?"↑ Update now":`↑ Update${` to v${K}`}`}`}),n&&s.jsx("button",{onClick:()=>u("disconnect"),disabled:p==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>u("revoke"),disabled:p==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(Jp,{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:[M&&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 ${M.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${M.state==="connecting"||M.state==="new"?"animate-pulse":""}`,style:M.state==="connecting"||M.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",M.state==="connected"?"connected":M.state==="connecting"||M.state==="new"?"connecting...":M.state||"off"]}),M.peers!==void 0&&M.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",M.peers," peer",M.peers!==1?"s":"",")"]})]}),M&&O>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),O>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[v.map(C=>{const I=sh(C.type),W=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:I.icon}),s.jsx("span",{children:I.name}),W!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${W?"bg-green-400":"animate-pulse"}`,style:W?void 0:{background:"var(--status-warning)"},title:W?"CDP connected":"CDP connecting..."})]},C.id)}),A.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)),g.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"})]}),(l||y)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||p==="error"?"text-red-400":o==="done"||p==="done"?"text-green-400":"text-text-muted"}`,children:y||l})]}),f==="disconnect"&&s.jsx(si,{title:"🔌 Disconnect Machine",message:`Disconnect "${x}" from ADHDev?
41
41
 
42
42
  This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
43
43
 
@@ -48,8 +48,8 @@ This will:
48
48
  • Delete the machine registration
49
49
  • Require restarting ADHDev on that machine
50
50
 
51
- Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:w,onCancel:()=>u(null)})]})}const rh=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function nh(){const{preference:e,setPreference:t}=ao();return s.jsx("div",{className:"flex gap-2",children:rh.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 ah(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 oh(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function _n(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function ri(e){const{r:t,g:r,b:n}=oh(e);return .2126*_n(t)+.7152*_n(r)+.0722*_n(n)}function ni(e,t){const r=ri(e),n=ri(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function al(e){const t=ah(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return ni(t,r)>=ni(t,n)?r:n}const ka={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},Sa={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},ih=[{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"}}}],ol="adhdev-chat-theme",il="adhdev-chat-theme-custom";function Kr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(ol)||"ember"}catch{return"ember"}}function _t(e){try{const t=localStorage.getItem(il);if(t){const r=JSON.parse(t);return{...e==="dark"?ka:Sa,...r[e]}}}catch{}return e==="dark"?ka:Sa}function Tr(e,t){try{localStorage.setItem(il,JSON.stringify({dark:e,light:t}))}catch{}}function Mt(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 rn(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 ch={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function er(e,t){var a;const r=(a=ch[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",rn(r,24)),n.style.setProperty("--accent-on-primary",al(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${rn(r,18)})`),n.style.setProperty("--border-accent",Mt(r,.35)),n.style.setProperty("--nav-active-bg",Mt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Mt(r,.06)}`)}function os(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Mt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Mt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Mt(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",Mt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Mt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",rn(e.accentColor,30)),t.style.setProperty("--accent-on-primary",al(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${rn(e.accentColor,40)})`),t.style.setProperty("--border-accent",Mt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Mt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Mt(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 ${Mt(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 oo(){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 lh(e){try{localStorage.setItem(ol,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=is()?"dark":"light";os(_t(t))}else oo(),er(e,is()?"dark":"light")}function dh(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Kr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=is()?"dark":"light";os(_t(t))}else oo(),er(e,is()?"dark":"light")}function is(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function gt({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 Hs({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 uh({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=i.useState(()=>_t(r));i.useEffect(()=>{a(_t(r))},[r]);const o=i.useCallback((c,l)=>{a(d=>{const f={...d,[c]:l},p=_t(r==="dark"?"light":"dark");return r==="dark"?Tr(f,p):Tr(p,f),os(f),t(f),f})},[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(Hs,{title:"App Background",children:[s.jsx(gt,{label:"Background",value:n.bgPrimary,onChange:c=>o("bgPrimary",c)}),s.jsx(gt,{label:"Surface",value:n.bgSecondary,onChange:c=>o("bgSecondary",c)}),s.jsx(gt,{label:"Card",value:n.surfacePrimary,onChange:c=>o("surfacePrimary",c)})]}),s.jsxs(Hs,{title:"App Text",children:[s.jsx(gt,{label:"Primary",value:n.textPrimary,onChange:c=>o("textPrimary",c)}),s.jsx(gt,{label:"Secondary",value:n.textSecondary,onChange:c=>o("textSecondary",c)}),s.jsx(gt,{label:"Muted",value:n.textMuted,onChange:c=>o("textMuted",c)})]}),s.jsxs(Hs,{title:"Borders & Accent",children:[s.jsx(gt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>o("borderSubtle",c)}),s.jsx(gt,{label:"Border default",value:n.borderDefault,onChange:c=>o("borderDefault",c)}),s.jsx(gt,{label:"Accent",value:n.accentColor,onChange:c=>o("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Hs,{title:"Chat Bubbles",children:[s.jsx(gt,{label:"User bubble",value:n.userBubble,onChange:c=>o("userBubble",c)}),s.jsx(gt,{label:"User text",value:n.userText,onChange:c=>o("userText",c)}),s.jsx(gt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>o("assistantBubble",c)}),s.jsx(gt,{label:"Agent text",value:n.assistantText,onChange:c=>o("assistantText",c)})]}),s.jsxs(Hs,{title:"Chat Layout",children:[s.jsx(gt,{label:"Chat BG",value:n.containerBg,onChange:c=>o("containerBg",c)}),s.jsx(gt,{label:"Send button",value:n.sendButton,onChange:c=>o("sendButton",c)}),s.jsx(gt,{label:"Input border",value:n.inputBorder,onChange:c=>o("inputBorder",c)}),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:c=>o("bubbleRadius",Number(c.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 c=e?ka:Sa,d=_t(e?"light":"dark");e?Tr(c,d):Tr(d,c),a(c),os(c),t(c)},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 fh(){const[e,t]=i.useState(Kr),[r,n]=i.useState(!0),[a,o]=i.useState(()=>_t("dark"));i.useEffect(()=>{n(is());const d=new MutationObserver(()=>{const p=is();n(p);const m=Kr();m==="custom"?os(_t(p?"dark":"light")):er(m,p?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const p=is();n(p);const m=Kr();m==="custom"?os(_t(p?"dark":"light")):er(m,p?"dark":"light")};return f.addEventListener("change",u),()=>{d.disconnect(),f.removeEventListener("change",u)}},[]),i.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?os(_t(r?"dark":"light")):(oo(),er(e,r?"dark":"light"))},[e,r]),i.useEffect(()=>{o(_t(r?"dark":"light"))},[r]);const c=d=>{t(d),lh(d)},l=[...ih,{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:l.map(d=>{const f=e===d.id,u=r?d.preview.dark:d.preview.light,p=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>c(d.id),className:"text-left rounded-xl p-3 transition-all",style:{background:f?"var(--bg-glass-hover)":"var(--bg-glass)",border:f?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:f?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:p},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[f&&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(uh,{dark:r,onColorsChange:d=>o(d)})]})}const io="adhdev_mobileDashboardMode_v1",Na="adhdev:mobile-dashboard-mode-change";function co(){try{return localStorage.getItem(io)==="workspace"?"workspace":"chat"}catch{return"chat"}}function mh(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??co())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==io||t()};return window.addEventListener(Na,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Na,r),window.removeEventListener("storage",n)}}function ph(e){try{localStorage.setItem(io,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Na,{detail:e}))}function hh(){const[e,t]=i.useState(!0);return i.useEffect(()=>{t(co()==="chat")},[]),s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ut,{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),ph(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Pn=new Map,ai=new Map;function xh(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 bh(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 cl(){const{sendCommand:e}=mt(),{injectEntries:t,getIdes:r}=rr();return i.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??mm,c=ai.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<o)return;const l=Pn.get(n);if(l)return l;const d=(async()=>{const f=await e(n,"get_machine_runtime_stats"),u=xh(f);if(!u)return;const p=r().find(y=>y.id===n),m=bh(p,n,u.machine,u.timestamp||Date.now());t([m]),ai.set(n,Date.now())})().finally(()=>{Pn.delete(n)});return Pn.set(n,d),d},[r,t,e])}function gh(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 yh(e,t){const{sendData:r}=mt(),{injectEntries:n,getIdes:a}=rr(),o=Array.from(new Set(e.filter(Boolean))).join("|");i.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const c=o?o.split("|"):[];if(c.length===0)return;const l=c.map(d=>Ht.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const p=a().find(y=>y.id===d),m=gh(p,d,u);n([m])}));return()=>{l.forEach(d=>d())}},[o,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function vh(e,t){const{sendData:r}=mt(),[n,a]=i.useState(null),[o,c]=i.useState(!1);return i.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(t!=null&&t.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const d=Ht.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}:{}}},f=>{l&&(clearTimeout(l),l=null),a(f.diagnostics),c(!1)});return d.initialSendAccepted?l=setTimeout(()=>{c(!1)},bm):c(!1),()=>{l&&clearTimeout(l),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 wh(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function ll(e){const{sendData:t}=mt(),[r,n]=i.useState({});return i.useEffect(()=>{const a=wh(e);if(!a||!e.sessionId||!t){n({});return}const o=Ht.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),Ns.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return o.initialSendAccepted||n({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const dl="adhdev_hiddenTabs";function jh(){try{const e=localStorage.getItem(dl);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function bs(e){try{localStorage.setItem(dl,JSON.stringify([...e]))}catch{}}function Dn(e){return qa(e)}function lo(e,t){return Ss(t).some(r=>e.has(r))}function kh(){const[e,t]=i.useState(jh),r=i.useCallback(f=>{const u=Dn(f);t(p=>{const m=new Set(p);return m.has(u)?m.delete(u):m.add(u),bs(m),m})},[]),n=i.useCallback(f=>{const u=Dn(f);t(p=>{if(p.has(u))return p;const m=new Set(p);return m.add(u),bs(m),m})},[]),a=i.useCallback(f=>{const u=Dn(f);t(p=>{if(!p.has(u))return p;const m=new Set(p);return m.delete(u),bs(m),m})},[]),o=i.useCallback(()=>{t(f=>{if(f.size===0)return f;const u=new Set;return bs(u),u})},[]),c=i.useCallback((f,u)=>{t(p=>{const m=new Set(p);for(const y of u)m.add(y);return bs(m),m})},[]),l=i.useCallback((f,u)=>{t(p=>{const m=new Set(p);for(const y of u)m.delete(y);return bs(m),m})},[]),d=i.useCallback(f=>lo(e,f),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:o,hideAllForDaemon:c,showAllForDaemon:l,isHidden:d}}function ul(e){return e instanceof Error?e.message:String(e||"")}function fl(e){const t=ul(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 ml(e){const t=ul(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function pl({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!et(e)||Xe(e))return;const o=Es(e);if(o===t)return;const c=e.sessionId;c&&a(l=>({...l,[c]:t}));try{await n(xs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Bt(e),mode:t})}catch(l){const d=ml(l);c&&!d&&a(f=>{const u={...f};return o===hl(r,c)?delete u[c]:u[c]=o,u}),fl(l)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",l instanceof Error?l.message:String(l)):console.error("Failed to switch CLI view mode:",l)}}function oi(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 Sh(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=oi(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(d=>oi(d,t)):a.childSessions,l=c!==a.childSessions;return o!==a||l?(r=!0,{...o,...l?{childSessions:c}:{}}):a});return r?n:e}function hl(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 Nh(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))hl(t,a)===o&&(delete n[a],r=!0);return r?n:e}function Ch({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){i.useEffect(()=>{mc()},[]);const a=i.useMemo(()=>e.map(o=>({id:o.tabKey,name:Fc(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return yf(a),i.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{r(l=>{const d=Date.now(),f={};for(const[u,p]of Object.entries(l))d-p<5e3&&(f[u]=p);return Object.keys(f).length===Object.keys(l).length?l:f})},5500);return()=>clearTimeout(c)},[t,r]),i.useEffect(()=>{const o=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const d=l.filter(f=>f.timestamp>c).slice(-100);return d.length===l.length?l:d})},6e4);return()=>clearInterval(o)},[n]),null}function Th(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=r.get(n.id);if(!a){r.set(n.id,n);continue}const o=(a.workspace?1:0)+(a.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>o||(n.timestamp||0)>(a.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function En(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 Mh(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 ii(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Mh(Kt(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 Ah(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||""),ii(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||""),ii(r.activeChat)].join(":"))].join("|")}function Ih(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 Lh(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const o of Ss({routeId:n.routeId}))r.set(o,a);for(const o of Ss({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of Ss({tabKey:n.tabKey}))r.set(o,n)}return r}function Rh(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function _h(e){const t=Rh(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=Kt(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Ph({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=i.useMemo(()=>Th(e),[e]),o=i.useMemo(()=>Yc(e),[e]),c=i.useRef([]),l=i.useRef([]),d=i.useRef([]),f=i.useRef(new Map),u=i.useRef(new Map),p=i.useMemo(()=>{const A=new Map,g=[];for(const w of a){const{connectionState:K="new",machineName:R}=Xc(w,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),S=Ah(w),O=f.current.get(w.id);if(O&&O.ide===w&&O.sourceSignature===S&&O.connectionState===K&&O.machineName===R){A.set(w.id,O),g.push(...O.conversations);continue}const U=no(w,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),P={ide:w,sourceSignature:S,connectionState:K,machineName:R,conversations:U};A.set(w.id,P),g.push(...U)}f.current=A;const M=new Map,T=w=>{const K=_h(w),R=u.current.get(w.tabKey);if(R&&R.signature===K)return M.set(w.tabKey,R),R.timestamp;const S={signature:K,timestamp:Tc(w)||(R==null?void 0:R.timestamp)||0};return M.set(w.tabKey,S),S.timestamp},k=[...g].sort((w,K)=>Mc(w,K,T));return u.current=M,k},[a,t,o]),m=i.useMemo(()=>{const A=Ih(p,r);return En(c.current,A)?c.current:(c.current=A,A)},[p,r]),y=i.useMemo(()=>{const A=new Map,g=Array.from(new Set(m.map(M=>M.routeId)));for(const M of g){const T=Pt(m,M);T&&A.set(M,T)}return A},[m]),N=i.useMemo(()=>{const A=new Map;for(const g of m){const M=y.get(g.routeId),T=g.streamSource==="native"&&M?M:g;for(const k of Ss({providerSessionId:g.providerSessionId,sessionId:g.sessionId}))A.set(k,T)}return A},[m,y]),h=i.useMemo(()=>Lh(m,y),[m,y]),j=i.useCallback(A=>{if(A)return N.get(A)},[N]),x=i.useCallback(A=>{if(A)return h.get(A)},[h]),b=i.useMemo(()=>{const A=m.filter(g=>!lo(n,g));return En(l.current,A)?l.current:(l.current=A,A)},[m,n]),v=i.useMemo(()=>{const A=b.map(g=>g.tabKey);return En(d.current,A)?d.current:(d.current=A,A)},[b]);return{chatIdes:a,conversations:m,visibleConversations:b,visibleTabKeys:v,resolveConversationBySessionId:j,resolveConversationByTarget:x}}function Dh({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=i.useMemo(()=>{var l;return e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),o=i.useMemo(()=>{var l;return!e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),c=i.useCallback(()=>{t&&n(l=>{const d=new URLSearchParams(l);return d.delete("activeTab"),d},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:c}}function Eh({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){i.useEffect(()=>{rt.setIdes(e)},[e]),i.useEffect(()=>{rt.setResolveAction((a,o,c)=>{t(a,o,c).catch(()=>{})})},[t]),i.useEffect(()=>{const a=rt.onToast(o=>{r(l=>l.some(f=>f.message===o.message&&o.timestamp-f.timestamp<3e3)?l:[...l.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const c=o.duration||5e3;setTimeout(()=>r(l=>l.filter(d=>d.id!==o.id)),c)});return()=>{a()}},[r]),i.useEffect(()=>{const a=Kc.on("status_event",o=>{rt.handleRawEvent(o,"ws")});return()=>{a()}},[]),i.useEffect(()=>{var o;const a=c=>{var h;const l=c.data;if((l==null?void 0:l.type)!=="notification_action"||typeof l.action!="string"||!l.action.startsWith("approval_")||!(l.daemonId||l.targetSessionId||l.targetKey))return;const d=l.targetSessionId||l.targetKey||l.daemonId,f=n(d),u=(f==null?void 0:f.routeId)||l.daemonId;if(!u)return;const p=Number(l.buttonIndex),m=l.button||((h=f==null?void 0:f.modalButtons)==null?void 0:h[p])||"Approve",y=String(m).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),N=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(y);t(u,"resolve_action",{action:N?"approve":"reject",button:m,...Number.isFinite(p)&&{buttonIndex:p},...(f==null?void 0:f.sessionId)&&{targetSessionId:f.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(j=>console.error("[SW Action] approval failed:",j))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var c;return(c=navigator.serviceWorker)==null?void 0:c.removeEventListener("message",a)}},[n,t])}const $h="adhdev_dashboardLayout_v1",Bh="adhdev_dashboardDockview_v1",Kh="adhdev_dashboardDockviewHiddenRestore_v1",Us={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function uo(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Oh(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function xl(e){return`${$h}:${e}`}function Wh(e){const t=xl(e);return uo(t,null)}function Fh(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=xl(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function bl(e){return`${Bh}:${e}`}function Hh(e){const t=bl(e);return uo(t,null)}function Uh(e,t){try{const r=bl(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function gl(e){return`${Kh}:${e}`}function zh(e){const t=gl(e);return uo(t,{})}function Vh(e,t){try{const r=gl(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Gh(){return{groupAssignments:[...Us.groupAssignments],focusedGroup:Us.focusedGroup,groupActiveTabIds:{...Us.groupActiveTabIds},groupTabOrders:{...Us.groupTabOrders},groupSizes:[...Us.groupSizes]}}function qh(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Yh(){const[e]=i.useState(()=>Oh(typeof window<"u"?window.innerWidth:1280)),[t,r]=i.useState(()=>new Map),[n,a]=i.useState(0),[o,c]=i.useState({}),[l,d]=i.useState({}),[f,u]=i.useState([]),[p,m]=i.useState(()=>typeof window<"u"&&window.innerWidth<768),[y,N]=i.useState(!1),h=i.useCallback(()=>{if(y)return;const w=Wh(e)??Gh();r(new Map(w.groupAssignments)),a(w.focusedGroup),c(w.groupActiveTabIds),d(w.groupTabOrders),u(w.groupSizes),N(!0)},[y,e]);i.useEffect(()=>{y&&Fh(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:l,groupSizes:f})},[y,e,t,n,o,l,f]),i.useEffect(()=>{const w=window.matchMedia("(max-width: 767px)"),K=R=>m(R.matches);return w.addEventListener("change",K),()=>w.removeEventListener("change",K)},[]);const j=i.useCallback(w=>{r(w)},[]),x=i.useCallback(w=>{a(w)},[]),b=i.useCallback(w=>{c(w)},[]),v=i.useCallback(w=>{d(w)},[]),A=i.useCallback(w=>{u(w)},[]),g=i.useCallback(w=>{x(w)},[x]),M=i.useCallback((w,K)=>{c(R=>(R[w]??null)===(K??null)?R:{...R,[w]:K})},[]),T=i.useCallback((w,K)=>{d(R=>{const S=R[w];return qh(S,K)?R:{...R,[w]:K}})},[]),k=i.useCallback((w,K)=>{const R=K.get(w)??0;return M(R,w),g(R),R},[g,M]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:j,focusedGroup:n,updateFocusedGroup:x,focusGroup:g,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:M,groupTabOrders:l,updateGroupTabOrders:v,setGroupTabOrder:T,groupSizes:f,updateGroupSizes:A,isMobile:p,hasHydratedStoredLayout:y,hydrateStoredLayout:h,focusConversationTab:k}}function Xh(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Ga(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Jh({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:c,setSearchParams:l,historyModalOpen:d,activeConv:f,isRefreshingHistory:u,ides:p,handleRefreshHistory:m}){const y=i.useRef(!1),N=i.useRef(!1),h=i.useRef(null),j=i.useRef(!1);i.useEffect(()=>{if(!e||y.current||t.length===0)return;if(!a){o();return}const x=r(e);x&&(c(x.tabKey,n),y.current=!0,N.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),l(b=>{const v=new URLSearchParams(b);return v.delete("activeTab"),v},{replace:!0}))},[e,t,r,n,a,o,c,l]),i.useEffect(()=>{if(!(N.current||a)&&t.length!==0){if(!e){o(),N.current=!0;return}if(y.current){N.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(N.current||a)&&(o(),N.current=!0)},1500),()=>{h.current!=null&&(window.clearTimeout(h.current),h.current=null)}}},[e,t.length,a,o]),i.useEffect(()=>{if(!d){j.current=!1;return}if(!f||j.current||u)return;const x=p.find(b=>b.id===f.routeId);x&&(!x.chats||x.chats.length===0||Xh(x.chats,f))&&(j.current=!0,m())},[d,f,u,p,m])}function $n(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=Ga(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function yl({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[c,l]=i.useState(!1),[d,f]=i.useState(!1),u=i.useCallback(async N=>{try{await e("standalone","launch_ide",{ideType:N,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),p=i.useCallback(async(N,h)=>{try{const j=N||(t==null?void 0:t.daemonId)||"",x=await e(j,"switch_chat",{id:h,sessionId:h,...ts(t)}),b=x==null?void 0:x.result;if((x==null?void 0:x.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?Ws(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Ws(a,`⚠️ Switch error: ${b}`):Ws(a,"⚠️ Session switch failed")}catch(j){console.error("Switch failed",j),Ws(a,`❌ Switch failed: ${j.message||"connection error"}`)}},[t,e,a]),m=i.useCallback(async()=>{if(!(!t||c)){l(!0);try{const N=Ms(t);await e(N,"new_chat",{...ts(t)}),o(h=>({...h,[t.tabKey]:Date.now()}))}catch(N){console.error("New chat failed",N)}finally{l(!1)}}},[t,c,e,o]),y=i.useCallback(async()=>{var N,h;if(!(!t||d)){f(!0);try{const j=Ms(t),x=async()=>e(j,"list_chats",{forceExpand:!0,...ts(t)});let b=await x(),v=(b==null?void 0:b.chats)||((N=b==null?void 0:b.result)==null?void 0:N.chats);$n(v,t)&&(await new Promise(A=>setTimeout(A,450)),b=await x(),v=(b==null?void 0:b.chats)||((h=b==null?void 0:b.result)==null?void 0:h.chats)),b!=null&&b.success&&Array.isArray(v)&&(n(t.routeId,v),$n(v,t)&&!$n(r,t)&&Ws(a,"⚠️ History dialog did not fully open — try once more"))}catch(j){console.error("Refresh history failed",j)}finally{f(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:p,handleNewChat:m,handleRefreshHistory:y}}function Qh(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 Zh(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function ci(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 Mr(e,t){const r=new Set(t),n=t.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const o=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const d=a[l];typeof d=="number"&&d>0&&o.set(c,d)}return{assignments:o,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function li(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 ex(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 tx(e,t,r){if(t.length<=1)return[];const n=t.map(c=>e[c]).filter(c=>Number.isFinite(c)),a=n.length===t.length?n:Array(r).fill(100/r),o=a.reduce((c,l)=>c+l,0);return o>0?a.map(c=>c/o*100):Array(r).fill(100/r)}function di(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 ui(e){return Array(e).fill(100/e)}function sx({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:c,isMobile:l,visibleConversations:d,visibleTabKeys:f}){const u=i.useRef(null),p=i.useMemo(()=>Mr(e,f),[e,f]),m=p.assignments,y=i.useMemo(()=>l?1:p.groupCount,[p.groupCount,l]),N=y>1,h=i.useCallback((g,M)=>{t(T=>{const k=new Map(Mr(T,f).assignments);return M===0?k.delete(g):k.set(g,M),k}),n(T=>({...T,[M]:g})),r(M)},[t,f,n,r]),j=i.useCallback(g=>{t(M=>{const T=Mr(M,f).assignments,k=new Map;for(const[w,K]of T)K!==g&&(K>g?k.set(w,K-1):k.set(w,K));return k}),c(M=>{if(M.length<=1)return[];const T=[...M];T.splice(g,1);const k=T.reduce((w,K)=>w+K,0);return k>0?T.map(w=>w/k*100):[]}),r(0)},[t,f,c,r]),x=i.useCallback((g,M)=>{M.preventDefault();const T=u.current;if(!T)return;const k=M.clientX,w=T.offsetWidth,K=o.length===y?[...o]:ui(y),R=O=>{const P=(O.clientX-k)/w*100,C=[...K];C[g]=Math.max(15,K[g]+P),C[g+1]=Math.max(15,K[g+1]-P),c(C)},S=()=>{document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",S),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",R),document.addEventListener("mouseup",S)},[o,y,c]),b=i.useCallback((g,M,T)=>{if(y>=4)return;const k=T==="left"?M:M+1;t(w=>{const K=Mr(w,f).assignments,R=new Map;for(const S of d){const O=K.get(S.tabKey)??0,U=O>=k?O+1:O;U>0&&R.set(S.tabKey,U)}return k>0&&R.set(g,k),R}),c(w=>{const K=w.length===y?[...w]:ui(y),R=K[M]??100/y,S=Math.max(15,R/2),O=Math.max(15,R/2),U=[...K];U[M]=S,U.splice(k,0,O);const P=U.reduce((C,I)=>C+I,0);return U.map(C=>C/P*100)}),n(w=>{const K=di(w,k);return K[k]=g,K}),a(w=>{const K=di(w,k);return K[k]=[g],K}),r(k)},[y,t,f,d,c,n,a,r]);i.useEffect(()=>{Qh(e,m)||t(m)},[e,m,t]),i.useEffect(()=>{const{mapping:g,usedGroups:M}=p;n(T=>{const k=li(T,g);return ci(T,k)?T:k}),a(T=>{const k=li(T,g);return ci(T,k)?T:k}),r(T=>{const k=l?0:ex(T,M,g);return T===k?T:k}),c(T=>{const k=l?[]:tx(T,M,p.groupCount);return Zh(T,k)?T:k})},[p,l,n,a,r,c]);const v=i.useMemo(()=>{const g=Array.from({length:y},()=>[]);for(const M of d){const T=m.get(M.tabKey)??0,k=Math.min(T,y-1);g[k].push(M)}return g},[d,m,y]),A=i.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:m,numGroups:y,isSplitMode:N,groupedConvs:v,moveTabToGroup:h,closeGroup:j,handleResizeStart:x,splitTabRelative:b,clearAllSplits:A}}function rx({ides:e,sendDaemonCommand:t}){const r="0.9.59",n=i.useMemo(()=>e.filter(u=>u.type!=="adhdev-daemon"?!1:nl(u,r)).sort((u,p)=>Number(Zs(p,r))-Number(Zs(u,r))),[r,e]),a=i.useMemo(()=>n.some(u=>Zs(u,r)),[r,n]),[o,c]=i.useState(!1),[l,d]=i.useState({}),f=i.useCallback(async u=>{var p,m;d(y=>({...y,[u]:"upgrading"}));try{const y=await t(u,"daemon_upgrade",{});(p=y==null?void 0:y.result)!=null&&p.upgraded||(m=y==null?void 0:y.result)!=null&&m.success?d(N=>({...N,[u]:"done"})):d(N=>({...N,[u]:"error"}))}catch{d(y=>({...y,[u]:"error"}))}},[t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:o,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:f}}const vl=80;function Or(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function nx(e){return{...e,createdAt:Or(e.createdAt),updatedAt:Or(e.updatedAt,e.createdAt),lastEventAt:Or(e.lastEventAt,e.updatedAt||e.createdAt)}}function ax(e){const t=qa(e);return t==="unknown:"?e.id:t}function ox(e){return[e.type,Cc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function ix(e,t=vl){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=ax(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 cx(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 c=dn(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const d=Or(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),f=ox({type:l,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(nx({id:f,dedupKey:f,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:gc(a),preview:Uf(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return ix(n)}function lx(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function dx(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=vl}=e,a=i.useMemo(()=>cx(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=i.useMemo(()=>lx(a),[a]);return{notifications:a,unreadCount:o}}function ux({notifications:e,sendDaemonCommand:t}){const r=i.useCallback(o=>{const c=e.find(d=>d.id===o),l=Math.max(Date.now(),(c==null?void 0:c.updatedAt)||0);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_session_seen",{sessionId:c.sessionId,seenAt:l}).catch(()=>{})},[e,t]),n=i.useCallback(o=>{const c=e.find(l=>l.id===o);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_notification_unread",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]),a=i.useCallback(o=>{const c=e.find(l=>l.id===o);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"delete_notification",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}function pn(...e){const t=new Set,r=[],n=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const c=o.toLowerCase();t.has(c)||(t.add(c),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 fx(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 hn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=fx(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 mx(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 px(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function xn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=px(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,c=o.includes("\\")?"\\":"/",l=(f,u)=>/^[A-Za-z]:\\?$/.test(f)?`${f.replace(/\\?$/,"\\")}${u}`:f==="/"||f==="\\"?`${c}${u}`:`${f.replace(/[\\/]+$/,"")}${c}${u}`,d=Array.isArray(a==null?void 0:a.files)?a.files.filter(f=>(f==null?void 0:f.type)==="directory"&&typeof(f==null?void 0:f.name)=="string").map(f=>({name:f.name,path:typeof(f==null?void 0:f.path)=="string"&&f.path.trim()?f.path:l(o,f.name)})).sort((f,u)=>f.name.localeCompare(u.name)):[];return{path:o,directories:d}}function hx(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function fi(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function xx(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function bx({ides:e,conversations:t,onOpenSession:r}){const[n,a]=i.useState(null),o=i.useCallback(c=>{a(c)},[]);return i.useEffect(()=>{if(!n)return;const c=fi(n.workspacePath),l=e.find(f=>{var N,h,j,x;if(!f||f.type==="adhdev-daemon"||hx(f.daemonId||f.id)!==n.machineId||(or(f)?"cli":js(f)?"acp":"ide")!==n.kind||String(f.agentType||f.type||"")!==n.providerType)return!1;if(n.resumeSessionId)return String(f.providerSessionId||"")===n.resumeSessionId;if(c){const b=fi(f.workspace||f.runtimeWorkspaceLabel);return b?b===c:!1}return Number(f.lastUpdated||f._lastUpdate||f.timestamp||((x=(j=(h=(N=f.activeChat)==null?void 0:N.messages)==null?void 0:h.at)==null?void 0:j.call(h,-1))==null?void 0:x.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const d=Ac({entrySessionId:l.sessionId,entryInstanceId:l.instanceId,entryRouteId:l.id,conversations:t});d&&(a(null),r(d))},[t,e,r,n]),i.useEffect(()=>{if(!n)return;const c=window.setTimeout(()=>{a(l=>!l||l.startedAt!==n.startedAt?l:null)},45e3);return()=>window.clearTimeout(c)},[n]),{trackPendingLaunch:o}}function gx({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const c=i.useCallback(async(m,y)=>xn(e,m,y),[e]),l=i.useCallback(async(m,y)=>{if(!y.trim())return{ok:!1,error:"Choose a workspace path first."};try{const N=await e(m,"workspace_add",{path:y.trim()});return N!=null&&N.success?{ok:!0}:{ok:!1,error:(N==null?void 0:N.error)||"Could not save workspace"}}catch(N){return{ok:!1,error:N instanceof Error?N.message:"Could not save workspace"}}},[e]),d=i.useCallback(async(m,y,N)=>{var h;try{const j={ideType:y,enableCdp:!0};(h=N==null?void 0:N.workspacePath)!=null&&h.trim()&&(j.workspace=N.workspacePath.trim());const x=await e(m,"launch_ide",j);return!(x!=null&&x.success)&&(x==null?void 0:x.success)!==void 0?{ok:!1,error:(x==null?void 0:x.error)||"Could not launch IDE"}:(t({machineId:m,kind:"ide",providerType:y,workspacePath:(N==null?void 0:N.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(j){return{ok:!1,error:j instanceof Error?j.message:"Could not launch IDE"}}},[e,t]),f=i.useCallback(async(m,y,N,h)=>{var x,b,v;const j=Date.now();try{const A={cliType:N};(x=h==null?void 0:h.workspacePath)!=null&&x.trim()?A.dir=h.workspacePath.trim():h!=null&&h.workspaceId&&(A.workspaceId=h.workspaceId),(b=h==null?void 0:h.resumeSessionId)!=null&&b.trim()&&(A.resumeSessionId=h.resumeSessionId.trim()),Array.isArray(h==null?void 0:h.cliArgs)&&h.cliArgs.length>0&&(A.cliArgs=h.cliArgs),(v=h==null?void 0:h.initialModel)!=null&&v.trim()&&(A.initialModel=h.initialModel.trim());const g=await e(m,"launch_cli",A),M=(g==null?void 0:g.result)||g,T=(M==null?void 0:M.sessionId)||(M==null?void 0:M.id);return g!=null&&g.success&&T?(r(T),{ok:!0}):g!=null&&g.success?(t({machineId:m,kind:y,providerType:N,workspacePath:(h==null?void 0:h.workspacePath)||null,resumeSessionId:(h==null?void 0:h.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:(g==null?void 0:g.error)||(M==null?void 0:M.error)||`Could not launch ${y.toUpperCase()} session`}}catch(A){return xx(A)?(t({machineId:m,kind:y,providerType:N,workspacePath:(h==null?void 0:h.workspacePath)||null,resumeSessionId:(h==null?void 0:h.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:A instanceof Error?A.message:`Could not launch ${y.toUpperCase()} session`}}},[r,e,t]),u=i.useCallback(async(m,y)=>{if(!m||!y)return[];try{const N=await e(m,"list_saved_sessions",{providerType:y,kind:"cli",limit:30}),h=(N==null?void 0:N.result)??N;return Array.isArray(h==null?void 0:h.sessions)?h.sessions:[]}catch(N){return console.error("List saved sessions failed",N),[]}},[e]),p=i.useCallback(async m=>{await pl({conversation:n,mode:m,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:l,handleLaunchMachineIde:d,handleLaunchMachineProvider:f,handleListMachineSavedSessions:u,setActiveCliViewMode:p}}function yx(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 vx(e,t,r=Date.now()){return!e||!yx(t)?null:{tabKey:e,nonce:r}}function wx({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:c}){const[l,d]=i.useState(null),[f,u]=i.useState(null),p=i.useMemo(()=>{var j,x;if(!e){if(l){const b=t.find(v=>v.tabKey===l);if(b)return b}return r[0]}const h=n[a];if(h){const b=t.find(v=>v.tabKey===h);if(b)return b}return((j=o[a])==null?void 0:j[0])||((x=o[0])==null?void 0:x[0])},[t,l,a,n,o,e,r]),m=i.useCallback(h=>{d(h)},[]),y=i.useCallback(h=>{d(h.tabKey),c(j=>{const x=new URLSearchParams(j),b=Vf(h);return b?x.set("activeTab",b):x.delete("activeTab"),x},{replace:!0})},[c]),N=i.useCallback((h,j)=>{const x=vx(h,j);x&&u(x)},[]);return{activeConv:p,openDesktopConversation:y,requestScrollToBottom:N,scrollToBottomRequest:f,setDesktopActiveTab:m}}function jx(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 kx(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 Sx({activeConv:e,isMobile:t,liveSessionInboxState:r,sendDaemonCommand:n}){const a=i.useRef(null),o=i.useRef(null),c=i.useRef(null),l=i.useRef(null),d=i.useRef(null);i.useEffect(()=>{const f=()=>{c.current&&(clearTimeout(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){f(),a.current=null;return}if(!(e!=null&&e.sessionId)){f(),a.current=null;return}const u=Yr(e,r),p=kx({tabKey:e.tabKey,historySessionId:ur(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:ss(e),liveState:u}),m=p.autoReadKey,y=jx({autoReadKey:m,shouldMarkSeen:p.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!p.shouldMarkSeen){y.shouldCancelPending&&f(),a.current=m;return}if(!y.shouldSchedule)return;y.shouldCancelPending&&f();const N=()=>{if(document.visibilityState!=="visible"||a.current===m)return;a.current=m,o.current=null,c.current=null,l.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const j=p.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:j,completionMarker:p.completionMarker}).catch(()=>{})};if(o.current=y.nextPendingKey,document.visibilityState==="visible"){c.current=setTimeout(N,1500);const j=()=>{document.visibilityState!=="visible"&&c.current&&(clearTimeout(c.current),c.current=null)};d.current=j,document.addEventListener("visibilitychange",j);return}const h=()=>{document.visibilityState==="visible"&&(l.current&&clearTimeout(l.current),l.current=setTimeout(N,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=h,document.addEventListener("visibilitychange",h)},[e,t,r,n]),i.useEffect(()=>()=>{c.current&&clearTimeout(c.current),l.current&&clearTimeout(l.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function Bn(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 Nx({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:c,setClearedTabs:l,setSearchParams:d}){var I;const[f,u]=i.useState(!1),[p,m]=i.useState([]),[y,N]=i.useState(()=>xt()),[h,j]=i.useState(!1),[x,b]=i.useState(null),v=i.useRef(null),A=i.useMemo(()=>r||t||e,[e,r,t]),g=!!A&&et(A)&&!Xe(A),M=i.useMemo(()=>{if(!A||!g)return null;const W=A.daemonId||A.routeId||"",E=Bt(A),$=Bn(A);return`${W}:${E}:${A.providerSessionId||""}:${$}`},[A,g]),T=i.useMemo(()=>!A||!g?"":Bn(A),[A,g]),{isCreatingChat:k,isRefreshingHistory:w,handleSwitchSession:K,handleNewChat:R,handleRefreshHistory:S}=yl({sendDaemonCommand:a,activeConv:A,chats:(I=n.find(W=>W.id===(A==null?void 0:A.routeId)))==null?void 0:I.chats,updateRouteChats:o,setToasts:c,setClearedTabs:l}),O=i.useCallback(()=>{u(!0)},[]),U=i.useCallback(()=>{u(!1)},[]),P=i.useCallback(async()=>{if(!(!A||!g||h)){j(!0);try{const W=A.daemonId||A.routeId,E=Bt(A),$=Bn(A),F=await a(W,"list_saved_sessions",{agentType:E,providerType:E,kind:"cli",limit:50,...A.providerSessionId?{providerSessionId:A.providerSessionId}:{},...$?{workspace:$}:{}}),J=(F==null?void 0:F.result)??F;m(Array.isArray(J==null?void 0:J.sessions)?J.sessions:[])}catch(W){console.error("Refresh saved sessions failed",W),m([])}finally{j(!1)}}},[A,h,g,a]);i.useEffect(()=>{if(!f){v.current=null;return}if(!g){v.current=null,m([]),j(!1);return}!M||h||v.current!==M&&(v.current=M,P())},[P,f,h,g,M]);const C=i.useCallback(async W=>{if(!A||!g||!W.providerSessionId||!W.workspace)return;const E=A.daemonId||A.routeId,$=Bt(A);try{b(W.providerSessionId);const F=await a(E,"launch_cli",{cliType:$,dir:W.workspace,resumeSessionId:W.providerSessionId,initialModel:uc(W.summaryMetadata,"model",{preferShortValue:!0})||void 0}),J=(F==null?void 0:F.result)??F,he=typeof(J==null?void 0:J.sessionId)=="string"?J.sessionId:typeof(J==null?void 0:J.id)=="string"?J.id:"";he&&d(le=>{const te=new URLSearchParams(le);return te.set("activeTab",he),te},{replace:!0}),U()}catch(F){console.error("Resume saved session failed",F)}finally{b(null)}},[U,A,g,a,d]);return{historyModalOpen:f,openHistoryModal:O,closeHistoryModal:U,historyTargetConv:A,isSavedSessionHistoryTarget:g,isHistoryCreatingChat:k,isHistoryRefreshingHistory:w,handleHistorySwitchSession:K,handleHistoryNewChat:R,handleHistoryRefresh:S,savedHistorySessions:p,savedHistoryFilters:y,setSavedHistoryFilters:N,missingWorkspaceResumePath:T,isSavedHistoryLoading:h,resumingSavedHistorySessionId:x,handleRefreshSavedHistory:P,handleResumeSavedHistorySession:C}}function Cx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l}){const[d,f]=i.useState(null),[u,p]=i.useState(null),m=i.useMemo(()=>{if(e||!n)return null;const x=l(n);return x&&!et(x)&&!Xe(x)?x:null},[e,n,l]),y=i.useMemo(()=>{const x=d==null?void 0:d.routeId;if(!x)return null;const b=d!=null&&d.tabKey?o.find(v=>v.tabKey===d.tabKey):a?o.find(v=>v.tabKey===a):null;return(b==null?void 0:b.routeId)===x?b:Pt(o,x)},[o,d,a]),N=i.useMemo(()=>{if(y)return c.find(x=>x.id===y.routeId)},[c,y]);i.useEffect(()=>{m&&(f({routeId:m.routeId,tabKey:Ko(m)}),p(m),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,m]);const h=i.useCallback(x=>{x&&(f({routeId:x.routeId,tabKey:Ko(x)}),p(x))},[]),j=i.useCallback(()=>{f(null),p(null)},[]);return{remoteDialogConv:y,remoteDialogIdeEntry:N,remoteDialogActiveConv:u,setRemoteDialogActiveConv:p,openRemoteDialog:h,closeRemoteDialog:j}}function Tx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l,activeConv:d,sendDaemonCommand:f}){const{remoteDialogConv:u,remoteDialogIdeEntry:p,remoteDialogActiveConv:m,setRemoteDialogActiveConv:y,openRemoteDialog:N,closeRemoteDialog:h}=Cx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l}),[j,x]=i.useState(!1),[b,v]=i.useState(null),A=i.useCallback(async T=>{const k=T||d;!k||!et(k)&&!Xe(k)||(v(k),x(!0))},[d]),g=i.useCallback(()=>{x(!1),v(null)},[]),M=i.useCallback(async T=>{const k=b||d;if(!k||!et(k)&&!Xe(k)){g();return}x(!1);try{const w=Bt(k),K=k.routeId||k.daemonId||"";await f(K,"stop_cli",{cliType:w,targetSessionId:k.sessionId,mode:T})}catch(w){console.error("Stop CLI failed:",w)}finally{v(null)}},[d,g,b,f]);return{remoteDialogConv:u,remoteDialogIdeEntry:p,remoteDialogActiveConv:m,setRemoteDialogActiveConv:y,openRemoteDialog:N,closeRemoteDialog:h,cliStopDialogOpen:j,cliStopTargetConv:b,requestCliStop:A,cancelCliStop:g,confirmCliStop:M}}function Kn(e,t=!0){return(e??!0)&&t}const fo=i.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:c,handleRelaunch:l,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u=null,handleFocusAgent:p,isFocusingAgent:m,actionLogs:y,userName:N,scrollToBottomRequestNonce:h,isInputActive:j=!0,isVisible:x=!0}){const b=n,v=!n,A=Kn(x,b),g=Kn(x,v),M=Kn(x),T=ll(t),k=T.status||T.modalMessage||T.modalButtons?{...t,...T.status?{status:T.status}:{},...T.modalMessage!==void 0?{modalMessage:T.modalMessage}:{},...T.modalButtons!==void 0?{modalButtons:T.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(ic,{activeConv:k,onModalButton:c}),k.transport!=="pty"&&k.transport!=="acp"&&k.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(nr,{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:l,children:"Relaunch with CDP"})]})}):null,k.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:b?"visible":"hidden",pointerEvents:b?"auto":"none"},children:s.jsx(up,{activeConv:k,clearToken:r,terminalRef:o,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u,isVisible:A,isInputActive:j&&A})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:v?"visible":"hidden",pointerEvents:v?"auto":"none"},children:s.jsx(wa,{activeConv:k,ideEntry:a,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u,handleFocusAgent:p,isFocusingAgent:m,actionLogs:y,userName:N,scrollToBottomRequestNonce:h,isInputActive:j&&g,isVisible:g})})]}):s.jsx(wa,{activeConv:k,ideEntry:a,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u,handleFocusAgent:p,isFocusingAgent:m,actionLogs:y,userName:N,scrollToBottomRequestNonce:h,isInputActive:j&&M,isVisible:M})]})},(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 Mx({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:d,onBack:f,onOpenNativeConversation:u,onOpenMachine:p,onOpenHistory:m,onOpenRemote:y,onHideConversation:N,onStopCli:h,cliViewMode:j,onSetCliViewMode:x,handleSendChat:b,handleFocusAgent:v,handleModalButton:A,handleRelaunch:g}){const M=i.useRef(null),T=et(e)&&!t,k=T&&j==="terminal",w=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 ${w} 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:f,type:"button","aria-label":"Back",children:s.jsx(_a,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:it(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(Ic,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>p(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[T&&j&&s.jsx(Qa,{mode:j,onChange:x,compact:!0}),T&&h&&s.jsx("button",{onClick:()=>{h(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(St,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(e),type:"button",children:s.jsx(Pa,{size:14})}),!t&&!T&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>y(e),type:"button",children:s.jsx(Tt,{size:14})}),N&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>N(e),type:"button",title:"Close chat",children:s.jsx(St,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(fo,{activeConv:e,clearToken:0,isCliTerminal:k,ideEntry:n,terminalRef:M,handleModalButton:A,handleRelaunch:g,handleSendChat:b,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:v,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const On={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 Ax(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function wl(){const[e,t]=i.useState("unix"),[r,n]=i.useState("powershell"),[a,o]=i.useState(!1),c=e==="unix"?"unix":r;i.useEffect(()=>{t(Ax())},[]);const l=i.useCallback(()=>{navigator.clipboard.writeText(On[c].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[c]);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:l,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:On[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:On[c].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 jl({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Tt},{key:"chats",label:"Chats",icon:Ut}];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 c=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 ${c?"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:c?{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":c,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{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 Ar({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 gs({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 zs({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 Ir({item:e,type:t,getAvatarText:r,onOpenConversation:n,onHideConversation:a,onCollectChatDebugBundle:o}){const c=t==="needs_attention"||t==="task_complete",l=t==="working",d=t==="earlier",f=t==="task_complete",{isReconnecting:u,isConnecting:p}=Ds(e.conversation),m=it(e.conversation),y=As(e.conversation),N=Wc(e.conversation,{requiresAction:t==="needs_attention"}),h=c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":l?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":d?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",j=c?"bg-accent-primary shadow-glow":l?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":d?"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",x=d?"text-text-secondary":"text-text-primary",b=d?"text-text-muted":"text-text-secondary",v=d?"text-text-secondary opacity-80":"text-text-muted",A=d?"text-text-muted opacity-80":"text-text-muted",g=!l&&!f,M="text-[color:var(--status-warning)]",T=k=>{if(!o)return;k.preventDefault(),k.stopPropagation();const w=o==null?void 0:o(e.conversation);Promise.resolve(w).catch(K=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",K)})};return s.jsxs("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${h}`,children:[s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative ${a?"pb-2":""}`,onClick:()=>n(e.conversation),onContextMenu:T,type:"button",children:[c||l?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.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${j}`,style:c?{color:"var(--accent-on-primary)"}:void 0,children:r(m)}),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 truncate tracking-tight ${x}`,children:m}),g&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${A}`,children:oc(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[s.jsx("span",{className:"truncate",children:y}),s.jsx(Is,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),u?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${M} animate-pulse`,children:"Reconnecting…"})]}):p?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):N==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:M,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${v}`,children:e.preview})]}),c&&!f&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),f&&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"}),l&&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"})]}),a&&s.jsx("div",{className:"flex justify-end px-4 pb-3 -mt-1",children:s.jsxs("button",{type:"button",className:"mobile-inbox-hide-button inline-flex items-center gap-1.5 rounded-full border border-border-subtle bg-bg-primary/70 px-2.5 py-1 text-[11px] font-semibold text-text-muted hover:border-border-default hover:text-text-primary",onClick:k=>{k.preventDefault(),k.stopPropagation(),a(e.conversation)},"aria-label":`Hide ${m}`,title:"Hide conversation",children:[s.jsx(Da,{size:12}),s.jsx("span",{children:"Hide"})]})})]},e.conversation.tabKey)}function mi({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 Ix({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:c,getAvatarText:l,actionLogs:d,sendDaemonCommand:f,onOpenConversation:u,onShowAllHidden:p,onHideConversation:m,onOpenNewSession:y,onOpenMachine:N,onOpenSettings:h,onSectionChange:j,wsStatus:x="connected",isStandalone:b=!1,onCollectChatDebugBundle:v}){const A=x==="disconnected"||x==="reconnecting"||x==="offline"||x==="auth_failed",g=c.length>0,M=t.length>0||r.length>0||n.length>0||a.length>0,T=e==="machines"?"Machines":"Chats",k=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",w=b?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",K=i.useCallback(async S=>{var $;const O=Ms(S);if(!O)return;const U=Array.isArray(S.messages)?S.messages:[],P=kc({activeConv:S,visibleMessages:U,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:U.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),C=await f(O,"get_chat_debug_bundle",{...ts(S),delivery:"daemon_file",frontendSnapshot:P}),I=Qr(C),W=Nc(I);let E=!1;if(($=navigator.clipboard)!=null&&$.writeText&&window.isSecureContext)try{await navigator.clipboard.writeText(W),E=!0}catch(F){console.warn("[chat-debug-bundle] clipboard API failed, trying execCommand fallback",F)}if(!E){let F=null;try{F=document.createElement("textarea"),F.value=W,F.setAttribute("readonly","true"),F.style.cssText="position:fixed;left:-9999px;top:0",document.body.appendChild(F),F.focus(),F.select(),E=document.execCommand("copy")}catch{}finally{F==null||F.remove()}}E||console.warn("[chat-debug-bundle] failed to copy mobile inbox debug bundle locator to clipboard"),rt.showToast(Sc(I,{locatorCopied:E}),E?"success":"warning")},[d,f]),R=v||K;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 ${k}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:T}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||r.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(cn,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:h,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(on,{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] ${w}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:A?s.jsx(zs,{icon:s.jsx(mi,{}),title:x==="offline"?"Network offline":x==="auth_failed"?"Session expired":"Reconnecting",subtitle:x==="offline"?"Waiting for network…":x==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):c.length===0?s.jsx(zs,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:b?"Waiting for your daemon":"Connect your machines",subtitle:b?"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:!b&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(wl,{})})}):s.jsx(gs,{children:c.map((S,O)=>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] ${O>0?"border-t border-border-subtle/70":""}`,onClick:()=>N(S.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:l(S.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:S.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:S.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[S.unread," new"]}):S.total>0?`${S.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:S.subtitle}),S.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[S.total," chat",S.total!==1?"s":"",S.unread>0?` · ${S.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},S.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(Ar,{title:"Needs attention",className:"mb-0"}),s.jsx(gs,{children:t.map((S,O)=>s.jsx("div",{className:O>0?"border-t border-border-subtle/70":"",children:s.jsx(Ir,{item:S,type:"needs_attention",getAvatarText:l,onOpenConversation:u,onHideConversation:m,onCollectChatDebugBundle:R})},S.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(Ar,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(gs,{children:r.map((S,O)=>s.jsx("div",{className:O>0?"border-t border-border-subtle/70":"",children:s.jsx(Ir,{item:S,type:"task_complete",getAvatarText:l,onOpenConversation:u,onHideConversation:m,onCollectChatDebugBundle:R})},S.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(Ar,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(gs,{children:n.map((S,O)=>s.jsx("div",{className:O>0?"border-t border-border-subtle/70":"",children:s.jsx(Ir,{item:S,type:"working",getAvatarText:l,onOpenConversation:u,onHideConversation:m,onCollectChatDebugBundle:R})},S.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(Ar,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(gs,{children:a.map((S,O)=>s.jsx("div",{className:O>0?"border-t border-border-subtle/70":"",children:s.jsx(Ir,{item:S,type:"earlier",getAvatarText:l,onOpenConversation:u,onHideConversation:m,onCollectChatDebugBundle:R})},S.conversation.tabKey))}):M?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):A?s.jsx(zs,{icon:s.jsx(mi,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):g?s.jsx(zs,{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(Ut,{size:20})}),title:"No conversations yet",subtitle:Uc,children:y&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:y,"aria-label":Et,title:Et,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:Et})]})}):s.jsx(zs,{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(gs,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:"Hidden tabs"}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[o.length," collapsed ",o.length===1?"conversation":"conversations"]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:p,children:"Restore all"})]})})})]}),e==="chats"&&y&&M&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:y,"aria-label":Et,title:Et,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"})]})}),s.jsx(jl,{section:e,onSectionChange:j})]})}function Lx(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 kl(e){const t=[e.workspace||"Workspace unknown"],r=fs(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Lx(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function bn({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:o="",confirmLabel:c="Use this folder",onClose:l,onNavigate:d,onConfirm:f}){const[u,p]=i.useState(r);i.useEffect(()=>{p(r)},[r]);const m=mx(r),y=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:l,"aria-label":"Close folder browser",children:s.jsx(St,{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:()=>{!m||a||d(m)},disabled:!m||a,children:[s.jsx(_a,{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:N=>p(N.target.value),onKeyDown:N=>{N.key!=="Enter"||!y||a||(N.preventDefault(),d(y))},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:()=>{!y||a||d(y)},disabled:!y||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(N=>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(N.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(Cs,{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:N.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:N.path})]})]},N.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:l,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>f(y||r),disabled:!y&&!r||a,children:c})]})]})})}function mo({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:d=!1,showArgsInput:f,argsValue:u,onArgsChange:p,showModelInput:m,modelValue:y,onModelChange:N,historyProviderNode:h,onConfirm:j,onCancel:x}){const b=n==null?void 0:n.find(v=>v.key===a);return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:x,"aria-label":"Close launch confirmation",children:s.jsx(St,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),s.jsx("select",{value:a||"",onChange:v=>o(v.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:n.map(v=>s.jsx("option",{value:v.key,children:v.label},v.key))}),(b==null?void 0:b.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:b.description})]}),h,r.map(v=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:v.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:v.value})]},`${v.label}:${v.value}`)),m&&N&&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:y||"",onChange:v=>N(v.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),f&&p&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:u||"",onChange:v=>p(v.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled: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:x,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:j,disabled:d,children:[s.jsx($a,{size:14}),d?l:c]})]})]})})}function pi(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function cs(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?"⭐ ":""}${pi(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const c=(r==null?void 0:r.trim())||"",l=c?(t.workspaces||[]).find(d=>d.path===c):null;if(c&&!l&&o.push({key:`custom:${c}`,label:pi(c),description:c,workspaceId:null,workspacePath:c}),n){const d=`saved:${n}`;if(o.some(f=>f.key===d))return{options:o,selectedKey:d}}return l?{options:o,selectedKey:`saved:${l.id}`}:c?{options:o,selectedKey:`custom:${c}`}:{options:o,selectedKey:"__home__"}}function Rx(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function _x(e){return[Rx(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Px(e){return e.lastLaunchedAt?ln(e.lastLaunchedAt):""}function Sl(e){return{metaText:_x(e),updatedLabel:Px(e)}}function Wn(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function Dx({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var Qe,lt,dt,ut;const c=fr(),[l,d]=i.useState(!1),f=(((Qe=e.detectedIdes)==null?void 0:Qe.length)||0)>0,u=i.useMemo(()=>(e.workspaces||[]).map(Te=>({id:Te.id,path:Te.path,label:Te.label})),[e]),p=e.defaultWorkspaceId||null,[m,y]=i.useState(p||((lt=u[0])==null?void 0:lt.id)||""),[N,h]=i.useState(""),[j,x]=i.useState(""),[b,v]=i.useState([]),[A,g]=i.useState(!1),[M,T]=i.useState(""),[k,w]=i.useState(!1),[K,R]=i.useState(Wn(f,t.length,r.length)),S=i.useRef(null),[O,U]=i.useState(null),P=i.useRef("__home__"),[C,I]=i.useState("__home__"),[W,E]=i.useState(""),[$,F]=i.useState(""),[J,he]=i.useState(""),[le,te]=i.useState([]),[ye,fe]=i.useState(()=>xt().textQuery),[be,X]=i.useState(()=>xt().workspaceQuery),[ae,ge]=i.useState(()=>xt().modelQuery),[ee,de]=i.useState(()=>xt().resumableOnly),[we,ue]=i.useState(()=>xt().sortMode),[xe,se]=i.useState(!1),[ie,re]=i.useState(!1),q=i.useRef(null),Y=i.useRef(null);i.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const ce=m==="__custom__"?N.trim():((dt=u.find(Te=>Te.id===m))==null?void 0:dt.path)||"",ke=m==="__custom__"&&!!ce&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),Z=m!=="__custom__"&&((ut=u.find(Te=>Te.id===m))==null?void 0:ut.path)||"",Se=i.useMemo(()=>(e.recentLaunches||[]).map(Te=>Te.workspace),[e]),Me=i.useCallback(async Te=>{g(!0),T("");try{const Ge=await a(Te);x(Ge.path),h(Ge.path),v(Ge.directories)}catch(Ge){T(Ge instanceof Error?Ge.message:"Could not load folder")}finally{g(!1)}},[a]),We=i.useCallback(()=>{var Ge;y("__custom__"),w(!0);const Te=hn(e.platform,pn(N.trim(),Z,Se,e.defaultWorkspacePath,(Ge=u.find(Ze=>Ze.id===p))==null?void 0:Ge.path,u.map(Ze=>Ze.path)));Me(Te)},[N,p,Me,Se,Z,e.platform,u]),Fe=i.useCallback(Te=>{if(Te!=null&&Te.workspaceId){y(Te.workspaceId),h("");return}if(Te!=null&&Te.workspacePath){y("__custom__"),h(Te.workspacePath);return}y(""),h("")},[]),D=i.useCallback(Te=>{if(y(Te),Te==="__custom__"){We();return}h("")},[We]),Ne=i.useCallback(Te=>{y("__custom__"),h(Te)},[]),Ie=i.useCallback((Te,Ge)=>{S.current=Ge,P.current=Te.selectedWorkspaceKey||"__home__",I(Te.selectedWorkspaceKey||"__home__"),E(Te.initialArgs||""),F(Te.initialModel||""),he(""),te([]);const Ze=Te.providerType?`${e.id}:${Te.providerType}`:null;if(jp(Y.current,Ze)){const qe=xt();fe(qe.textQuery),X(qe.workspaceQuery),ge(qe.modelQuery),de(qe.resumableOnly),ue(qe.sortMode)}Y.current=Ze,U(Te),Te.providerType&&o&&(se(!0),o(Te.providerType).then(qe=>te(qe||[])).catch(qe=>console.warn("Failed to load saved sessions",qe)).finally(()=>se(!1)))},[o,e.id]),Re=i.useMemo(()=>zc(le,{textQuery:ye,workspaceQuery:be,modelQuery:ae,resumableOnly:ee,sortMode:we}),[ae,ee,le,we,ye,be]);i.useEffect(()=>{J&&(Re.some(Te=>Te.providerSessionId===J)||he(""))},[Re,J]);const De=i.useCallback(()=>{S.current&&(re(!0),S.current().finally(()=>{S.current=null,re(!1),U(null)}))},[]),He=i.useCallback(()=>{S.current=null,U(null)},[]),Ue=i.useCallback(Te=>{P.current=Te,I(Te)},[]);return i.useEffect(()=>{var Te;q.current!==e.id&&(q.current=e.id,y(p||((Te=u[0])==null?void 0:Te.id)||"__custom__"),h(""),x(""),v([]),T(""),w(!1),fe(xt().textQuery),X(xt().workspaceQuery),ge(xt().modelQuery),de(xt().resumableOnly),ue(xt().sortMode),Y.current=null,R(Wn(f,t.length,r.length)))},[r.length,t.length,p,f,e.id,u]),i.useEffect(()=>{var Te;m!=="__custom__"&&(m&&u.some(Ge=>Ge.id===m)||y(p||((Te=u[0])==null?void 0:Te.id)||"__custom__"))},[p,m,u]),i.useEffect(()=>{K==="ide"&&f||K==="cli"&&t.length>0||K==="acp"&&r.length>0||R(Wn(f,t.length,r.length))},[K,r.length,t.length,f]),{showAllRecent:l,setShowAllRecent:d,hasIdeOptions:f,workspaceRows:u,defaultWorkspaceId:p,workspaceChoice:m,customWorkspacePath:N,browseCurrentPath:j,browseDirectories:b,browseBusy:A,browseError:M,browseDialogOpen:k,activeLauncherKind:K,launchConfirm:O,launchConfirmWorkspaceKeyRef:P,launchConfirmWorkspaceKey:C,launchConfirmArgs:W,launchConfirmModel:$,launchConfirmResumeId:J,launchConfirmSavedSessions:le,launchConfirmTextFilter:ye,launchConfirmWorkspaceFilter:be,launchConfirmModelFilter:ae,launchConfirmResumableOnly:ee,launchConfirmSortMode:we,filteredLaunchConfirmSavedSessions:Re,launchConfirmSessionsLoading:xe,launchConfirmBusy:ie,resolvedWorkspacePath:ce,canCreateMissingWorkspace:ke,openBrowseDialog:We,loadBrowsePath:Me,handleWorkspaceChoiceChange:D,chooseCustomWorkspacePath:Ne,setCustomWorkspacePath:h,setBrowseDialogOpen:w,setActiveLauncherKind:R,openLaunchConfirm:Ie,handleConfirmLaunch:De,closeLaunchConfirm:He,setWorkspaceSelectionFromOption:Fe,setLaunchConfirmWorkspaceKeyAndSync:Ue,setLaunchConfirmArgs:E,setLaunchConfirmModel:F,setLaunchConfirmResumeId:he,setLaunchConfirmTextFilter:fe,setLaunchConfirmWorkspaceFilter:X,setLaunchConfirmModelFilter:ge,setLaunchConfirmResumableOnly:de,setLaunchConfirmSortMode:ue}}function Ex({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:c,machineAction:l,isStandalone:d,section:f,showBottomNav:u,onBack:p,onSectionChange:m,onOpenConversation:y,onOpenRecent:N,onOpenMachineDetails:h,onMachineUpgrade:j,onLaunchDetectedIde:x,onAddWorkspace:b,onBrowseDirectory:v,onLaunchWorkspaceProvider:A,onListSavedSessions:g}){const M=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",T=r.slice(0,4),k=t.slice(0,3),w=Dx({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:v,onListSavedSessions:g}),K=i.useMemo(()=>T.map(C=>{const{metaText:I,updatedLabel:W}=Sl(C);return{key:`recent-launch:${C.id}`,primary:C.label,secondary:I,updatedLabel:W,onClick:()=>{const{options:E,selectedKey:$}=cs({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspacePath:C.workspace});w.openLaunchConfirm({title:C.kind==="ide"?ns("restart-ide",C.label):C.providerSessionId?to(C.label):ns("start-fresh",C.label),description:C.kind==="ide"?as("restart-ide"):C.providerSessionId?so():as("start-fresh"),confirmLabel:C.kind==="ide"?Ls("restart-ide"):C.providerSessionId?tn(!0):Ls("start-fresh"),busyLabel:C.kind==="ide"?Rs("restart-ide"):C.providerSessionId?Za(!0):Rs("start-fresh"),workspaceOptions:E,selectedWorkspaceKey:$,details:[{label:"Mode",value:M(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const F=E.find(J=>J.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(F),await N({...C,workspace:(F==null?void 0:F.workspacePath)??null})})}}}),[w,N,T]),R=i.useMemo(()=>k.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:it(C.conversation),secondary:ip(C.conversation,{timestampLabel:C.timestamp?oc(C.timestamp):null}),unread:C.unread,onClick:()=>y(C.conversation)})),[y,k]),S=w.showAllRecent?K:K.slice(0,4),O=K.length>0,U=R.length>0,P=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 ${P} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:s.jsx(_a,{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:Ct(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:[U&&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:R.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))})]}),O&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:S.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))}),K.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 ${K.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?"⭐ ":"",un(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(Cs,{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&&b(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:I,selectedKey:W}=cs({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:I,selectedWorkspaceKey:W,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const E=I.find($=>$.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(E),x(C.type,{workspacePath:(E==null?void 0:E.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 I=w.activeLauncherKind==="cli"?"cli":"acp",{options:W,selectedKey:E}=cs({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 ${I.toUpperCase()}`,workspaceOptions:W,selectedWorkspaceKey:E,details:[{label:"Mode",value:I.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:I==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const $=W.find(F=>F.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption($),A(I,C.type,{workspaceId:($==null?void 0:$.workspaceId)??null,workspacePath:($==null?void 0:$.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))})]}),l.message&&s.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.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:()=>b(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:j,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),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:h,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(bn,{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(mo,{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?tn(!!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:eo()}),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:Np()}),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(W=>W.providerSessionId===w.launchConfirmResumeId);if(!C)return null;const I=kl(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:I.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:I.providerSessionId}),s.jsx("div",{className:"mt-1",children:I.metaLine}),I.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:I.updatedLabel}),I.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:I.preview})]})})()]}),onConfirm:w.handleConfirmLaunch,onCancel:w.closeLaunchConfirm}),u&&s.jsx(jl,{section:f,onSectionChange:m})]})}function Wr(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function $x(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:Wr(e)}function Bx(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 Kx(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:fs(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 c,l,d,f,u;const a=or(n)?"cli":js(n)?"acp":"ide",o=fs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(or(n)?n.cliName||n.type:js(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:js(n)?o||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((u=(f=(d=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:d.at)==null?void 0:f.call(d,-1))==null?void 0:u.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Ox(e,t){const r=new Map;for(const n of t){const a=xs(n.conversation),o=r.get(a);o?o.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],o=[...a].sort((p,m)=>m.timestamp-p.timestamp)[0]||null,c=(o==null?void 0:o.conversation)||null,l=fa(n),d=a.filter(p=>p.unread||p.requiresAction).length,f=Bx(n),u=[n.platform||"machine",f].filter(Boolean);return{id:n.id,label:Ct(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:d,total:a.length,latestConversation:c,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:l,preview:c?cp(c):"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,c=a.latestTimestamp||a.fallbackActivityAt||0;return c!==o?c-o:n.label.localeCompare(a.label)})}function Wx(e){return e==="chat"}function Lr(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 Fx({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:f,requestedMachineId:u,onRequestedMachineConsumed:p,requestedMobileSection:m,onRequestedMobileSectionConsumed:y,setSelectedTabKey:N,setScreen:h,setSelectedMachineId:j,setSection:x,setMachineBackTarget:b,resetMachineAction:v}){const A=i.useRef(null),g=i.useCallback(M=>{if(!(M!=null&&M.sessionId))return;const T=Yr(M,c),k=Math.max(Date.now(),ss(M),T.lastUpdated||0);Lr("mark_read:start",{tabKey:M.tabKey,sessionId:M.sessionId,displayPrimary:it(M),inboxBucket:T.inboxBucket,unread:T.unread,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,activityAt:ss(M),readAt:k}),l(xs(M)||M.routeId,"mark_session_seen",{sessionId:M.sessionId,providerSessionId:M.providerSessionId,seenAt:k,completionMarker:T.completionMarker}).then(w=>{Lr("mark_read:result",{tabKey:M.tabKey,sessionId:M.sessionId,result:w})}).catch(w=>{Lr("mark_read:error",{tabKey:M.tabKey,sessionId:M.sessionId,error:w instanceof Error?w.message:String(w)})})},[c,l]);return i.useEffect(()=>{var T;if(!n){Wx(o)&&h("inbox"),N(((T=e[0])==null?void 0:T.tabKey)||null),A.current=null;return}if(o!=="chat"){A.current=null;return}const M=`${n.tabKey}:${n.sessionId||""}`;A.current!==M&&(A.current=M,g(n))},[e,g,o,n,h,N]),i.useEffect(()=>{if(!d)return;const M=e.find(T=>T.tabKey===d);M&&(N(M.tabKey),h("chat"),f==null||f())},[e,f,d,h,N]),i.useEffect(()=>{if(!u)return;const M=t.find(T=>T.id===u);M&&(j(M.id),v(),x("machines"),b("inbox"),h("machine"),p==null||p())},[t,p,u,v,b,h,x,j]),i.useEffect(()=>{m&&(x(m),h("inbox"),y==null||y())},[y,m,h,x]),i.useEffect(()=>{const M=r.filter(T=>T.inboxBucket==="task_complete"||T.unread);M.length!==0&&Lr("inbox_state",{screen:o,selectedTabKey:a,items:M.map(T=>{const k=Yr(T.conversation,c);return{liveState:k,tabKey:T.conversation.tabKey,sessionId:T.conversation.sessionId,displayPrimary:it(T.conversation),serverBucket:k.inboxBucket,computedBucket:T.inboxBucket,serverUnread:k.unread,computedUnread:T.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,activityAt:ss(T.conversation)}})})},[r,c,o,a]),{markConversationRead:g}}function Hx(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function hi(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Ux(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function zx({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,o]=i.useState("idle"),[c,l]=i.useState(""),[d,f]=i.useState(null),u=i.useCallback(()=>{o("idle"),l(""),f(null)},[]),p=i.useCallback(async(b,v,A)=>{var g;try{o("loading"),l(`Launching ${v}…`);const M={ideType:v,enableCdp:!0};(g=A==null?void 0:A.workspacePath)!=null&&g.trim()&&(M.workspace=A.workspacePath.trim()),await e(b,"launch_ide",M),o("done"),l(`${v} launch requested`)}catch(M){o("error"),l(M instanceof Error?M.message:"Launch IDE failed"),console.error("Launch IDE failed",M)}},[e]),m=i.useCallback(async(b,v,A)=>{if(v.trim())try{o("loading"),l(A!=null&&A.createIfMissing?"Creating folder…":"Saving workspace…");const g=await e(b,"workspace_add",{path:v.trim(),createIfMissing:(A==null?void 0:A.createIfMissing)===!0});if(g!=null&&g.success){o("done"),l(A!=null&&A.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}o("error"),l((g==null?void 0:g.error)||"Could not save workspace")}catch(g){o("error"),l(g instanceof Error?g.message:"Could not save workspace")}},[e]),y=i.useCallback(async b=>{var v,A,g,M,T,k;try{o("loading"),l("Starting daemon upgrade…");const w=await e(b,"daemon_upgrade",{});if((v=w==null?void 0:w.result)!=null&&v.alreadyLatest){o("done"),l(`Already on v${((A=w==null?void 0:w.result)==null?void 0:A.version)||"latest"}.`);return}if((g=w==null?void 0:w.result)!=null&&g.upgraded||(M=w==null?void 0:w.result)!=null&&M.success){o("done"),l(`Upgrade to v${((T=w==null?void 0:w.result)==null?void 0:T.version)||"latest"} started. Daemon is restarting…`);return}o("error"),l(((k=w==null?void 0:w.result)==null?void 0:k.error)||"Upgrade failed")}catch(w){o("error"),l(w instanceof Error?w.message:"Upgrade failed")}},[e]),N=i.useCallback(async(b,v,A,g)=>{var k,w,K;const M=Date.now(),T={machineId:b,kind:v,providerType:A,workspaceId:(g==null?void 0:g.workspaceId)||null,workspacePath:(g==null?void 0:g.workspacePath)||null,resumeSessionId:(g==null?void 0:g.resumeSessionId)||null,startedAt:M};try{o("loading"),l(`Launching ${A}…`),f(T);const R={cliType:A};(k=g==null?void 0:g.workspacePath)!=null&&k.trim()?R.dir=g.workspacePath.trim():g!=null&&g.workspaceId&&(R.workspaceId=g.workspaceId),g!=null&&g.resumeSessionId&&(R.resumeSessionId=g.resumeSessionId),(w=g==null?void 0:g.args)!=null&&w.trim()&&(R.cliArgs=g.args.trim().split(/\s+/).filter(Boolean)),(K=g==null?void 0:g.model)!=null&&K.trim()&&(R.initialModel=g.model.trim());const S=await e(b,"launch_cli",R),O=(S==null?void 0:S.result)||S,U=(O==null?void 0:O.sessionId)||(O==null?void 0:O.id);if(S!=null&&S.success&&U){f(null),o("done"),l(`${A} launched`),t(Yt(U));return}if(S!=null&&S.success){o("loading"),l(`${A} launch requested — waiting for session…`);return}f(null),o("error"),l((S==null?void 0:S.error)||(O==null?void 0:O.error)||`Could not launch ${v.toUpperCase()} workspace`)}catch(R){if(Ux(R)){o("loading"),l(`${A} launch requested — waiting for session…`);return}f(null),o("error"),l(R instanceof Error?R.message:`Could not launch ${v.toUpperCase()} workspace`)}},[t,e]),h=i.useCallback(async(b,v)=>{try{const A=await e(b,"list_saved_sessions",{providerType:v,kind:"cli",limit:30}),g=(A==null?void 0:A.result)??A;return Array.isArray(g==null?void 0:g.sessions)?g.sessions:[]}catch(A){return console.error("Failed to list saved sessions on mobile:",A),[]}},[e]),j=i.useCallback(async(b,v)=>xn(e,b,v),[e]);i.useEffect(()=>{if(!d)return;const b=hi(d.workspacePath),v=r.find(g=>{var R,S,O,U;if(!g||g.type==="adhdev-daemon"||Hx(g.daemonId||g.id)!==d.machineId||(g.transport==="acp"?"acp":g.transport==="pty"?"cli":null)!==d.kind||String(g.agentType||g.type||"")!==d.providerType)return!1;const w=String(g.providerSessionId||"");if(d.resumeSessionId&&w)return w===d.resumeSessionId;if(b){const P=hi(g.workspace||g.runtimeWorkspaceLabel);return P?P===b:!1}return Number(g.lastUpdated||g._lastUpdate||g.timestamp||((U=(O=(S=(R=g.activeChat)==null?void 0:R.messages)==null?void 0:S.at)==null?void 0:O.call(S,-1))==null?void 0:U.timestamp)||0)>=d.startedAt-5e3});if(!v)return;const A=Ac({entrySessionId:v.sessionId,entryInstanceId:v.instanceId,entryRouteId:v.id,conversations:n});A&&(f(null),o("done"),l(`${d.providerType} launched`),t(Yt(A)))},[n,r,t,d]),i.useEffect(()=>{if(!d)return;const b=window.setTimeout(()=>{f(v=>!v||v.startedAt!==d.startedAt?v:(o("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(b)},[d]);const x=i.useCallback(async(b,v)=>{if(v.kind==="ide"&&v.providerType){await p(b,v.providerType,{workspacePath:v.workspace||null});return}(v.kind==="cli"||v.kind==="acp")&&v.providerType&&await N(b,v.kind,v.providerType,{workspacePath:v.workspace||null,resumeSessionId:v.providerSessionId||null})},[p,N]);return{machineAction:{state:a,message:c},resetMachineAction:u,handleLaunchDetectedIde:p,handleAddWorkspace:m,handleMachineUpgrade:y,handleLaunchWorkspaceProvider:N,handleListSavedSessions:h,handleBrowseDirectory:j,handleOpenRecent:x}}function Vx({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:c,setSelectedMachineId:l,setSection:d,setMachineBackTarget:f}){const u=i.useCallback(x=>{o(x.tabKey),c("chat"),n(x)},[n,c,o]),p=i.useCallback(x=>{const b=e.find(v=>v.routeId===x.routeId&&v.streamSource==="native");b&&(o(b.tabKey),c("chat"),n(b))},[e,n,c,o]),m=i.useCallback(()=>{n(t),c("inbox")},[n,t,c]),y=i.useCallback((x,b="inbox")=>{l(x),a(),d("machines"),f(b),c("machine")},[a,f,c,d,l]),N=i.useCallback(x=>{const b=xs(x);b&&y(b,"chat")},[y]),h=i.useCallback(()=>{a(),c(r)},[r,a,c]),j=i.useCallback(x=>{d(x),c("inbox")},[c,d]);return{openConversation:u,openNativeConversation:p,backFromConversation:m,openMachine:y,openConversationMachine:N,backFromMachine:h,changeMachineSection:j}}function ps(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function Gx(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function qx({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,userName:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:f,requestedMachineId:u,onRequestedMachineConsumed:p,requestedMobileSection:m,onRequestedMobileSectionConsumed:y,onOpenHistory:N,onOpenRemote:h,onStopCli:j,wsStatus:x,isConnected:b,onShowAllHiddenConversations:v,onHideConversation:A,onOpenNewSession:g,liveSessionInboxState:M,setCliViewModeOverrides:T}){const[k,w]=i.useState(()=>{var Z;return((Z=e[0])==null?void 0:Z.tabKey)||null}),[K,R]=i.useState(()=>e[0]?"chat":"inbox"),[S,O]=i.useState("chats"),[U,P]=i.useState(null),[C,I]=i.useState("inbox"),W=i.useRef([]),E=Ps(),$="0.9.59",F=i.useMemo(()=>e.find(Z=>Z.tabKey===k)||e[0]||null,[e,k]),J=i.useMemo(()=>F?r.find(Z=>Z.id===F.routeId):void 0,[r,F]),he=i.useMemo(()=>!F||Xe(F)||!et(F)?null:Es(F),[F]),le=i.useMemo(()=>r.filter(Z=>Z.type==="adhdev-daemon").sort(Wa),[r]),te=i.useMemo(()=>le.find(Z=>Z.id===U)||null,[le,U]),ye=mn({sendDaemonCommand:a,activeConv:F||void 0,setActionLogs:o,isStandalone:c}),fe=zx({sendDaemonCommand:a,navigate:E,ides:r,conversations:e}),be=i.useMemo(()=>e.map(Z=>{const Se=K==="chat"&&(F==null?void 0:F.tabKey)===Z.tabKey,Me=dn(Z,M,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Se}),We=ss(Z),Fe=Oc(Z);return{conversation:Z,timestamp:We,preview:Fe,unread:Me.unread,requiresAction:Me.requiresAction,isWorking:Me.isWorking,inboxBucket:Me.inboxBucket}}),[e,M,K,F]),{markConversationRead:X}=Fx({conversations:e,machineEntries:le,items:be,selectedConversation:F,selectedTabKey:k,screen:K,liveSessionInboxState:M,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:f,requestedMachineId:u,onRequestedMachineConsumed:p,requestedMobileSection:m,onRequestedMobileSectionConsumed:y,setSelectedTabKey:w,setScreen:R,setSelectedMachineId:P,setSection:O,setMachineBackTarget:I,resetMachineAction:fe.resetMachineAction}),ae=Vx({conversations:e,selectedConversation:F,machineBackTarget:C,markConversationRead:X,resetMachineAction:fe.resetMachineAction,setSelectedTabKey:w,setScreen:R,setSelectedMachineId:P,setSection:O,setMachineBackTarget:I}),ge=i.useMemo(()=>Wr(be.filter(Z=>Z.requiresAction)),[be]),ee=i.useMemo(()=>Wr(be.filter(Z=>Z.unread&&!Z.requiresAction)),[be]),de=i.useMemo(()=>$x(be.filter(Z=>!Z.unread&&!Z.requiresAction&&Z.isWorking),W.current),[be]);i.useEffect(()=>{W.current=de.map(Z=>Z.conversation.tabKey)},[de]);const we=i.useMemo(()=>Wr(be.filter(Z=>!Z.unread&&!Z.requiresAction&&!Z.isWorking)),[be]),ue=i.useMemo(()=>te?be.filter(Z=>xs(Z.conversation)===te.id):[],[be,te]),xe=i.useMemo(()=>Kx(te,r),[r,te]),se=(te==null?void 0:te.version)||null,ie=!!te&&!!se&&!0&&se!==$,re=i.useMemo(()=>(te==null?void 0:te.availableProviders)||[],[te]),q=i.useMemo(()=>re.filter(Z=>ps(Z,"cli")).map(Z=>({type:Z.type,displayName:Z.displayName||Z.type,icon:Z.icon})),[re]),Y=i.useMemo(()=>re.filter(Z=>ps(Z,"acp")).map(Z=>({type:Z.type,displayName:Z.displayName||Z.type,icon:Z.icon})),[re]),ce=i.useMemo(()=>Ox(le,be),[be,le]),ke=i.useCallback(async Z=>{te&&await fe.handleOpenRecent(te.id,Z)},[fe,te]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:K==="chat"&&F?s.jsx(Mx,{selectedConversation:F,isAcp:Xe(F),isStandalone:c,selectedIdeEntry:J,actionLogs:n,userName:l,isSendingChat:ye.isSendingChat,sendFeedbackMessage:ye.sendFeedbackMessage,isFocusingAgent:ye.isFocusingAgent,handleModalButton:ye.handleModalButton,handleRelaunch:ye.handleRelaunch,onBack:ae.backFromConversation,onOpenNativeConversation:ae.openNativeConversation,onOpenMachine:ae.openConversationMachine,onHideConversation:A,onOpenHistory:N,onOpenRemote:h,onStopCli:j,cliViewMode:he,onSetCliViewMode:async Z=>{await pl({conversation:F,mode:Z,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:T})},handleSendChat:ye.handleSendChat,handleFocusAgent:ye.handleFocusAgent}):K==="machine"&&te?s.jsx(Ex,{selectedMachineEntry:te,selectedMachineConversations:ue,selectedMachineRecentLaunches:xe,cliProviders:q,acpProviders:Y,selectedMachineNeedsUpgrade:ie,appVersion:$,machineAction:fe.machineAction,isStandalone:c,section:S,showBottomNav:C==="inbox",onBack:ae.backFromMachine,onSectionChange:ae.changeMachineSection,onOpenConversation:ae.openConversation,onOpenRecent:ke,onOpenMachineDetails:()=>E(`/machines/${te.id}`),onMachineUpgrade:()=>fe.handleMachineUpgrade(te.id),onLaunchDetectedIde:(Z,Se)=>fe.handleLaunchDetectedIde(te.id,Z,Se),onAddWorkspace:(Z,Se)=>fe.handleAddWorkspace(te.id,Z,Se),onBrowseDirectory:Z=>fe.handleBrowseDirectory(te.id,Z),onLaunchWorkspaceProvider:(Z,Se,Me)=>fe.handleLaunchWorkspaceProvider(te.id,Z,Se,Me),onListSavedSessions:Z=>fe.handleListSavedSessions(te.id,Z)}):s.jsx(Ix,{section:S,attentionItems:ge,unreadItems:ee,workingItems:de,completedItems:we,hiddenConversations:t,machineCards:ce,getAvatarText:Gx,actionLogs:n,sendDaemonCommand:a,onOpenConversation:ae.openConversation,onShowAllHidden:v,onHideConversation:A,onOpenNewSession:g,onOpenMachine:ae.openMachine,onOpenSettings:()=>E("/settings"),onSectionChange:O,wsStatus:x,isConnected:b,isStandalone:c})})}function Fn(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function Yx({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const c=i.useRef(0),[l,d]=i.useState(!1),[f,u]=i.useState(null),p=i.useCallback(()=>{c.current=0,d(!1),u(null)},[]);i.useEffect(()=>(window.addEventListener("dragend",p),window.addEventListener("drop",p),()=>{window.removeEventListener("dragend",p),window.removeEventListener("drop",p)}),[p]);const m=i.useCallback(j=>{j.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,d(!0))},[]),y=i.useCallback(j=>{if(!j.dataTransfer.types.includes("text/tab-key"))return;if(j.preventDefault(),!Fn(t,r)){u("merge");return}const x=j.currentTarget.getBoundingClientRect(),b=j.clientX-x.left,v=x.width/3;b<v?u("split-left"):b>v*2?u("split-right"):u("merge")},[t,r]),N=i.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,d(!1),u(null))},[]),h=i.useCallback(j=>{c.current=0,d(!1);const x=j.dataTransfer.getData("text/tab-key"),b=x?e.some(A=>A.tabKey===x):!1,v=f;if(u(null),o(),!!x){if(j.preventDefault(),v==="split-left"&&Fn(t,r)){r==null||r(x,"split-left");return}if(v==="split-right"&&Fn(t,r)){r==null||r(x,"split-right");return}if(b){a(x);return}n==null||n(x)}},[e,f,t,r,n,a,o]);return{dragOver:l,dropAction:f,resetDragState:p,handleDragEnter:m,handleDragOver:y,handleDragLeave:N,handleDrop:h}}function Xx(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 Jx({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,c]=i.useState(t??null),[l,d]=i.useState(r??[]),[f,u]=i.useState(null),p=i.useRef(null),m=i.useRef(null),y=i.useRef(n),N=i.useRef(a);i.useEffect(()=>{y.current=n},[n]),i.useEffect(()=>{N.current=a},[a]),i.useEffect(()=>{t&&t!==o&&c(t)},[t,o]),i.useEffect(()=>{d(T=>{const k=Xx(T,e);return k.length===T.length&&k.every((w,K)=>w===T[K])?T:k})},[e]);const h=i.useMemo(()=>{const T=f??l;if(T.length===0)return e;const k=new Map(T.map((w,K)=>[w,K]));return[...e].sort((w,K)=>{const R=k.get(w.tabKey)??999,S=k.get(K.tabKey)??999;return R-S})},[e,f,l]);i.useEffect(()=>{var k,w;if(h.length===0){o!==null&&(c(null),(k=y.current)==null||k.call(y,null));return}if(o&&h.some(K=>K.tabKey===o))return;const T=h[0].tabKey;T!==o&&(c(T),(w=y.current)==null||w.call(y,T))},[h,o]);const j=i.useMemo(()=>h.find(T=>T.tabKey===o),[h,o]),x=i.useCallback(T=>{var k;c(T),(k=y.current)==null||k.call(y,T)},[]),b=i.useCallback((T,k,w)=>{d(K=>{var U;const R=K.filter(P=>P!==T),S=R.indexOf(k);if(S<0)return K;const O=w==="left"?S:S+1;return R.splice(O,0,T),(U=N.current)==null||U.call(N,R),R}),u(null)},[]),v=i.useCallback((T,k,w)=>{const R=(l.length>0?l:e.map(U=>U.tabKey)).filter(U=>U!==T),S=R.indexOf(k);if(S<0)return;const O=w==="left"?S:S+1;R.splice(O,0,T),p.current=R,u(R)},[l,e]),A=i.useCallback(()=>{var k;const T=p.current;T&&(d(T),(k=N.current)==null||k.call(N,T))},[]),g=i.useCallback(()=>{p.current=null,u(null)},[]),M=i.useCallback(T=>{d(k=>{var K;const w=k.filter(R=>R!==T);return w.push(T),(K=N.current)==null||K.call(N,w),w})},[]);return{activeTabId:o,activeConv:j,sortedConversations:h,previewOrderRef:p,draggingTabRef:m,selectTab:x,handleTabReorder:b,updatePreviewOrder:v,commitPreviewOrder:A,clearPreviewOrder:g,moveTabToEnd:M,setDraggingTabKey:T=>{m.current=T}}}function Qx({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 po({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 c=!r&&!n,l=n&&!!o,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",f=n?Uc: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:f}),l&&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:Et,"aria-label":Et,children:[s.jsx(Zi,{size:14}),s.jsx("span",{children:Et})]})}),c&&s.jsx(wl,{}),c&&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 Nl="adhdev-tab-shortcuts";function Cl(){try{return JSON.parse(localStorage.getItem(Nl)||"{}")}catch{return{}}}function Tl({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,c]=i.useState(()=>Cl()),[l,d]=i.useState(null),f=i.useCallback(p=>{const m=[];return p.metaKey&&m.push(a?"⌘":"Meta"),p.ctrlKey&&m.push("Ctrl"),p.altKey&&m.push(a?"⌥":"Alt"),p.shiftKey&&m.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(m.push(p.key.length===1?p.key.toUpperCase():p.key),m.join("+"))},[a]),u=i.useCallback(p=>{c(p);try{localStorage.setItem(Nl,JSON.stringify(p))}catch{}},[]);return i.useEffect(()=>{if(!e||!l)return;const p=m=>{if(m.preventDefault(),m.stopPropagation(),m.key==="Escape"){d(null);return}const y=f(m);if(!y)return;const N={...o};for(const[h,j]of Object.entries(N))j===y&&delete N[h];N[l]=y,u(N),d(null)};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[e,l,o,u,f]),i.useEffect(()=>{if(!e)return;const p=m=>{if(!(!m.ctrlKey&&!m.metaKey&&!m.altKey)){for(const[y,N]of Object.entries(o))if(t.includes(y)&&f(m)===N){m.preventDefault(),r(),n(y);return}}};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[e,o,t,r,n,f]),{isMac:a,tabShortcuts:o,shortcutListening:l,setShortcutListening:d,saveShortcuts:u}}const Hn=e=>{e.preventDefault()},Zx=i.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:c,draggingTabRef:l,onFocus:d,onSelectTab:f,onConversationActivated:u,onPreviewReorder:p,onReorderTab:m,onCommitPreviewOrder:y,onClearPreviewOrder:N,onDragStateReset:h,onDragTabKeyChange:j,onReceiveTab:x,onOpenContextMenu:b,longPressTimer:v,isGroupActive:A}){const g=Ds(t),M=g.isGenerating?"agent-tab-generating":g.isWaiting?"agent-tab-waiting":"",T=g.isReconnecting,k=i.useCallback(I=>{l.current=t.tabKey,j(t.tabKey),I.dataTransfer.setData("text/tab-key",t.tabKey),I.dataTransfer.effectAllowed="move"},[t.tabKey,l,j]),w=i.useCallback(()=>{l.current=null,j(null),y(),N(),h()},[l,j,y,N,h]),K=i.useCallback(I=>{const W=l.current;if(!(!W||W===t.tabKey)&&I.dataTransfer.types.includes("text/tab-key")){I.preventDefault(),I.stopPropagation();const E=I.currentTarget.getBoundingClientRect(),$=I.clientX<E.left+E.width/2?"left":"right";p(W,t.tabKey,$)}},[t.tabKey,l,p]),R=i.useCallback(I=>{I.preventDefault(),I.stopPropagation();const W=I.dataTransfer.getData("text/tab-key");if(W&&W!==t.tabKey){const E=I.currentTarget.getBoundingClientRect(),$=I.clientX<E.left+E.width/2?"left":"right";c.includes(W)?m(W,t.tabKey,$):x&&x(W)}N()},[t.tabKey,c,m,x,N]),S=i.useCallback(I=>{I.stopPropagation(),d(),f(t.tabKey),u(t)},[t,u,d,f]),O=i.useCallback(I=>{I.preventDefault(),b(I.clientX,I.clientY,t.tabKey)},[t.tabKey,b]),U=i.useCallback(I=>{const W=I.touches[0];v.current=setTimeout(()=>{b(W.clientX,W.clientY,t.tabKey)},600)},[t.tabKey,v,b]),P=i.useCallback(()=>{v.current&&clearTimeout(v.current)},[v]),C=["adhdev-dockview-tab",M,r&&"is-active",A&&"is-group-active",T&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:C,draggable:!0,onDragStart:k,onDragEnd:w,onDragOver:K,onDrop:R,onClick:S,onContextMenu:O,onTouchStart:U,onTouchEnd:P,onTouchMove:P,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:g.isGenerating?s.jsx("div",{className:"tab-spinner"}):g.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):T?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):g.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:it(t),children:it(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[T?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:rs(t)}):g.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[rs(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:rs(t)}),s.jsx(Is,{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 eb({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:f,onCommitPreviewOrder:u,onClearPreviewOrder:p,onDragStateReset:m,onDragTabKeyChange:y,onReceiveTab:N,onHideTab:h,isGroupActive:j,allowTabShortcuts:x=!0}){const[b,v]=i.useState(null),A=i.useRef(null),g=i.useRef(null),M=i.useMemo(()=>e.map(O=>O.tabKey),[e]);dr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(b==null?void 0:b.tabKey)||null});const{isMac:T,tabShortcuts:k,shortcutListening:w,setShortcutListening:K,saveShortcuts:R}=Tl({enabled:x,sortedTabKeys:e.map(O=>O.tabKey),onFocus:o,onSelectTab:c});i.useEffect(()=>{if(!b)return;const O=U=>{const P=document.querySelector("[data-pane-context-menu]");P&&P.contains(U.target)||v(null)};return window.addEventListener("mousedown",O,!0),()=>window.removeEventListener("mousedown",O,!0)},[b]),i.useEffect(()=>{const O=g.current;if(!O)return;const U=P=>{Math.abs(P.deltaY)<=Math.abs(P.deltaX)||(P.preventDefault(),O.scrollLeft+=P.deltaY)};return O.addEventListener("wheel",U,{passive:!1}),()=>O.removeEventListener("wheel",U)},[]);const S=i.useCallback((O,U,P)=>{v({x:O,y:U,tabKey:P})},[]);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:g,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(O=>s.jsx(Zx,{conv:O,isActive:t===O.tabKey,isDraggedTab:a.current===O.tabKey,isTaskCompleteUnread:n.has(O.tabKey),shortcut:x?k[O.tabKey]:void 0,conversationKeys:M,draggingTabRef:a,onFocus:o,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:f,onCommitPreviewOrder:u,onClearPreviewOrder:p,onDragStateReset:m,onDragTabKeyChange:y,onReceiveTab:N,onOpenContextMenu:S,longPressTimer:A,isGroupActive:j},O.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),b&&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:b.x,top:b.y},children:[x&&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:Hn,onClick:O=>{O.stopPropagation(),K(b.tabKey),v(null)},children:["⌨ ",k[b.tabKey]?`Change shortcut (${k[b.tabKey]})`:"Set shortcut"]}),k[b.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:Hn,onClick:()=>{const O={...k};delete O[b.tabKey],R(O),v(null)},children:"✕ Remove shortcut"})]}),h&&s.jsxs(s.Fragment,{children:[x&&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:Hn,onClick:()=>{h(b.tabKey),v(null)},children:"🚫 Hide from Dashboard"})]})]}),x&&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:()=>K(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:O=>O.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. ",T?"⌘+1":"Ctrl+1",", ",T?"⌥+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 tb({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,hasRegisteredMachines:l,userName:d,groupIndex:f,onFocus:u,isSplitMode:p,numGroups:m,onMoveTab:y,onReceiveTab:N,style:h,onActiveTabChange:j,initialActiveTabId:x,initialTabOrder:b,onTabOrderChange:v,onHideTab:A,isFocused:g,allowTabShortcuts:M=!0,onOpenNewSession:T,liveSessionInboxState:k}){const{sendCommand:w}=mt(),K=i.useRef(null),{activeTabId:R,activeConv:S,sortedConversations:O,draggingTabRef:U,selectTab:P,handleTabReorder:C,updatePreviewOrder:I,commitPreviewOrder:W,clearPreviewOrder:E,moveTabToEnd:$,setDraggingTabKey:F}=Jx({conversations:e,initialActiveTabId:x,initialTabOrder:b,onActiveTabChange:j,onTabOrderChange:v}),J=mn({sendDaemonCommand:a,activeConv:S,setActionLogs:o,isStandalone:c}),{dragOver:he,dropAction:le,resetDragState:te,handleDragEnter:ye,handleDragOver:fe,handleDragLeave:be,handleDrop:X}=Yx({conversations:e,numGroups:m,onMoveTab:y,onReceiveTab:N,onOwnTabDrop:$,onClearPreviewOrder:E}),ae=S&&!Xe(S)&&Es(S)==="terminal",ge=i.useMemo(()=>S?t.find(ue=>ue.id===S.routeId):void 0,[t,S]),ee=i.useMemo(()=>S?n.filter(ue=>ue.routeId===S.tabKey):[],[n,S]),de=i.useMemo(()=>new Set(O.filter(ue=>Gu(ue,k,{isOpenConversation:ue.tabKey===R})).map(ue=>ue.tabKey)),[R,k,O]);dr("PaneGroup",{groupIndex:f,conversationCount:e.length,activeTabId:R,dragOver:he});const we=i.useCallback(ue=>{ue.streamSource==="agent-stream"&&ue.agentType&&w(ue.routeId,jc(),{agentType:ue.agentType,...ue.sessionId&&{targetSessionId:ue.sessionId}}).catch(()=>{})},[w]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...h,outline:he?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(eb,{conversations:O,activeTabId:R,groupIndex:f,numGroups:m,unreadTabKeys:de,draggingTabRef:U,onFocus:u,onSelectTab:P,onConversationActivated:we,onPreviewReorder:I,onReorderTab:C,onCommitPreviewOrder:W,onClearPreviewOrder:E,onDragStateReset:te,onDragTabKeyChange:F,onMoveTab:y,onReceiveTab:N,onHideTab:A,isGroupActive:g??!1,allowTabShortcuts:M}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ye,onDragOver:fe,onDragLeave:be,onDrop:X,children:[he&&s.jsx(Qx,{dropAction:le,canSplit:!!(m<4&&y)}),S?s.jsx(fo,{activeConv:S,clearToken:r[S.tabKey]||0,isCliTerminal:!!ae,ideEntry:ge,terminalRef:K,handleModalButton:J.handleModalButton,handleRelaunch:J.handleRelaunch,handleSendChat:J.handleSendChat,isSendingChat:J.isSendingChat,sendFeedbackMessage:J.sendFeedbackMessage,handleFocusAgent:J.handleFocusAgent,isFocusingAgent:J.isFocusingAgent,actionLogs:ee,userName:d,isInputActive:!p||!!g}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(po,{conversationsCount:e.length,isSplitMode:p,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:T})})]})]})}function sb({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:f,isStandalone:u,hasRegisteredMachines:p,userName:m,focusedGroup:y,focusGroup:N,moveTabToGroup:h,splitTabRelative:j,closeGroup:x,handleResizeStart:b,groupActiveTabIds:v,setGroupActiveTab:A,groupTabOrders:g,setGroupTabOrder:M,toggleHiddenTab:T,onOpenNewSession:k,allowTabShortcuts:w=!0,liveSessionInboxState:K}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((R,S)=>{const O=t&&n.length===r?`${n[S]}%`:void 0;return s.jsxs(kt.Fragment,{children:[t&&S>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:U=>b(S-1,U),onDoubleClick:()=>x(S),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(tb,{style:t?{flexBasis:O??`${100/r}%`,flexGrow:O?0:1,flexShrink:O?0:1}:void 0,conversations:R,clearedTabs:o,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:f,isStandalone:u,hasRegisteredMachines:p,userName:m,groupIndex:S,isFocused:t&&y===S,onFocus:()=>N(S),isSplitMode:t,numGroups:r,onMoveTab:(U,P)=>{P==="left"&&S>0?h(U,S-1):P==="right"&&S<r-1?h(U,S+1):P==="split-left"&&r<4?j(U,S,"left"):P==="split-right"&&r<4&&j(U,S,"right")},onReceiveTab:U=>h(U,S),onActiveTabChange:U=>A(S,U),initialActiveTabId:v[S],initialTabOrder:g[S],onTabOrderChange:U=>M(S,U),onHideTab:T,onOpenNewSession:k,allowTabShortcuts:w,liveSessionInboxState:K})]},S)})})}function Ml({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=i.useState(null),[c,l]=i.useState(null);i.useEffect(()=>e?ot.onScreenshot("ide-page",(u,p)=>{if(u!==e)return;const m=new FileReader;m.onload=()=>o(m.result),m.readAsDataURL(p)}):void 0,[e]),i.useEffect(()=>{r!=="connected"&&o(null)},[r]),i.useEffect(()=>{var u;return e?((u=ot.onStatus)==null?void 0:u.call(ot,(p,m)=>{p===e&&m!=null&&m.screenshotUsage&&l(m.screenshotUsage)}))||(()=>{}):void 0},[e]),i.useEffect(()=>{o(null)},[e,t]),i.useEffect(()=>{const f=e?ot.get(e):null;if(!(!f||r!=="connected"))return n!=="chat"&&t?f.startScreenshots(t):f.stopScreenshots(t),()=>{f.stopScreenshots(t)}},[n,r,t,e]);const d=i.useCallback(async(f,u)=>{const p=e?ot.get(e):null;return!p||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):p.sendInput(f,u,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:d}}const Al="adhdev-dashboard-action-shortcuts",rb=1200,nb=[["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 ab(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function st(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 Il(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:st("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:st("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:st("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:st("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:st("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:st("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:st("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:st("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:st("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:st("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:st("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:st("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:st("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:st("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:st("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:st("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:st("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:st("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:st("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:st("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:st("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:st("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:st("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:st("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:st("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:st("toggleCliView",e)}]}function Ca(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function nn(e){const t=Object.fromEntries(Il(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Al)||"{}"),n={...t,...r};for(const[a,o]of nb)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function Ll(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function ob({enabled:e=!0,onTrigger:t}){const r=ab(),[n,a]=i.useState(()=>nn(r)),[o,c]=i.useState(null),[l,d]=i.useState([]),f=i.useRef({parts:[],timer:null}),u=i.useCallback(h=>{const j=[];return h.metaKey&&j.push(r?"⌘":"Meta"),h.ctrlKey&&j.push("Ctrl"),h.altKey&&j.push(r?"⌥":"Alt"),h.shiftKey&&h.key.length!==1&&j.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(j.push(Ll(h.key)),j.join("+"))},[r]),p=i.useCallback(h=>{a(h);try{localStorage.setItem(Al,JSON.stringify(h))}catch{}},[]);i.useEffect(()=>{const h=nn(r),j=Object.entries(n),x=Object.entries(h);j.length===x.length&&j.every(([b,v])=>h[b]===v)||p(h)},[n,r,p]);const m=i.useCallback(()=>{typeof window<"u"&&f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current={parts:[],timer:null}},[]),y=i.useCallback(()=>{typeof window>"u"||(f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current.timer=window.setTimeout(()=>{f.current={parts:[],timer:null}},rb))},[]);i.useEffect(()=>{if(!o)return;const h=j=>{if(j.preventDefault(),j.stopPropagation(),j.key==="Escape"){c(null),d([]);return}const x=u(j);if(!x)return;const v=!(j.metaKey||j.ctrlKey||j.altKey)&&/^[A-Z0-9]$/.test(x);if(l.length===0&&v){d([x]);return}const g=[...l,x].slice(0,2).join(" "),M={...n};for(const[T,k]of Object.entries(M))k===g&&delete M[T];M[o]=g,p(M),c(null),d([])};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[n,u,p,o,l]),i.useEffect(()=>{if(!e||o)return;const h=j=>{if(j.defaultPrevented)return;const x=u(j);if(!x)return;const b=j.metaKey||j.ctrlKey||j.altKey;if(Ca(j.target))return;const v=f.current.parts,A=b?[x]:[...v.slice(-1),x].slice(-2),g=A.join(" "),M=A[A.length-1],T=Object.entries(n).filter(([,S])=>!!S),k=T.find(([,S])=>S===g);if(k){j.preventDefault(),m(),t(k[0]);return}if(T.some(([,S])=>S.startsWith(`${g} `))){j.preventDefault(),f.current.parts=A,y();return}const K=T.find(([,S])=>S===M);if(K){j.preventDefault(),m(),t(K[0]);return}if(T.some(([,S])=>S.startsWith(`${M} `))){j.preventDefault(),f.current.parts=[M],y();return}m()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[n,y,e,u,t,m,o]),i.useEffect(()=>()=>m(),[m]);const N=i.useMemo(()=>Il(r),[r]);return{isMac:r,actionDefinitions:N,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:d,saveShortcuts:p}}function ib({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 Rl(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function xi({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!Rl(n):!0}function cb({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:Rl(r)}const _l=1e3,lb=4;function bi(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function gi(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function db({detachDelayMs:e=_l,stillnessThresholdPx:t=lb,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,c=null,l=null,d=null,f=null,u=!1;const p=()=>{f!=null&&(a(f),f=null)},m=()=>{p(),l=null},y=()=>{p(),o=null,c=null,l=null,d=null,u=!1},N=()=>{!o||!l||!d||u||f!=null||(f=n(()=>{f=null,!(!o||!l||!d||u)&&bi(d,c)&&(gi(l,d,t)||(u=!0,r({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},h=x=>{if(!(!o||u)){if(!bi(x,c)){d={clientX:x.clientX,clientY:x.clientY},m();return}(!l||gi(l,x,t))&&(p(),l={clientX:x.clientX,clientY:x.clientY}),d={clientX:x.clientX,clientY:x.clientY},N()}},j=x=>{!o||u||(x&&(d={clientX:x.clientX,clientY:x.clientY}),m())};return{startDrag:x=>{p(),o=x.panelId,c=x.selfPanelBounds??null,l=null,d={clientX:x.clientX,clientY:x.clientY},u=!1},markSelfPanel:h,markNonSelfPanel:j,markNoDropTarget:j,markDockTarget:j,endDrag:y,isDragging:()=>o!=null,hasDetached:()=>u,dispose:y}}function ub(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}const Pl=i.createContext(null);function gn(){const e=i.useContext(Pl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Fr(e){return it(e)||e.tabKey}function fb(e){return`remote:${e}`}function Lt(e){return e.startsWith("remote:")}function yi(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function mb(e){e.preventDefault()}function Un(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 zn(e,t){e.classList.remove(aa.className,oa.className),e.classList.add(t==="light"?aa.className:oa.className)}function vi(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 pb(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 hb(e,t,r){var c;const n=[t];let a;for(const l of n){let d;for(const f of l){const u=e.addPanel({id:f.tabKey,component:"conversation",title:Fr(f),params:{kind:"conversation",tabKey:f.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??((c=t[0])==null?void 0:c.tabKey)??null}function wi(e,t){const r=new Set(t.map(n=>n.tabKey));for(const n of[...e.panels])Lt(n.id)||r.has(n.id)||e.removePanel(n);for(const n of t){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==Fr(n)&&a.api.setTitle(Fr(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Fr(n),params:{kind:"conversation",tabKey:n.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 ji(e,t,r){var d,f;const n=r?fb(r):null;for(const u of[...e.panels])Lt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=Pt(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),c=Hc(a);if(o){o.title!==c&&o.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((f=e.panels.find(u=>!Lt(u.id)))==null?void 0:f.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function xb({params:e,api:t}){var p;const r=gn(),n=i.useRef(null),[a,o]=i.useState(t.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=mn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});i.useEffect(()=>{o(t.isActive);const m=[t.onDidActiveChange(y=>o(y.isActive)),t.onDidActiveGroupChange(y=>{if(!t.isActive&&!y.isActive){o(!1);return}o(t.isActive)})];return()=>{for(const y of m)y.dispose()}},[t]);const d=i.useMemo(()=>c?r.ides.find(m=>m.id===c.routeId):void 0,[r.ides,c]),f=i.useMemo(()=>c?r.actionLogs.filter(m=>m.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(po,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const u=!Xe(c)&&Es(c)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(fo,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:u,ideEntry:d,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((p=r.scrollToBottomRequest)==null?void 0:p.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:a})})}function bb({params:e}){var d;const t=gn(),r=i.useMemo(()=>Pt([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=i.useMemo(()=>t.ides.find(f=>f.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:c,handleRemoteAction:l}=Ml({doId:a,targetSessionId:r?wc(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:c,transportType:r.transport,onAction:l})}):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 gb(){const e=gn();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(po,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function yb(e){var y,N;pb(e);const t=gn(),r=i.useCallback(h=>{"button"in h&&h.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const h=Pt([...t.conversationsByTabKey.values()],e.params.routeId),j=((y=e.api.group.activePanel)==null?void 0:y.id)===e.api.id,x=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${j?" is-active":""}${x?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(h==null?void 0:h.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:h!=null&&h.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:h.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=((N=e.api.group.activePanel)==null?void 0:N.id)===e.api.id,o=e.api.isGroupActive,c=dn(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,d=c.isConnecting,f=c.isGenerating,u=c.isWaiting,p=c.unread,m=t.tabShortcuts[n.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${o?" is-group-active":""}${l?" is-reconnecting":""}`,title:it(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:h=>{var j;h.preventDefault(),r(h),t.openTabContextMenu({x:h.clientX,y:h.clientY,tabKey:n.tabKey,sourceDocument:((j=h.target)==null?void 0:j.ownerDocument)??document})},children:[p&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:f?s.jsx("div",{className:"tab-spinner"}):u?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?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:it(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:rs(n)}):d?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:rs(n)}):s.jsx("span",{children:rs(n)})})]}),m&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:m,children:m})]})}function vb({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:d,userName:f,toggleHiddenTab:u,actionShortcuts:p,registerActionHandlers:m,onActiveTabChange:y,onOpenNewSession:N,onRequestScrollToBottom:h,requestedActiveTabKey:j,requestedRemoteIdeId:x,onRequestedActiveTabConsumed:b,scrollToBottomRequest:v,liveSessionInboxState:A,layoutProfile:g}){var Ze,qe,tt;const{theme:M}=ao(),{sendCommand:T}=mt(),k=i.useRef(null),w=i.useRef(null),K=i.useRef(null),R=i.useRef(!1),S=i.useRef(!1),O=i.useRef(!1),U=i.useRef(null),P=i.useRef([]),[C,I]=i.useState(null),[W,E]=i.useState(0),$=i.useRef(typeof window>"u"?{}:zh(g)),F=i.useMemo(()=>new Map(e.map(H=>[H.tabKey,H])),[e]),J=i.useMemo(()=>{const H=k.current;return H?H.groups.some(V=>{try{const L=V.model.location.type;return L!=="floating"&&L!=="popout"?!1:V.panels.some(G=>F.has(G.id))}catch{return!1}}):!1},[F,W,e]),he=i.useCallback(()=>{var H;(H=k.current)==null||H.focus()},[]),le=i.useCallback((H,V)=>{h==null||h(H,V)},[h]),te=i.useCallback(H=>{const V=document,L=H.document;for(const ne of V.querySelectorAll('link[rel="stylesheet"]')){const ve=L.createElement("link");ve.rel="stylesheet",ve.href=ne.href,ne.crossOrigin&&(ve.crossOrigin=ne.crossOrigin),L.head.appendChild(ve)}for(const ne of V.querySelectorAll("style")){const ve=L.createElement("style");ve.textContent=ne.textContent,L.head.appendChild(ve)}const G=[];for(const ne of V.styleSheets)try{for(const ve of ne.cssRules)ve instanceof CSSStyleRule&&(ve.selectorText===":root"||ve.selectorText==="html")&&G.push(ve.cssText)}catch{}if(G.length>0){const ne=L.createElement("style");ne.textContent=G.join(`
52
- `),L.head.appendChild(ne)}const _=V.documentElement.getAttribute("data-theme");_&&L.documentElement.setAttribute("data-theme",_),L.documentElement.style.colorScheme=_==="light"?"light":"dark",L.body.className=V.body.className;const z=V.documentElement.getAttribute("style");z&&L.documentElement.setAttribute("style",z);const Q=L.getElementById("dv-popout-window");Q instanceof HTMLElement&&(Q.classList.add("adhdev-dockview"),zn(Q,M))},[M]),ye=i.useCallback(()=>{var V;const H=k.current;if(H)for(const L of H.groups)try{const G=(V=L.element)==null?void 0:V.ownerDocument;if(!G||G===document)continue;const _=G.getElementById("dv-popout-window");_ instanceof HTMLElement&&(_.classList.add("adhdev-dockview"),zn(_,M));const z=document.documentElement.getAttribute("data-theme");z&&G.documentElement.setAttribute("data-theme",z),G.documentElement.style.colorScheme=z==="light"?"light":"dark",G.body.className=document.body.className;const Q=document.documentElement.getAttribute("style");Q?G.documentElement.setAttribute("style",Q):G.documentElement.removeAttribute("style")}catch{}},[M]),fe=i.useCallback(H=>{const V=k.current;if(!V)return;const L=V.getPanel(H);L&&V.addPopoutGroup(L,{popoutUrl:"/popout.html",onDidOpen:({window:G})=>{te(G),xe();const _=F.get(H);G.document.title=_?`${it(_)} — ADHDev`:"ADHDev — Popout"}})},[F,te]),be=i.useCallback(H=>{const V=k.current,L=V==null?void 0:V.getPanel(H);if(!V||!L)return;const G=V.groups.filter(_=>{var z;try{return((z=_.element)==null?void 0:z.ownerDocument)===document}catch{return!0}});G.length>0?L.api.moveTo({group:G[0],position:"center"}):L.api.moveTo({position:"center"}),L.api.setActive()},[]),X=i.useCallback(H=>{var G;const V=k.current;if(!V)return!1;const L=V.getPanel(H);if(!L)return!1;try{return((G=L.group.element)==null?void 0:G.ownerDocument)!==document}catch{return!1}},[]),ae=i.useCallback(H=>{X(H)&&be(H),u(H)},[X,be,u]),ge=i.useCallback(H=>{const V=k.current,L=V==null?void 0:V.getPanel(H);!V||!L||V.addFloatingGroup(L,{width:600,height:500})},[]),ee=i.useCallback(H=>{var L;const V=(L=k.current)==null?void 0:L.getPanel(H);if(!V)return!1;try{return V.group.model.location.type==="floating"}catch{return!1}},[]),de=i.useCallback(()=>{var V,L;const H=(L=(V=k.current)==null?void 0:V.activePanel)==null?void 0:L.id;return!H||Lt(H)?null:F.has(H)?H:null},[F]),we=i.useCallback(H=>{const V=k.current,L=V==null?void 0:V.getPanel(H);if(!V||!L)return;const G=V.groups.filter(_=>{try{return _.model.location.type==="grid"}catch{return!0}});G.length>0?L.api.moveTo({group:G[0],position:"center"}):L.api.moveTo({position:"center"}),L.api.setActive()},[]),ue=i.useCallback(()=>{var z;const H=k.current;if(!H)return;const L=H.groups.filter(Q=>{var ne;try{return((ne=Q.element)==null?void 0:ne.ownerDocument)===document&&Q.model.location.type==="grid"}catch{return!1}})[0]||null,G=[...H.panels];for(const Q of G){const ne=(z=Q.group.element)==null?void 0:z.ownerDocument,ve=Q.group.model.location.type;ne===document&&ve==="grid"||(L&&L.id!==Q.group.id?Q.api.moveTo({group:L,position:"center"}):Q.api.moveTo({position:"center"}))}const _=H.activePanel;_&&(_.group.model.openPanel(_),_.api.setActive()),Un(document)},[]),xe=i.useCallback(()=>{var V,L;const H=k.current;if(H)for(const G of H.groups){const _=(V=G.element)==null?void 0:V.ownerDocument;if(!_||_===document)continue;const z=_.getElementById("dv-popout-window");if(!(z instanceof HTMLElement))continue;let Q=null,ne=_.title||"ADHDev",ve="Popout workspace";const Ae=G.activePanel;if(Ae)if(Q=Ae.id,Lt(Ae.id)){const _e=((L=Ae.params)==null?void 0:L.routeId)||Ae.id.slice(7),ze=Pt([...F.values()],_e);ne=Hc(ze),ve=ze!=null&&ze.machineName?`Remote view · ${ze.machineName}`:"Remote view"}else{const _e=F.get(Ae.id);ne=_e?it(_e):Ae.title||Ae.id,ve=_e?rs(_e):"Dockview panel"}_.title=`${ne} — ADHDev`;const Pe=Array.from(_.querySelectorAll("#adhdev-popout-header"));for(const _e of Pe)_e.remove();const Ce=_.createElement("div");Ce.id="adhdev-popout-header",_.body.appendChild(Ce),Ce.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(";")),Ce.innerHTML=`
51
+ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:w,onCancel:()=>u(null)})]})}const nh=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function ah(){const{preference:e,setPreference:t}=ao();return s.jsx("div",{className:"flex gap-2",children:nh.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 oh(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 ih(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function _n(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function ri(e){const{r:t,g:r,b:n}=ih(e);return .2126*_n(t)+.7152*_n(r)+.0722*_n(n)}function ni(e,t){const r=ri(e),n=ri(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function ol(e){const t=oh(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return ni(t,r)>=ni(t,n)?r:n}const ka={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},Sa={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},ch=[{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"}}}],il="adhdev-chat-theme",cl="adhdev-chat-theme-custom";function Kr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(il)||"ember"}catch{return"ember"}}function _t(e){try{const t=localStorage.getItem(cl);if(t){const r=JSON.parse(t);return{...e==="dark"?ka:Sa,...r[e]}}}catch{}return e==="dark"?ka:Sa}function Tr(e,t){try{localStorage.setItem(cl,JSON.stringify({dark:e,light:t}))}catch{}}function Mt(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 rn(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 lh={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function er(e,t){var a;const r=(a=lh[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",rn(r,24)),n.style.setProperty("--accent-on-primary",ol(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${rn(r,18)})`),n.style.setProperty("--border-accent",Mt(r,.35)),n.style.setProperty("--nav-active-bg",Mt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Mt(r,.06)}`)}function os(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Mt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Mt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Mt(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",Mt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Mt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",rn(e.accentColor,30)),t.style.setProperty("--accent-on-primary",ol(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${rn(e.accentColor,40)})`),t.style.setProperty("--border-accent",Mt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Mt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Mt(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 ${Mt(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 oo(){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 dh(e){try{localStorage.setItem(il,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=is()?"dark":"light";os(_t(t))}else oo(),er(e,is()?"dark":"light")}function uh(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Kr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=is()?"dark":"light";os(_t(t))}else oo(),er(e,is()?"dark":"light")}function is(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function gt({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 Hs({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 fh({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=i.useState(()=>_t(r));i.useEffect(()=>{a(_t(r))},[r]);const o=i.useCallback((c,l)=>{a(d=>{const f={...d,[c]:l},p=_t(r==="dark"?"light":"dark");return r==="dark"?Tr(f,p):Tr(p,f),os(f),t(f),f})},[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(Hs,{title:"App Background",children:[s.jsx(gt,{label:"Background",value:n.bgPrimary,onChange:c=>o("bgPrimary",c)}),s.jsx(gt,{label:"Surface",value:n.bgSecondary,onChange:c=>o("bgSecondary",c)}),s.jsx(gt,{label:"Card",value:n.surfacePrimary,onChange:c=>o("surfacePrimary",c)})]}),s.jsxs(Hs,{title:"App Text",children:[s.jsx(gt,{label:"Primary",value:n.textPrimary,onChange:c=>o("textPrimary",c)}),s.jsx(gt,{label:"Secondary",value:n.textSecondary,onChange:c=>o("textSecondary",c)}),s.jsx(gt,{label:"Muted",value:n.textMuted,onChange:c=>o("textMuted",c)})]}),s.jsxs(Hs,{title:"Borders & Accent",children:[s.jsx(gt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>o("borderSubtle",c)}),s.jsx(gt,{label:"Border default",value:n.borderDefault,onChange:c=>o("borderDefault",c)}),s.jsx(gt,{label:"Accent",value:n.accentColor,onChange:c=>o("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Hs,{title:"Chat Bubbles",children:[s.jsx(gt,{label:"User bubble",value:n.userBubble,onChange:c=>o("userBubble",c)}),s.jsx(gt,{label:"User text",value:n.userText,onChange:c=>o("userText",c)}),s.jsx(gt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>o("assistantBubble",c)}),s.jsx(gt,{label:"Agent text",value:n.assistantText,onChange:c=>o("assistantText",c)})]}),s.jsxs(Hs,{title:"Chat Layout",children:[s.jsx(gt,{label:"Chat BG",value:n.containerBg,onChange:c=>o("containerBg",c)}),s.jsx(gt,{label:"Send button",value:n.sendButton,onChange:c=>o("sendButton",c)}),s.jsx(gt,{label:"Input border",value:n.inputBorder,onChange:c=>o("inputBorder",c)}),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:c=>o("bubbleRadius",Number(c.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 c=e?ka:Sa,d=_t(e?"light":"dark");e?Tr(c,d):Tr(d,c),a(c),os(c),t(c)},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 mh(){const[e,t]=i.useState(Kr),[r,n]=i.useState(!0),[a,o]=i.useState(()=>_t("dark"));i.useEffect(()=>{n(is());const d=new MutationObserver(()=>{const p=is();n(p);const m=Kr();m==="custom"?os(_t(p?"dark":"light")):er(m,p?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const p=is();n(p);const m=Kr();m==="custom"?os(_t(p?"dark":"light")):er(m,p?"dark":"light")};return f.addEventListener("change",u),()=>{d.disconnect(),f.removeEventListener("change",u)}},[]),i.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?os(_t(r?"dark":"light")):(oo(),er(e,r?"dark":"light"))},[e,r]),i.useEffect(()=>{o(_t(r?"dark":"light"))},[r]);const c=d=>{t(d),dh(d)},l=[...ch,{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:l.map(d=>{const f=e===d.id,u=r?d.preview.dark:d.preview.light,p=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>c(d.id),className:"text-left rounded-xl p-3 transition-all",style:{background:f?"var(--bg-glass-hover)":"var(--bg-glass)",border:f?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:f?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:p},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[f&&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(fh,{dark:r,onColorsChange:d=>o(d)})]})}const io="adhdev_mobileDashboardMode_v1",Na="adhdev:mobile-dashboard-mode-change";function co(){try{return localStorage.getItem(io)==="workspace"?"workspace":"chat"}catch{return"chat"}}function ph(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??co())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==io||t()};return window.addEventListener(Na,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Na,r),window.removeEventListener("storage",n)}}function hh(e){try{localStorage.setItem(io,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Na,{detail:e}))}function xh(){const[e,t]=i.useState(!0);return i.useEffect(()=>{t(co()==="chat")},[]),s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ut,{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),hh(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Pn=new Map,ai=new Map;function bh(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 gh(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 ll(){const{sendCommand:e}=mt(),{injectEntries:t,getIdes:r}=rr();return i.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??pm,c=ai.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<o)return;const l=Pn.get(n);if(l)return l;const d=(async()=>{const f=await e(n,"get_machine_runtime_stats"),u=bh(f);if(!u)return;const p=r().find(y=>y.id===n),m=gh(p,n,u.machine,u.timestamp||Date.now());t([m]),ai.set(n,Date.now())})().finally(()=>{Pn.delete(n)});return Pn.set(n,d),d},[r,t,e])}function yh(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 vh(e,t){const{sendData:r}=mt(),{injectEntries:n,getIdes:a}=rr(),o=Array.from(new Set(e.filter(Boolean))).join("|");i.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const c=o?o.split("|"):[];if(c.length===0)return;const l=c.map(d=>Ht.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const p=a().find(y=>y.id===d),m=yh(p,d,u);n([m])}));return()=>{l.forEach(d=>d())}},[o,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function wh(e,t){const{sendData:r}=mt(),[n,a]=i.useState(null),[o,c]=i.useState(!1);return i.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(t!=null&&t.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const d=Ht.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}:{}}},f=>{l&&(clearTimeout(l),l=null),a(f.diagnostics),c(!1)});return d.initialSendAccepted?l=setTimeout(()=>{c(!1)},gm):c(!1),()=>{l&&clearTimeout(l),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 jh(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function dl(e){const{sendData:t}=mt(),[r,n]=i.useState({});return i.useEffect(()=>{const a=jh(e);if(!a||!e.sessionId||!t){n({});return}const o=Ht.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),Ns.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return o.initialSendAccepted||n({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const ul="adhdev_hiddenTabs";function kh(){try{const e=localStorage.getItem(ul);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function bs(e){try{localStorage.setItem(ul,JSON.stringify([...e]))}catch{}}function Dn(e){return qa(e)}function lo(e,t){return Ss(t).some(r=>e.has(r))}function Sh(){const[e,t]=i.useState(kh),r=i.useCallback(f=>{const u=Dn(f);t(p=>{const m=new Set(p);return m.has(u)?m.delete(u):m.add(u),bs(m),m})},[]),n=i.useCallback(f=>{const u=Dn(f);t(p=>{if(p.has(u))return p;const m=new Set(p);return m.add(u),bs(m),m})},[]),a=i.useCallback(f=>{const u=Dn(f);t(p=>{if(!p.has(u))return p;const m=new Set(p);return m.delete(u),bs(m),m})},[]),o=i.useCallback(()=>{t(f=>{if(f.size===0)return f;const u=new Set;return bs(u),u})},[]),c=i.useCallback((f,u)=>{t(p=>{const m=new Set(p);for(const y of u)m.add(y);return bs(m),m})},[]),l=i.useCallback((f,u)=>{t(p=>{const m=new Set(p);for(const y of u)m.delete(y);return bs(m),m})},[]),d=i.useCallback(f=>lo(e,f),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:o,hideAllForDaemon:c,showAllForDaemon:l,isHidden:d}}function fl(e){return e instanceof Error?e.message:String(e||"")}function ml(e){const t=fl(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 pl(e){const t=fl(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function hl({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!et(e)||Xe(e))return;const o=Es(e);if(o===t)return;const c=e.sessionId;c&&a(l=>({...l,[c]:t}));try{await n(xs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Bt(e),mode:t})}catch(l){const d=pl(l);c&&!d&&a(f=>{const u={...f};return o===xl(r,c)?delete u[c]:u[c]=o,u}),ml(l)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",l instanceof Error?l.message:String(l)):console.error("Failed to switch CLI view mode:",l)}}function oi(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 Nh(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=oi(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(d=>oi(d,t)):a.childSessions,l=c!==a.childSessions;return o!==a||l?(r=!0,{...o,...l?{childSessions:c}:{}}):a});return r?n:e}function xl(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 Ch(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))xl(t,a)===o&&(delete n[a],r=!0);return r?n:e}function Th({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){i.useEffect(()=>{mc()},[]);const a=i.useMemo(()=>e.map(o=>({id:o.tabKey,name:Hc(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return vf(a),i.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{r(l=>{const d=Date.now(),f={};for(const[u,p]of Object.entries(l))d-p<5e3&&(f[u]=p);return Object.keys(f).length===Object.keys(l).length?l:f})},5500);return()=>clearTimeout(c)},[t,r]),i.useEffect(()=>{const o=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const d=l.filter(f=>f.timestamp>c).slice(-100);return d.length===l.length?l:d})},6e4);return()=>clearInterval(o)},[n]),null}function Mh(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=r.get(n.id);if(!a){r.set(n.id,n);continue}const o=(a.workspace?1:0)+(a.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>o||(n.timestamp||0)>(a.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function En(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 Ah(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 ii(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Ah(Kt(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 Ih(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||""),ii(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||""),ii(r.activeChat)].join(":"))].join("|")}function Lh(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 Rh(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const o of Ss({routeId:n.routeId}))r.set(o,a);for(const o of Ss({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of Ss({tabKey:n.tabKey}))r.set(o,n)}return r}function _h(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Ph(e){const t=_h(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=Kt(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Dh({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=i.useMemo(()=>Mh(e),[e]),o=i.useMemo(()=>Xc(e),[e]),c=i.useRef([]),l=i.useRef([]),d=i.useRef([]),f=i.useRef(new Map),u=i.useRef(new Map),p=i.useMemo(()=>{const A=new Map,g=[];for(const w of a){const{connectionState:K="new",machineName:R}=Jc(w,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),S=Ih(w),O=f.current.get(w.id);if(O&&O.ide===w&&O.sourceSignature===S&&O.connectionState===K&&O.machineName===R){A.set(w.id,O),g.push(...O.conversations);continue}const H=no(w,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),P={ide:w,sourceSignature:S,connectionState:K,machineName:R,conversations:H};A.set(w.id,P),g.push(...H)}f.current=A;const M=new Map,T=w=>{const K=Ph(w),R=u.current.get(w.tabKey);if(R&&R.signature===K)return M.set(w.tabKey,R),R.timestamp;const S={signature:K,timestamp:Mc(w)||(R==null?void 0:R.timestamp)||0};return M.set(w.tabKey,S),S.timestamp},k=[...g].sort((w,K)=>Ac(w,K,T));return u.current=M,k},[a,t,o]),m=i.useMemo(()=>{const A=Lh(p,r);return En(c.current,A)?c.current:(c.current=A,A)},[p,r]),y=i.useMemo(()=>{const A=new Map,g=Array.from(new Set(m.map(M=>M.routeId)));for(const M of g){const T=Pt(m,M);T&&A.set(M,T)}return A},[m]),N=i.useMemo(()=>{const A=new Map;for(const g of m){const M=y.get(g.routeId),T=g.streamSource==="native"&&M?M:g;for(const k of Ss({providerSessionId:g.providerSessionId,sessionId:g.sessionId}))A.set(k,T)}return A},[m,y]),h=i.useMemo(()=>Rh(m,y),[m,y]),j=i.useCallback(A=>{if(A)return N.get(A)},[N]),x=i.useCallback(A=>{if(A)return h.get(A)},[h]),b=i.useMemo(()=>{const A=m.filter(g=>!lo(n,g));return En(l.current,A)?l.current:(l.current=A,A)},[m,n]),v=i.useMemo(()=>{const A=b.map(g=>g.tabKey);return En(d.current,A)?d.current:(d.current=A,A)},[b]);return{chatIdes:a,conversations:m,visibleConversations:b,visibleTabKeys:v,resolveConversationBySessionId:j,resolveConversationByTarget:x}}function Eh({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=i.useMemo(()=>{var l;return e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),o=i.useMemo(()=>{var l;return!e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),c=i.useCallback(()=>{t&&n(l=>{const d=new URLSearchParams(l);return d.delete("activeTab"),d},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:c}}function $h({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){i.useEffect(()=>{rt.setIdes(e)},[e]),i.useEffect(()=>{rt.setResolveAction((a,o,c)=>{t(a,o,c).catch(()=>{})})},[t]),i.useEffect(()=>{const a=rt.onToast(o=>{r(l=>l.some(f=>f.message===o.message&&o.timestamp-f.timestamp<3e3)?l:[...l.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const c=o.duration||5e3;setTimeout(()=>r(l=>l.filter(d=>d.id!==o.id)),c)});return()=>{a()}},[r]),i.useEffect(()=>{const a=Oc.on("status_event",o=>{rt.handleRawEvent(o,"ws")});return()=>{a()}},[]),i.useEffect(()=>{var o;const a=c=>{var h;const l=c.data;if((l==null?void 0:l.type)!=="notification_action"||typeof l.action!="string"||!l.action.startsWith("approval_")||!(l.daemonId||l.targetSessionId||l.targetKey))return;const d=l.targetSessionId||l.targetKey||l.daemonId,f=n(d),u=(f==null?void 0:f.routeId)||l.daemonId;if(!u)return;const p=Number(l.buttonIndex),m=l.button||((h=f==null?void 0:f.modalButtons)==null?void 0:h[p])||"Approve",y=String(m).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),N=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(y);t(u,"resolve_action",{action:N?"approve":"reject",button:m,...Number.isFinite(p)&&{buttonIndex:p},...(f==null?void 0:f.sessionId)&&{targetSessionId:f.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(j=>console.error("[SW Action] approval failed:",j))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var c;return(c=navigator.serviceWorker)==null?void 0:c.removeEventListener("message",a)}},[n,t])}const Bh="adhdev_dashboardLayout_v1",Kh="adhdev_dashboardDockview_v1",Oh="adhdev_dashboardDockviewHiddenRestore_v1",Us={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function uo(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Wh(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function bl(e){return`${Bh}:${e}`}function Fh(e){const t=bl(e);return uo(t,null)}function Hh(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=bl(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function gl(e){return`${Kh}:${e}`}function Uh(e){const t=gl(e);return uo(t,null)}function zh(e,t){try{const r=gl(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function yl(e){return`${Oh}:${e}`}function Vh(e){const t=yl(e);return uo(t,{})}function Gh(e,t){try{const r=yl(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function qh(){return{groupAssignments:[...Us.groupAssignments],focusedGroup:Us.focusedGroup,groupActiveTabIds:{...Us.groupActiveTabIds},groupTabOrders:{...Us.groupTabOrders},groupSizes:[...Us.groupSizes]}}function Yh(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Xh(){const[e]=i.useState(()=>Wh(typeof window<"u"?window.innerWidth:1280)),[t,r]=i.useState(()=>new Map),[n,a]=i.useState(0),[o,c]=i.useState({}),[l,d]=i.useState({}),[f,u]=i.useState([]),[p,m]=i.useState(()=>typeof window<"u"&&window.innerWidth<768),[y,N]=i.useState(!1),h=i.useCallback(()=>{if(y)return;const w=Fh(e)??qh();r(new Map(w.groupAssignments)),a(w.focusedGroup),c(w.groupActiveTabIds),d(w.groupTabOrders),u(w.groupSizes),N(!0)},[y,e]);i.useEffect(()=>{y&&Hh(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:l,groupSizes:f})},[y,e,t,n,o,l,f]),i.useEffect(()=>{const w=window.matchMedia("(max-width: 767px)"),K=R=>m(R.matches);return w.addEventListener("change",K),()=>w.removeEventListener("change",K)},[]);const j=i.useCallback(w=>{r(w)},[]),x=i.useCallback(w=>{a(w)},[]),b=i.useCallback(w=>{c(w)},[]),v=i.useCallback(w=>{d(w)},[]),A=i.useCallback(w=>{u(w)},[]),g=i.useCallback(w=>{x(w)},[x]),M=i.useCallback((w,K)=>{c(R=>(R[w]??null)===(K??null)?R:{...R,[w]:K})},[]),T=i.useCallback((w,K)=>{d(R=>{const S=R[w];return Yh(S,K)?R:{...R,[w]:K}})},[]),k=i.useCallback((w,K)=>{const R=K.get(w)??0;return M(R,w),g(R),R},[g,M]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:j,focusedGroup:n,updateFocusedGroup:x,focusGroup:g,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:M,groupTabOrders:l,updateGroupTabOrders:v,setGroupTabOrder:T,groupSizes:f,updateGroupSizes:A,isMobile:p,hasHydratedStoredLayout:y,hydrateStoredLayout:h,focusConversationTab:k}}function Jh(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Ga(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Qh({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:c,setSearchParams:l,historyModalOpen:d,activeConv:f,isRefreshingHistory:u,ides:p,handleRefreshHistory:m}){const y=i.useRef(!1),N=i.useRef(!1),h=i.useRef(null),j=i.useRef(!1);i.useEffect(()=>{if(!e||y.current||t.length===0)return;if(!a){o();return}const x=r(e);x&&(c(x.tabKey,n),y.current=!0,N.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),l(b=>{const v=new URLSearchParams(b);return v.delete("activeTab"),v},{replace:!0}))},[e,t,r,n,a,o,c,l]),i.useEffect(()=>{if(!(N.current||a)&&t.length!==0){if(!e){o(),N.current=!0;return}if(y.current){N.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(N.current||a)&&(o(),N.current=!0)},1500),()=>{h.current!=null&&(window.clearTimeout(h.current),h.current=null)}}},[e,t.length,a,o]),i.useEffect(()=>{if(!d){j.current=!1;return}if(!f||j.current||u)return;const x=p.find(b=>b.id===f.routeId);x&&(!x.chats||x.chats.length===0||Jh(x.chats,f))&&(j.current=!0,m())},[d,f,u,p,m])}function $n(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=Ga(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function vl({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[c,l]=i.useState(!1),[d,f]=i.useState(!1),u=i.useCallback(async N=>{try{await e("standalone","launch_ide",{ideType:N,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),p=i.useCallback(async(N,h)=>{try{const j=N||(t==null?void 0:t.daemonId)||"",x=await e(j,"switch_chat",{id:h,sessionId:h,...ts(t)}),b=x==null?void 0:x.result;if((x==null?void 0:x.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?Ws(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Ws(a,`⚠️ Switch error: ${b}`):Ws(a,"⚠️ Session switch failed")}catch(j){console.error("Switch failed",j),Ws(a,`❌ Switch failed: ${j.message||"connection error"}`)}},[t,e,a]),m=i.useCallback(async()=>{if(!(!t||c)){l(!0);try{const N=Ms(t);await e(N,"new_chat",{...ts(t)}),o(h=>({...h,[t.tabKey]:Date.now()}))}catch(N){console.error("New chat failed",N)}finally{l(!1)}}},[t,c,e,o]),y=i.useCallback(async()=>{var N,h;if(!(!t||d)){f(!0);try{const j=Ms(t),x=async()=>e(j,"list_chats",{forceExpand:!0,...ts(t)});let b=await x(),v=(b==null?void 0:b.chats)||((N=b==null?void 0:b.result)==null?void 0:N.chats);$n(v,t)&&(await new Promise(A=>setTimeout(A,450)),b=await x(),v=(b==null?void 0:b.chats)||((h=b==null?void 0:b.result)==null?void 0:h.chats)),b!=null&&b.success&&Array.isArray(v)&&(n(t.routeId,v),$n(v,t)&&!$n(r,t)&&Ws(a,"⚠️ History dialog did not fully open — try once more"))}catch(j){console.error("Refresh history failed",j)}finally{f(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:p,handleNewChat:m,handleRefreshHistory:y}}function Zh(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 ex(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function ci(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 Mr(e,t){const r=new Set(t),n=t.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const o=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const d=a[l];typeof d=="number"&&d>0&&o.set(c,d)}return{assignments:o,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function li(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 tx(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 sx(e,t,r){if(t.length<=1)return[];const n=t.map(c=>e[c]).filter(c=>Number.isFinite(c)),a=n.length===t.length?n:Array(r).fill(100/r),o=a.reduce((c,l)=>c+l,0);return o>0?a.map(c=>c/o*100):Array(r).fill(100/r)}function di(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 ui(e){return Array(e).fill(100/e)}function rx({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:c,isMobile:l,visibleConversations:d,visibleTabKeys:f}){const u=i.useRef(null),p=i.useMemo(()=>Mr(e,f),[e,f]),m=p.assignments,y=i.useMemo(()=>l?1:p.groupCount,[p.groupCount,l]),N=y>1,h=i.useCallback((g,M)=>{t(T=>{const k=new Map(Mr(T,f).assignments);return M===0?k.delete(g):k.set(g,M),k}),n(T=>({...T,[M]:g})),r(M)},[t,f,n,r]),j=i.useCallback(g=>{t(M=>{const T=Mr(M,f).assignments,k=new Map;for(const[w,K]of T)K!==g&&(K>g?k.set(w,K-1):k.set(w,K));return k}),c(M=>{if(M.length<=1)return[];const T=[...M];T.splice(g,1);const k=T.reduce((w,K)=>w+K,0);return k>0?T.map(w=>w/k*100):[]}),r(0)},[t,f,c,r]),x=i.useCallback((g,M)=>{M.preventDefault();const T=u.current;if(!T)return;const k=M.clientX,w=T.offsetWidth,K=o.length===y?[...o]:ui(y),R=O=>{const P=(O.clientX-k)/w*100,C=[...K];C[g]=Math.max(15,K[g]+P),C[g+1]=Math.max(15,K[g+1]-P),c(C)},S=()=>{document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",S),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",R),document.addEventListener("mouseup",S)},[o,y,c]),b=i.useCallback((g,M,T)=>{if(y>=4)return;const k=T==="left"?M:M+1;t(w=>{const K=Mr(w,f).assignments,R=new Map;for(const S of d){const O=K.get(S.tabKey)??0,H=O>=k?O+1:O;H>0&&R.set(S.tabKey,H)}return k>0&&R.set(g,k),R}),c(w=>{const K=w.length===y?[...w]:ui(y),R=K[M]??100/y,S=Math.max(15,R/2),O=Math.max(15,R/2),H=[...K];H[M]=S,H.splice(k,0,O);const P=H.reduce((C,I)=>C+I,0);return H.map(C=>C/P*100)}),n(w=>{const K=di(w,k);return K[k]=g,K}),a(w=>{const K=di(w,k);return K[k]=[g],K}),r(k)},[y,t,f,d,c,n,a,r]);i.useEffect(()=>{Zh(e,m)||t(m)},[e,m,t]),i.useEffect(()=>{const{mapping:g,usedGroups:M}=p;n(T=>{const k=li(T,g);return ci(T,k)?T:k}),a(T=>{const k=li(T,g);return ci(T,k)?T:k}),r(T=>{const k=l?0:tx(T,M,g);return T===k?T:k}),c(T=>{const k=l?[]:sx(T,M,p.groupCount);return ex(T,k)?T:k})},[p,l,n,a,r,c]);const v=i.useMemo(()=>{const g=Array.from({length:y},()=>[]);for(const M of d){const T=m.get(M.tabKey)??0,k=Math.min(T,y-1);g[k].push(M)}return g},[d,m,y]),A=i.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:m,numGroups:y,isSplitMode:N,groupedConvs:v,moveTabToGroup:h,closeGroup:j,handleResizeStart:x,splitTabRelative:b,clearAllSplits:A}}function nx({ides:e,sendDaemonCommand:t}){const r="0.9.60",n=i.useMemo(()=>e.filter(u=>u.type!=="adhdev-daemon"?!1:al(u,r)).sort((u,p)=>Number(Zs(p,r))-Number(Zs(u,r))),[r,e]),a=i.useMemo(()=>n.some(u=>Zs(u,r)),[r,n]),[o,c]=i.useState(!1),[l,d]=i.useState({}),f=i.useCallback(async u=>{var p,m;d(y=>({...y,[u]:"upgrading"}));try{const y=await t(u,"daemon_upgrade",{});(p=y==null?void 0:y.result)!=null&&p.upgraded||(m=y==null?void 0:y.result)!=null&&m.success?d(N=>({...N,[u]:"done"})):d(N=>({...N,[u]:"error"}))}catch{d(y=>({...y,[u]:"error"}))}},[t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:o,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:f}}const wl=80;function Or(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function ax(e){return{...e,createdAt:Or(e.createdAt),updatedAt:Or(e.updatedAt,e.createdAt),lastEventAt:Or(e.lastEventAt,e.updatedAt||e.createdAt)}}function ox(e){const t=qa(e);return t==="unknown:"?e.id:t}function ix(e){return[e.type,Tc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function cx(e,t=wl){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=ox(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 lx(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 c=dn(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const d=Or(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),f=ix({type:l,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(ax({id:f,dedupKey:f,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:gc(a),preview:zf(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return cx(n)}function dx(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function ux(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=wl}=e,a=i.useMemo(()=>lx(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=i.useMemo(()=>dx(a),[a]);return{notifications:a,unreadCount:o}}function fx({notifications:e,sendDaemonCommand:t}){const r=i.useCallback(o=>{const c=e.find(d=>d.id===o),l=Math.max(Date.now(),(c==null?void 0:c.updatedAt)||0);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_session_seen",{sessionId:c.sessionId,seenAt:l}).catch(()=>{})},[e,t]),n=i.useCallback(o=>{const c=e.find(l=>l.id===o);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_notification_unread",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]),a=i.useCallback(o=>{const c=e.find(l=>l.id===o);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"delete_notification",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}function pn(...e){const t=new Set,r=[],n=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const c=o.toLowerCase();t.has(c)||(t.add(c),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 mx(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 hn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=mx(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 px(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 hx(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function xn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=hx(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,c=o.includes("\\")?"\\":"/",l=(f,u)=>/^[A-Za-z]:\\?$/.test(f)?`${f.replace(/\\?$/,"\\")}${u}`:f==="/"||f==="\\"?`${c}${u}`:`${f.replace(/[\\/]+$/,"")}${c}${u}`,d=Array.isArray(a==null?void 0:a.files)?a.files.filter(f=>(f==null?void 0:f.type)==="directory"&&typeof(f==null?void 0:f.name)=="string").map(f=>({name:f.name,path:typeof(f==null?void 0:f.path)=="string"&&f.path.trim()?f.path:l(o,f.name)})).sort((f,u)=>f.name.localeCompare(u.name)):[];return{path:o,directories:d}}function xx(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function fi(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function bx(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function gx({ides:e,conversations:t,onOpenSession:r}){const[n,a]=i.useState(null),o=i.useCallback(c=>{a(c)},[]);return i.useEffect(()=>{if(!n)return;const c=fi(n.workspacePath),l=e.find(f=>{var N,h,j,x;if(!f||f.type==="adhdev-daemon"||xx(f.daemonId||f.id)!==n.machineId||(or(f)?"cli":js(f)?"acp":"ide")!==n.kind||String(f.agentType||f.type||"")!==n.providerType)return!1;if(n.resumeSessionId)return String(f.providerSessionId||"")===n.resumeSessionId;if(c){const b=fi(f.workspace||f.runtimeWorkspaceLabel);return b?b===c:!1}return Number(f.lastUpdated||f._lastUpdate||f.timestamp||((x=(j=(h=(N=f.activeChat)==null?void 0:N.messages)==null?void 0:h.at)==null?void 0:j.call(h,-1))==null?void 0:x.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const d=Ic({entrySessionId:l.sessionId,entryInstanceId:l.instanceId,entryRouteId:l.id,conversations:t});d&&(a(null),r(d))},[t,e,r,n]),i.useEffect(()=>{if(!n)return;const c=window.setTimeout(()=>{a(l=>!l||l.startedAt!==n.startedAt?l:null)},45e3);return()=>window.clearTimeout(c)},[n]),{trackPendingLaunch:o}}function yx({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const c=i.useCallback(async(m,y)=>xn(e,m,y),[e]),l=i.useCallback(async(m,y)=>{if(!y.trim())return{ok:!1,error:"Choose a workspace path first."};try{const N=await e(m,"workspace_add",{path:y.trim()});return N!=null&&N.success?{ok:!0}:{ok:!1,error:(N==null?void 0:N.error)||"Could not save workspace"}}catch(N){return{ok:!1,error:N instanceof Error?N.message:"Could not save workspace"}}},[e]),d=i.useCallback(async(m,y,N)=>{var h;try{const j={ideType:y,enableCdp:!0};(h=N==null?void 0:N.workspacePath)!=null&&h.trim()&&(j.workspace=N.workspacePath.trim());const x=await e(m,"launch_ide",j);return!(x!=null&&x.success)&&(x==null?void 0:x.success)!==void 0?{ok:!1,error:(x==null?void 0:x.error)||"Could not launch IDE"}:(t({machineId:m,kind:"ide",providerType:y,workspacePath:(N==null?void 0:N.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(j){return{ok:!1,error:j instanceof Error?j.message:"Could not launch IDE"}}},[e,t]),f=i.useCallback(async(m,y,N,h)=>{var x,b,v;const j=Date.now();try{const A={cliType:N};(x=h==null?void 0:h.workspacePath)!=null&&x.trim()?A.dir=h.workspacePath.trim():h!=null&&h.workspaceId&&(A.workspaceId=h.workspaceId),(b=h==null?void 0:h.resumeSessionId)!=null&&b.trim()&&(A.resumeSessionId=h.resumeSessionId.trim()),Array.isArray(h==null?void 0:h.cliArgs)&&h.cliArgs.length>0&&(A.cliArgs=h.cliArgs),(v=h==null?void 0:h.initialModel)!=null&&v.trim()&&(A.initialModel=h.initialModel.trim());const g=await e(m,"launch_cli",A),M=(g==null?void 0:g.result)||g,T=(M==null?void 0:M.sessionId)||(M==null?void 0:M.id);return g!=null&&g.success&&T?(r(T),{ok:!0}):g!=null&&g.success?(t({machineId:m,kind:y,providerType:N,workspacePath:(h==null?void 0:h.workspacePath)||null,resumeSessionId:(h==null?void 0:h.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:(g==null?void 0:g.error)||(M==null?void 0:M.error)||`Could not launch ${y.toUpperCase()} session`}}catch(A){return bx(A)?(t({machineId:m,kind:y,providerType:N,workspacePath:(h==null?void 0:h.workspacePath)||null,resumeSessionId:(h==null?void 0:h.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:A instanceof Error?A.message:`Could not launch ${y.toUpperCase()} session`}}},[r,e,t]),u=i.useCallback(async(m,y)=>{if(!m||!y)return[];try{const N=await e(m,"list_saved_sessions",{providerType:y,kind:"cli",limit:30}),h=(N==null?void 0:N.result)??N;return Array.isArray(h==null?void 0:h.sessions)?h.sessions:[]}catch(N){return console.error("List saved sessions failed",N),[]}},[e]),p=i.useCallback(async m=>{await hl({conversation:n,mode:m,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:l,handleLaunchMachineIde:d,handleLaunchMachineProvider:f,handleListMachineSavedSessions:u,setActiveCliViewMode:p}}function vx(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 wx(e,t,r=Date.now()){return!e||!vx(t)?null:{tabKey:e,nonce:r}}function jx({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:c}){const[l,d]=i.useState(null),[f,u]=i.useState(null),p=i.useMemo(()=>{var j,x;if(!e){if(l){const b=t.find(v=>v.tabKey===l);if(b)return b}return r[0]}const h=n[a];if(h){const b=t.find(v=>v.tabKey===h);if(b)return b}return((j=o[a])==null?void 0:j[0])||((x=o[0])==null?void 0:x[0])},[t,l,a,n,o,e,r]),m=i.useCallback(h=>{d(h)},[]),y=i.useCallback(h=>{d(h.tabKey),c(j=>{const x=new URLSearchParams(j),b=Gf(h);return b?x.set("activeTab",b):x.delete("activeTab"),x},{replace:!0})},[c]),N=i.useCallback((h,j)=>{const x=wx(h,j);x&&u(x)},[]);return{activeConv:p,openDesktopConversation:y,requestScrollToBottom:N,scrollToBottomRequest:f,setDesktopActiveTab:m}}function kx(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 Sx(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 Nx({activeConv:e,isMobile:t,liveSessionInboxState:r,sendDaemonCommand:n}){const a=i.useRef(null),o=i.useRef(null),c=i.useRef(null),l=i.useRef(null),d=i.useRef(null);i.useEffect(()=>{const f=()=>{c.current&&(clearTimeout(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){f(),a.current=null;return}if(!(e!=null&&e.sessionId)){f(),a.current=null;return}const u=Yr(e,r),p=Sx({tabKey:e.tabKey,historySessionId:ur(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:ss(e),liveState:u}),m=p.autoReadKey,y=kx({autoReadKey:m,shouldMarkSeen:p.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!p.shouldMarkSeen){y.shouldCancelPending&&f(),a.current=m;return}if(!y.shouldSchedule)return;y.shouldCancelPending&&f();const N=()=>{if(document.visibilityState!=="visible"||a.current===m)return;a.current=m,o.current=null,c.current=null,l.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const j=p.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:j,completionMarker:p.completionMarker}).catch(()=>{})};if(o.current=y.nextPendingKey,document.visibilityState==="visible"){c.current=setTimeout(N,1500);const j=()=>{document.visibilityState!=="visible"&&c.current&&(clearTimeout(c.current),c.current=null)};d.current=j,document.addEventListener("visibilitychange",j);return}const h=()=>{document.visibilityState==="visible"&&(l.current&&clearTimeout(l.current),l.current=setTimeout(N,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=h,document.addEventListener("visibilitychange",h)},[e,t,r,n]),i.useEffect(()=>()=>{c.current&&clearTimeout(c.current),l.current&&clearTimeout(l.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function Bn(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 Cx({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:c,setClearedTabs:l,setSearchParams:d}){var I;const[f,u]=i.useState(!1),[p,m]=i.useState([]),[y,N]=i.useState(()=>xt()),[h,j]=i.useState(!1),[x,b]=i.useState(null),v=i.useRef(null),A=i.useMemo(()=>r||t||e,[e,r,t]),g=!!A&&et(A)&&!Xe(A),M=i.useMemo(()=>{if(!A||!g)return null;const W=A.daemonId||A.routeId||"",E=Bt(A),$=Bn(A);return`${W}:${E}:${A.providerSessionId||""}:${$}`},[A,g]),T=i.useMemo(()=>!A||!g?"":Bn(A),[A,g]),{isCreatingChat:k,isRefreshingHistory:w,handleSwitchSession:K,handleNewChat:R,handleRefreshHistory:S}=vl({sendDaemonCommand:a,activeConv:A,chats:(I=n.find(W=>W.id===(A==null?void 0:A.routeId)))==null?void 0:I.chats,updateRouteChats:o,setToasts:c,setClearedTabs:l}),O=i.useCallback(()=>{u(!0)},[]),H=i.useCallback(()=>{u(!1)},[]),P=i.useCallback(async()=>{if(!(!A||!g||h)){j(!0);try{const W=A.daemonId||A.routeId,E=Bt(A),$=Bn(A),z=await a(W,"list_saved_sessions",{agentType:E,providerType:E,kind:"cli",limit:50,...A.providerSessionId?{providerSessionId:A.providerSessionId}:{},...$?{workspace:$}:{}}),J=(z==null?void 0:z.result)??z;m(Array.isArray(J==null?void 0:J.sessions)?J.sessions:[])}catch(W){console.error("Refresh saved sessions failed",W),m([])}finally{j(!1)}}},[A,h,g,a]);i.useEffect(()=>{if(!f){v.current=null;return}if(!g){v.current=null,m([]),j(!1);return}!M||h||v.current!==M&&(v.current=M,P())},[P,f,h,g,M]);const C=i.useCallback(async W=>{if(!A||!g||!W.providerSessionId||!W.workspace)return;const E=A.daemonId||A.routeId,$=Bt(A);try{b(W.providerSessionId);const z=await a(E,"launch_cli",{cliType:$,dir:W.workspace,resumeSessionId:W.providerSessionId,initialModel:uc(W.summaryMetadata,"model",{preferShortValue:!0})||void 0}),J=(z==null?void 0:z.result)??z,he=typeof(J==null?void 0:J.sessionId)=="string"?J.sessionId:typeof(J==null?void 0:J.id)=="string"?J.id:"";he&&d(ce=>{const te=new URLSearchParams(ce);return te.set("activeTab",he),te},{replace:!0}),H()}catch(z){console.error("Resume saved session failed",z)}finally{b(null)}},[H,A,g,a,d]);return{historyModalOpen:f,openHistoryModal:O,closeHistoryModal:H,historyTargetConv:A,isSavedSessionHistoryTarget:g,isHistoryCreatingChat:k,isHistoryRefreshingHistory:w,handleHistorySwitchSession:K,handleHistoryNewChat:R,handleHistoryRefresh:S,savedHistorySessions:p,savedHistoryFilters:y,setSavedHistoryFilters:N,missingWorkspaceResumePath:T,isSavedHistoryLoading:h,resumingSavedHistorySessionId:x,handleRefreshSavedHistory:P,handleResumeSavedHistorySession:C}}function Tx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l}){const[d,f]=i.useState(null),[u,p]=i.useState(null),m=i.useMemo(()=>{if(e||!n)return null;const x=l(n);return x&&!et(x)&&!Xe(x)?x:null},[e,n,l]),y=i.useMemo(()=>{const x=d==null?void 0:d.routeId;if(!x)return null;const b=d!=null&&d.tabKey?o.find(v=>v.tabKey===d.tabKey):a?o.find(v=>v.tabKey===a):null;return(b==null?void 0:b.routeId)===x?b:Pt(o,x)},[o,d,a]),N=i.useMemo(()=>{if(y)return c.find(x=>x.id===y.routeId)},[c,y]);i.useEffect(()=>{m&&(f({routeId:m.routeId,tabKey:Ko(m)}),p(m),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,m]);const h=i.useCallback(x=>{x&&(f({routeId:x.routeId,tabKey:Ko(x)}),p(x))},[]),j=i.useCallback(()=>{f(null),p(null)},[]);return{remoteDialogConv:y,remoteDialogIdeEntry:N,remoteDialogActiveConv:u,setRemoteDialogActiveConv:p,openRemoteDialog:h,closeRemoteDialog:j}}function Mx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l,activeConv:d,sendDaemonCommand:f}){const{remoteDialogConv:u,remoteDialogIdeEntry:p,remoteDialogActiveConv:m,setRemoteDialogActiveConv:y,openRemoteDialog:N,closeRemoteDialog:h}=Tx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l}),[j,x]=i.useState(!1),[b,v]=i.useState(null),A=i.useCallback(async T=>{const k=T||d;!k||!et(k)&&!Xe(k)||(v(k),x(!0))},[d]),g=i.useCallback(()=>{x(!1),v(null)},[]),M=i.useCallback(async T=>{const k=b||d;if(!k||!et(k)&&!Xe(k)){g();return}x(!1);try{const w=Bt(k),K=k.routeId||k.daemonId||"";await f(K,"stop_cli",{cliType:w,targetSessionId:k.sessionId,mode:T})}catch(w){console.error("Stop CLI failed:",w)}finally{v(null)}},[d,g,b,f]);return{remoteDialogConv:u,remoteDialogIdeEntry:p,remoteDialogActiveConv:m,setRemoteDialogActiveConv:y,openRemoteDialog:N,closeRemoteDialog:h,cliStopDialogOpen:j,cliStopTargetConv:b,requestCliStop:A,cancelCliStop:g,confirmCliStop:M}}function Kn(e,t=!0){return(e??!0)&&t}const fo=i.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:c,handleRelaunch:l,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u=null,handleFocusAgent:p,isFocusingAgent:m,actionLogs:y,userName:N,scrollToBottomRequestNonce:h,isInputActive:j=!0,isVisible:x=!0}){const b=n,v=!n,A=Kn(x,b),g=Kn(x,v),M=Kn(x),T=dl(t),k=T.status||T.modalMessage||T.modalButtons?{...t,...T.status?{status:T.status}:{},...T.modalMessage!==void 0?{modalMessage:T.modalMessage}:{},...T.modalButtons!==void 0?{modalButtons:T.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(ic,{activeConv:k,onModalButton:c}),k.transport!=="pty"&&k.transport!=="acp"&&k.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(nr,{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:l,children:"Relaunch with CDP"})]})}):null,k.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:b?"visible":"hidden",pointerEvents:b?"auto":"none"},children:s.jsx(fp,{activeConv:k,clearToken:r,terminalRef:o,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u,isVisible:A,isInputActive:j&&A})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:v?"visible":"hidden",pointerEvents:v?"auto":"none"},children:s.jsx(wa,{activeConv:k,ideEntry:a,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u,handleFocusAgent:p,isFocusingAgent:m,actionLogs:y,userName:N,scrollToBottomRequestNonce:h,isInputActive:j&&g,isVisible:g})})]}):s.jsx(wa,{activeConv:k,ideEntry:a,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u,handleFocusAgent:p,isFocusingAgent:m,actionLogs:y,userName:N,scrollToBottomRequestNonce:h,isInputActive:j&&M,isVisible:M})]})},(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 Ax({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:d,onBack:f,onOpenNativeConversation:u,onOpenMachine:p,onOpenHistory:m,onOpenRemote:y,onHideConversation:N,onStopCli:h,cliViewMode:j,onSetCliViewMode:x,handleSendChat:b,handleFocusAgent:v,handleModalButton:A,handleRelaunch:g}){const M=i.useRef(null),T=et(e)&&!t,k=T&&j==="terminal",w=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 ${w} 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:f,type:"button","aria-label":"Back",children:s.jsx(_a,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:it(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(Lc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>p(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[T&&j&&s.jsx(Qa,{mode:j,onChange:x,compact:!0}),T&&h&&s.jsx("button",{onClick:()=>{h(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(St,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(e),type:"button",children:s.jsx(Pa,{size:14})}),!t&&!T&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>y(e),type:"button",children:s.jsx(Tt,{size:14})}),N&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>N(e),type:"button",title:"Close chat",children:s.jsx(St,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(fo,{activeConv:e,clearToken:0,isCliTerminal:k,ideEntry:n,terminalRef:M,handleModalButton:A,handleRelaunch:g,handleSendChat:b,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:v,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const On={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 Ix(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function jl(){const[e,t]=i.useState("unix"),[r,n]=i.useState("powershell"),[a,o]=i.useState(!1),c=e==="unix"?"unix":r;i.useEffect(()=>{t(Ix())},[]);const l=i.useCallback(()=>{navigator.clipboard.writeText(On[c].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[c]);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:l,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:On[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:On[c].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 kl({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Tt},{key:"chats",label:"Chats",icon:Ut}];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 c=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 ${c?"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:c?{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":c,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{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 Ar({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 gs({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 zs({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 Ir({item:e,type:t,getAvatarText:r,onOpenConversation:n,onHideConversation:a,onCollectChatDebugBundle:o}){const c=t==="needs_attention"||t==="task_complete",l=t==="working",d=t==="earlier",f=t==="task_complete",{isReconnecting:u,isConnecting:p}=Ds(e.conversation),m=it(e.conversation),y=As(e.conversation),N=Fc(e.conversation,{requiresAction:t==="needs_attention"}),h=c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":l?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":d?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",j=c?"bg-accent-primary shadow-glow":l?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":d?"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",x=d?"text-text-secondary":"text-text-primary",b=d?"text-text-muted":"text-text-secondary",v=d?"text-text-secondary opacity-80":"text-text-muted",A=d?"text-text-muted opacity-80":"text-text-muted",g=!l&&!f,M="text-[color:var(--status-warning)]",T=k=>{if(!o)return;k.preventDefault(),k.stopPropagation();const w=o==null?void 0:o(e.conversation);Promise.resolve(w).catch(K=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",K)})};return s.jsxs("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${h}`,children:[s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative ${a?"pb-2":""}`,onClick:()=>n(e.conversation),onContextMenu:T,type:"button",children:[c||l?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.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${j}`,style:c?{color:"var(--accent-on-primary)"}:void 0,children:r(m)}),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 truncate tracking-tight ${x}`,children:m}),g&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${A}`,children:oc(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[s.jsx("span",{className:"truncate",children:y}),s.jsx(Is,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),u?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${M} animate-pulse`,children:"Reconnecting…"})]}):p?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):N==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:M,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${v}`,children:e.preview})]}),c&&!f&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),f&&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"}),l&&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"})]}),a&&s.jsx("div",{className:"flex justify-end px-4 pb-3 -mt-1",children:s.jsxs("button",{type:"button",className:"mobile-inbox-hide-button inline-flex items-center gap-1.5 rounded-full border border-border-subtle bg-bg-primary/70 px-2.5 py-1 text-[11px] font-semibold text-text-muted hover:border-border-default hover:text-text-primary",onClick:k=>{k.preventDefault(),k.stopPropagation(),a(e.conversation)},"aria-label":`Hide ${m}`,title:"Hide conversation",children:[s.jsx(Da,{size:12}),s.jsx("span",{children:"Hide"})]})})]},e.conversation.tabKey)}function mi({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 Lx({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:c,getAvatarText:l,actionLogs:d,sendDaemonCommand:f,onOpenConversation:u,onShowAllHidden:p,onHideConversation:m,onOpenNewSession:y,onOpenMachine:N,onOpenSettings:h,onSectionChange:j,wsStatus:x="connected",isStandalone:b=!1,onCollectChatDebugBundle:v}){const A=x==="disconnected"||x==="reconnecting"||x==="offline"||x==="auth_failed",g=c.length>0,M=t.length>0||r.length>0||n.length>0||a.length>0,T=e==="machines"?"Machines":"Chats",k=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",w=b?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",K=i.useCallback(async S=>{const O=Ms(S);if(!O)return;const H=Array.isArray(S.messages)?S.messages:[],P=kc({activeConv:S,visibleMessages:H,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:H.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),C=await f(O,"get_chat_debug_bundle",{...ts(S),delivery:"daemon_file",frontendSnapshot:P}),I=Qr(C),W=Cc(I),E=await Nc(W);E==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),rt.showToast(Sc(I,{locatorCopyStatus:E}),E==="failed"?"warning":"success")},[d,f]),R=v||K;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 ${k}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:T}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||r.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(cn,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:h,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(on,{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] ${w}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:A?s.jsx(zs,{icon:s.jsx(mi,{}),title:x==="offline"?"Network offline":x==="auth_failed"?"Session expired":"Reconnecting",subtitle:x==="offline"?"Waiting for network…":x==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):c.length===0?s.jsx(zs,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:b?"Waiting for your daemon":"Connect your machines",subtitle:b?"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:!b&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(jl,{})})}):s.jsx(gs,{children:c.map((S,O)=>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] ${O>0?"border-t border-border-subtle/70":""}`,onClick:()=>N(S.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:l(S.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:S.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:S.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[S.unread," new"]}):S.total>0?`${S.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:S.subtitle}),S.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[S.total," chat",S.total!==1?"s":"",S.unread>0?` · ${S.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},S.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(Ar,{title:"Needs attention",className:"mb-0"}),s.jsx(gs,{children:t.map((S,O)=>s.jsx("div",{className:O>0?"border-t border-border-subtle/70":"",children:s.jsx(Ir,{item:S,type:"needs_attention",getAvatarText:l,onOpenConversation:u,onHideConversation:m,onCollectChatDebugBundle:R})},S.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(Ar,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(gs,{children:r.map((S,O)=>s.jsx("div",{className:O>0?"border-t border-border-subtle/70":"",children:s.jsx(Ir,{item:S,type:"task_complete",getAvatarText:l,onOpenConversation:u,onHideConversation:m,onCollectChatDebugBundle:R})},S.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(Ar,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(gs,{children:n.map((S,O)=>s.jsx("div",{className:O>0?"border-t border-border-subtle/70":"",children:s.jsx(Ir,{item:S,type:"working",getAvatarText:l,onOpenConversation:u,onHideConversation:m,onCollectChatDebugBundle:R})},S.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(Ar,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(gs,{children:a.map((S,O)=>s.jsx("div",{className:O>0?"border-t border-border-subtle/70":"",children:s.jsx(Ir,{item:S,type:"earlier",getAvatarText:l,onOpenConversation:u,onHideConversation:m,onCollectChatDebugBundle:R})},S.conversation.tabKey))}):M?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):A?s.jsx(zs,{icon:s.jsx(mi,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):g?s.jsx(zs,{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(Ut,{size:20})}),title:"No conversations yet",subtitle:zc,children:y&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:y,"aria-label":Et,title:Et,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:Et})]})}):s.jsx(zs,{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(gs,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:"Hidden tabs"}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[o.length," collapsed ",o.length===1?"conversation":"conversations"]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:p,children:"Restore all"})]})})})]}),e==="chats"&&y&&M&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:y,"aria-label":Et,title:Et,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"})]})}),s.jsx(kl,{section:e,onSectionChange:j})]})}function Rx(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 Sl(e){const t=[e.workspace||"Workspace unknown"],r=fs(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Rx(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function bn({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:o="",confirmLabel:c="Use this folder",onClose:l,onNavigate:d,onConfirm:f}){const[u,p]=i.useState(r);i.useEffect(()=>{p(r)},[r]);const m=px(r),y=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:l,"aria-label":"Close folder browser",children:s.jsx(St,{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:()=>{!m||a||d(m)},disabled:!m||a,children:[s.jsx(_a,{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:N=>p(N.target.value),onKeyDown:N=>{N.key!=="Enter"||!y||a||(N.preventDefault(),d(y))},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:()=>{!y||a||d(y)},disabled:!y||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(N=>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(N.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(Cs,{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:N.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:N.path})]})]},N.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:l,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>f(y||r),disabled:!y&&!r||a,children:c})]})]})})}function mo({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:d=!1,showArgsInput:f,argsValue:u,onArgsChange:p,showModelInput:m,modelValue:y,onModelChange:N,historyProviderNode:h,onConfirm:j,onCancel:x}){const b=n==null?void 0:n.find(v=>v.key===a);return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:x,"aria-label":"Close launch confirmation",children:s.jsx(St,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),s.jsx("select",{value:a||"",onChange:v=>o(v.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:n.map(v=>s.jsx("option",{value:v.key,children:v.label},v.key))}),(b==null?void 0:b.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:b.description})]}),h,r.map(v=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:v.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:v.value})]},`${v.label}:${v.value}`)),m&&N&&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:y||"",onChange:v=>N(v.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),f&&p&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:u||"",onChange:v=>p(v.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled: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:x,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:j,disabled:d,children:[s.jsx($a,{size:14}),d?l:c]})]})]})})}function pi(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function cs(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?"⭐ ":""}${pi(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const c=(r==null?void 0:r.trim())||"",l=c?(t.workspaces||[]).find(d=>d.path===c):null;if(c&&!l&&o.push({key:`custom:${c}`,label:pi(c),description:c,workspaceId:null,workspacePath:c}),n){const d=`saved:${n}`;if(o.some(f=>f.key===d))return{options:o,selectedKey:d}}return l?{options:o,selectedKey:`saved:${l.id}`}:c?{options:o,selectedKey:`custom:${c}`}:{options:o,selectedKey:"__home__"}}function _x(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Px(e){return[_x(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Dx(e){return e.lastLaunchedAt?ln(e.lastLaunchedAt):""}function Nl(e){return{metaText:Px(e),updatedLabel:Dx(e)}}function Wn(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function Ex({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var Qe,lt,dt,ut;const c=fr(),[l,d]=i.useState(!1),f=(((Qe=e.detectedIdes)==null?void 0:Qe.length)||0)>0,u=i.useMemo(()=>(e.workspaces||[]).map(Te=>({id:Te.id,path:Te.path,label:Te.label})),[e]),p=e.defaultWorkspaceId||null,[m,y]=i.useState(p||((lt=u[0])==null?void 0:lt.id)||""),[N,h]=i.useState(""),[j,x]=i.useState(""),[b,v]=i.useState([]),[A,g]=i.useState(!1),[M,T]=i.useState(""),[k,w]=i.useState(!1),[K,R]=i.useState(Wn(f,t.length,r.length)),S=i.useRef(null),[O,H]=i.useState(null),P=i.useRef("__home__"),[C,I]=i.useState("__home__"),[W,E]=i.useState(""),[$,z]=i.useState(""),[J,he]=i.useState(""),[ce,te]=i.useState([]),[ye,fe]=i.useState(()=>xt().textQuery),[be,X]=i.useState(()=>xt().workspaceQuery),[ae,ge]=i.useState(()=>xt().modelQuery),[ee,de]=i.useState(()=>xt().resumableOnly),[we,ue]=i.useState(()=>xt().sortMode),[xe,se]=i.useState(!1),[ie,re]=i.useState(!1),q=i.useRef(null),Y=i.useRef(null);i.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const le=m==="__custom__"?N.trim():((dt=u.find(Te=>Te.id===m))==null?void 0:dt.path)||"",ke=m==="__custom__"&&!!le&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),Z=m!=="__custom__"&&((ut=u.find(Te=>Te.id===m))==null?void 0:ut.path)||"",Ce=i.useMemo(()=>(e.recentLaunches||[]).map(Te=>Te.workspace),[e]),Ee=i.useCallback(async Te=>{g(!0),T("");try{const Ge=await a(Te);x(Ge.path),h(Ge.path),v(Ge.directories)}catch(Ge){T(Ge instanceof Error?Ge.message:"Could not load folder")}finally{g(!1)}},[a]),We=i.useCallback(()=>{var Ge;y("__custom__"),w(!0);const Te=hn(e.platform,pn(N.trim(),Z,Ce,e.defaultWorkspacePath,(Ge=u.find(Ze=>Ze.id===p))==null?void 0:Ge.path,u.map(Ze=>Ze.path)));Ee(Te)},[N,p,Ee,Ce,Z,e.platform,u]),Fe=i.useCallback(Te=>{if(Te!=null&&Te.workspaceId){y(Te.workspaceId),h("");return}if(Te!=null&&Te.workspacePath){y("__custom__"),h(Te.workspacePath);return}y(""),h("")},[]),D=i.useCallback(Te=>{if(y(Te),Te==="__custom__"){We();return}h("")},[We]),Se=i.useCallback(Te=>{y("__custom__"),h(Te)},[]),Ae=i.useCallback((Te,Ge)=>{S.current=Ge,P.current=Te.selectedWorkspaceKey||"__home__",I(Te.selectedWorkspaceKey||"__home__"),E(Te.initialArgs||""),z(Te.initialModel||""),he(""),te([]);const Ze=Te.providerType?`${e.id}:${Te.providerType}`:null;if(kp(Y.current,Ze)){const qe=xt();fe(qe.textQuery),X(qe.workspaceQuery),ge(qe.modelQuery),de(qe.resumableOnly),ue(qe.sortMode)}Y.current=Ze,H(Te),Te.providerType&&o&&(se(!0),o(Te.providerType).then(qe=>te(qe||[])).catch(qe=>console.warn("Failed to load saved sessions",qe)).finally(()=>se(!1)))},[o,e.id]),Le=i.useMemo(()=>Vc(ce,{textQuery:ye,workspaceQuery:be,modelQuery:ae,resumableOnly:ee,sortMode:we}),[ae,ee,ce,we,ye,be]);i.useEffect(()=>{J&&(Le.some(Te=>Te.providerSessionId===J)||he(""))},[Le,J]);const Pe=i.useCallback(()=>{S.current&&(re(!0),S.current().finally(()=>{S.current=null,re(!1),H(null)}))},[]),He=i.useCallback(()=>{S.current=null,H(null)},[]),Ue=i.useCallback(Te=>{P.current=Te,I(Te)},[]);return i.useEffect(()=>{var Te;q.current!==e.id&&(q.current=e.id,y(p||((Te=u[0])==null?void 0:Te.id)||"__custom__"),h(""),x(""),v([]),T(""),w(!1),fe(xt().textQuery),X(xt().workspaceQuery),ge(xt().modelQuery),de(xt().resumableOnly),ue(xt().sortMode),Y.current=null,R(Wn(f,t.length,r.length)))},[r.length,t.length,p,f,e.id,u]),i.useEffect(()=>{var Te;m!=="__custom__"&&(m&&u.some(Ge=>Ge.id===m)||y(p||((Te=u[0])==null?void 0:Te.id)||"__custom__"))},[p,m,u]),i.useEffect(()=>{K==="ide"&&f||K==="cli"&&t.length>0||K==="acp"&&r.length>0||R(Wn(f,t.length,r.length))},[K,r.length,t.length,f]),{showAllRecent:l,setShowAllRecent:d,hasIdeOptions:f,workspaceRows:u,defaultWorkspaceId:p,workspaceChoice:m,customWorkspacePath:N,browseCurrentPath:j,browseDirectories:b,browseBusy:A,browseError:M,browseDialogOpen:k,activeLauncherKind:K,launchConfirm:O,launchConfirmWorkspaceKeyRef:P,launchConfirmWorkspaceKey:C,launchConfirmArgs:W,launchConfirmModel:$,launchConfirmResumeId:J,launchConfirmSavedSessions:ce,launchConfirmTextFilter:ye,launchConfirmWorkspaceFilter:be,launchConfirmModelFilter:ae,launchConfirmResumableOnly:ee,launchConfirmSortMode:we,filteredLaunchConfirmSavedSessions:Le,launchConfirmSessionsLoading:xe,launchConfirmBusy:ie,resolvedWorkspacePath:le,canCreateMissingWorkspace:ke,openBrowseDialog:We,loadBrowsePath:Ee,handleWorkspaceChoiceChange:D,chooseCustomWorkspacePath:Se,setCustomWorkspacePath:h,setBrowseDialogOpen:w,setActiveLauncherKind:R,openLaunchConfirm:Ae,handleConfirmLaunch:Pe,closeLaunchConfirm:He,setWorkspaceSelectionFromOption:Fe,setLaunchConfirmWorkspaceKeyAndSync:Ue,setLaunchConfirmArgs:E,setLaunchConfirmModel:z,setLaunchConfirmResumeId:he,setLaunchConfirmTextFilter:fe,setLaunchConfirmWorkspaceFilter:X,setLaunchConfirmModelFilter:ge,setLaunchConfirmResumableOnly:de,setLaunchConfirmSortMode:ue}}function $x({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:c,machineAction:l,isStandalone:d,section:f,showBottomNav:u,onBack:p,onSectionChange:m,onOpenConversation:y,onOpenRecent:N,onOpenMachineDetails:h,onMachineUpgrade:j,onLaunchDetectedIde:x,onAddWorkspace:b,onBrowseDirectory:v,onLaunchWorkspaceProvider:A,onListSavedSessions:g}){const M=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",T=r.slice(0,4),k=t.slice(0,3),w=Ex({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:v,onListSavedSessions:g}),K=i.useMemo(()=>T.map(C=>{const{metaText:I,updatedLabel:W}=Nl(C);return{key:`recent-launch:${C.id}`,primary:C.label,secondary:I,updatedLabel:W,onClick:()=>{const{options:E,selectedKey:$}=cs({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspacePath:C.workspace});w.openLaunchConfirm({title:C.kind==="ide"?ns("restart-ide",C.label):C.providerSessionId?to(C.label):ns("start-fresh",C.label),description:C.kind==="ide"?as("restart-ide"):C.providerSessionId?so():as("start-fresh"),confirmLabel:C.kind==="ide"?Ls("restart-ide"):C.providerSessionId?tn(!0):Ls("start-fresh"),busyLabel:C.kind==="ide"?Rs("restart-ide"):C.providerSessionId?Za(!0):Rs("start-fresh"),workspaceOptions:E,selectedWorkspaceKey:$,details:[{label:"Mode",value:M(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const z=E.find(J=>J.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(z),await N({...C,workspace:(z==null?void 0:z.workspacePath)??null})})}}}),[w,N,T]),R=i.useMemo(()=>k.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:it(C.conversation),secondary:cp(C.conversation,{timestampLabel:C.timestamp?oc(C.timestamp):null}),unread:C.unread,onClick:()=>y(C.conversation)})),[y,k]),S=w.showAllRecent?K:K.slice(0,4),O=K.length>0,H=R.length>0,P=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 ${P} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:s.jsx(_a,{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:Ct(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:R.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))})]}),O&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:S.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))}),K.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 ${K.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?"⭐ ":"",un(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(Cs,{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&&b(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:I,selectedKey:W}=cs({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:I,selectedWorkspaceKey:W,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const E=I.find($=>$.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(E),x(C.type,{workspacePath:(E==null?void 0:E.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 I=w.activeLauncherKind==="cli"?"cli":"acp",{options:W,selectedKey:E}=cs({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 ${I.toUpperCase()}`,workspaceOptions:W,selectedWorkspaceKey:E,details:[{label:"Mode",value:I.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:I==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const $=W.find(z=>z.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption($),A(I,C.type,{workspaceId:($==null?void 0:$.workspaceId)??null,workspacePath:($==null?void 0:$.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))})]}),l.message&&s.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.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:()=>b(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:j,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),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:h,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(bn,{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(mo,{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?tn(!!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:eo()}),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:Cp()}),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(W=>W.providerSessionId===w.launchConfirmResumeId);if(!C)return null;const I=Sl(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:I.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:I.providerSessionId}),s.jsx("div",{className:"mt-1",children:I.metaLine}),I.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:I.updatedLabel}),I.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:I.preview})]})})()]}),onConfirm:w.handleConfirmLaunch,onCancel:w.closeLaunchConfirm}),u&&s.jsx(kl,{section:f,onSectionChange:m})]})}function Wr(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Bx(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:Wr(e)}function Kx(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 Ox(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:fs(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 c,l,d,f,u;const a=or(n)?"cli":js(n)?"acp":"ide",o=fs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(or(n)?n.cliName||n.type:js(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:js(n)?o||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((u=(f=(d=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:d.at)==null?void 0:f.call(d,-1))==null?void 0:u.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Wx(e,t){const r=new Map;for(const n of t){const a=xs(n.conversation),o=r.get(a);o?o.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],o=[...a].sort((p,m)=>m.timestamp-p.timestamp)[0]||null,c=(o==null?void 0:o.conversation)||null,l=fa(n),d=a.filter(p=>p.unread||p.requiresAction).length,f=Kx(n),u=[n.platform||"machine",f].filter(Boolean);return{id:n.id,label:Ct(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:d,total:a.length,latestConversation:c,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:l,preview:c?lp(c):"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,c=a.latestTimestamp||a.fallbackActivityAt||0;return c!==o?c-o:n.label.localeCompare(a.label)})}function Fx(e){return e==="chat"}function Lr(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 Hx({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:f,requestedMachineId:u,onRequestedMachineConsumed:p,requestedMobileSection:m,onRequestedMobileSectionConsumed:y,setSelectedTabKey:N,setScreen:h,setSelectedMachineId:j,setSection:x,setMachineBackTarget:b,resetMachineAction:v}){const A=i.useRef(null),g=i.useCallback(M=>{if(!(M!=null&&M.sessionId))return;const T=Yr(M,c),k=Math.max(Date.now(),ss(M),T.lastUpdated||0);Lr("mark_read:start",{tabKey:M.tabKey,sessionId:M.sessionId,displayPrimary:it(M),inboxBucket:T.inboxBucket,unread:T.unread,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,activityAt:ss(M),readAt:k}),l(xs(M)||M.routeId,"mark_session_seen",{sessionId:M.sessionId,providerSessionId:M.providerSessionId,seenAt:k,completionMarker:T.completionMarker}).then(w=>{Lr("mark_read:result",{tabKey:M.tabKey,sessionId:M.sessionId,result:w})}).catch(w=>{Lr("mark_read:error",{tabKey:M.tabKey,sessionId:M.sessionId,error:w instanceof Error?w.message:String(w)})})},[c,l]);return i.useEffect(()=>{var T;if(!n){Fx(o)&&h("inbox"),N(((T=e[0])==null?void 0:T.tabKey)||null),A.current=null;return}if(o!=="chat"){A.current=null;return}const M=`${n.tabKey}:${n.sessionId||""}`;A.current!==M&&(A.current=M,g(n))},[e,g,o,n,h,N]),i.useEffect(()=>{if(!d)return;const M=e.find(T=>T.tabKey===d);M&&(N(M.tabKey),h("chat"),f==null||f())},[e,f,d,h,N]),i.useEffect(()=>{if(!u)return;const M=t.find(T=>T.id===u);M&&(j(M.id),v(),x("machines"),b("inbox"),h("machine"),p==null||p())},[t,p,u,v,b,h,x,j]),i.useEffect(()=>{m&&(x(m),h("inbox"),y==null||y())},[y,m,h,x]),i.useEffect(()=>{const M=r.filter(T=>T.inboxBucket==="task_complete"||T.unread);M.length!==0&&Lr("inbox_state",{screen:o,selectedTabKey:a,items:M.map(T=>{const k=Yr(T.conversation,c);return{liveState:k,tabKey:T.conversation.tabKey,sessionId:T.conversation.sessionId,displayPrimary:it(T.conversation),serverBucket:k.inboxBucket,computedBucket:T.inboxBucket,serverUnread:k.unread,computedUnread:T.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,activityAt:ss(T.conversation)}})})},[r,c,o,a]),{markConversationRead:g}}function Ux(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function hi(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function zx(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Vx({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,o]=i.useState("idle"),[c,l]=i.useState(""),[d,f]=i.useState(null),u=i.useCallback(()=>{o("idle"),l(""),f(null)},[]),p=i.useCallback(async(b,v,A)=>{var g;try{o("loading"),l(`Launching ${v}…`);const M={ideType:v,enableCdp:!0};(g=A==null?void 0:A.workspacePath)!=null&&g.trim()&&(M.workspace=A.workspacePath.trim()),await e(b,"launch_ide",M),o("done"),l(`${v} launch requested`)}catch(M){o("error"),l(M instanceof Error?M.message:"Launch IDE failed"),console.error("Launch IDE failed",M)}},[e]),m=i.useCallback(async(b,v,A)=>{if(v.trim())try{o("loading"),l(A!=null&&A.createIfMissing?"Creating folder…":"Saving workspace…");const g=await e(b,"workspace_add",{path:v.trim(),createIfMissing:(A==null?void 0:A.createIfMissing)===!0});if(g!=null&&g.success){o("done"),l(A!=null&&A.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}o("error"),l((g==null?void 0:g.error)||"Could not save workspace")}catch(g){o("error"),l(g instanceof Error?g.message:"Could not save workspace")}},[e]),y=i.useCallback(async b=>{var v,A,g,M,T,k;try{o("loading"),l("Starting daemon upgrade…");const w=await e(b,"daemon_upgrade",{});if((v=w==null?void 0:w.result)!=null&&v.alreadyLatest){o("done"),l(`Already on v${((A=w==null?void 0:w.result)==null?void 0:A.version)||"latest"}.`);return}if((g=w==null?void 0:w.result)!=null&&g.upgraded||(M=w==null?void 0:w.result)!=null&&M.success){o("done"),l(`Upgrade to v${((T=w==null?void 0:w.result)==null?void 0:T.version)||"latest"} started. Daemon is restarting…`);return}o("error"),l(((k=w==null?void 0:w.result)==null?void 0:k.error)||"Upgrade failed")}catch(w){o("error"),l(w instanceof Error?w.message:"Upgrade failed")}},[e]),N=i.useCallback(async(b,v,A,g)=>{var k,w,K;const M=Date.now(),T={machineId:b,kind:v,providerType:A,workspaceId:(g==null?void 0:g.workspaceId)||null,workspacePath:(g==null?void 0:g.workspacePath)||null,resumeSessionId:(g==null?void 0:g.resumeSessionId)||null,startedAt:M};try{o("loading"),l(`Launching ${A}…`),f(T);const R={cliType:A};(k=g==null?void 0:g.workspacePath)!=null&&k.trim()?R.dir=g.workspacePath.trim():g!=null&&g.workspaceId&&(R.workspaceId=g.workspaceId),g!=null&&g.resumeSessionId&&(R.resumeSessionId=g.resumeSessionId),(w=g==null?void 0:g.args)!=null&&w.trim()&&(R.cliArgs=g.args.trim().split(/\s+/).filter(Boolean)),(K=g==null?void 0:g.model)!=null&&K.trim()&&(R.initialModel=g.model.trim());const S=await e(b,"launch_cli",R),O=(S==null?void 0:S.result)||S,H=(O==null?void 0:O.sessionId)||(O==null?void 0:O.id);if(S!=null&&S.success&&H){f(null),o("done"),l(`${A} launched`),t(Yt(H));return}if(S!=null&&S.success){o("loading"),l(`${A} launch requested — waiting for session…`);return}f(null),o("error"),l((S==null?void 0:S.error)||(O==null?void 0:O.error)||`Could not launch ${v.toUpperCase()} workspace`)}catch(R){if(zx(R)){o("loading"),l(`${A} launch requested — waiting for session…`);return}f(null),o("error"),l(R instanceof Error?R.message:`Could not launch ${v.toUpperCase()} workspace`)}},[t,e]),h=i.useCallback(async(b,v)=>{try{const A=await e(b,"list_saved_sessions",{providerType:v,kind:"cli",limit:30}),g=(A==null?void 0:A.result)??A;return Array.isArray(g==null?void 0:g.sessions)?g.sessions:[]}catch(A){return console.error("Failed to list saved sessions on mobile:",A),[]}},[e]),j=i.useCallback(async(b,v)=>xn(e,b,v),[e]);i.useEffect(()=>{if(!d)return;const b=hi(d.workspacePath),v=r.find(g=>{var R,S,O,H;if(!g||g.type==="adhdev-daemon"||Ux(g.daemonId||g.id)!==d.machineId||(g.transport==="acp"?"acp":g.transport==="pty"?"cli":null)!==d.kind||String(g.agentType||g.type||"")!==d.providerType)return!1;const w=String(g.providerSessionId||"");if(d.resumeSessionId&&w)return w===d.resumeSessionId;if(b){const P=hi(g.workspace||g.runtimeWorkspaceLabel);return P?P===b:!1}return Number(g.lastUpdated||g._lastUpdate||g.timestamp||((H=(O=(S=(R=g.activeChat)==null?void 0:R.messages)==null?void 0:S.at)==null?void 0:O.call(S,-1))==null?void 0:H.timestamp)||0)>=d.startedAt-5e3});if(!v)return;const A=Ic({entrySessionId:v.sessionId,entryInstanceId:v.instanceId,entryRouteId:v.id,conversations:n});A&&(f(null),o("done"),l(`${d.providerType} launched`),t(Yt(A)))},[n,r,t,d]),i.useEffect(()=>{if(!d)return;const b=window.setTimeout(()=>{f(v=>!v||v.startedAt!==d.startedAt?v:(o("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(b)},[d]);const x=i.useCallback(async(b,v)=>{if(v.kind==="ide"&&v.providerType){await p(b,v.providerType,{workspacePath:v.workspace||null});return}(v.kind==="cli"||v.kind==="acp")&&v.providerType&&await N(b,v.kind,v.providerType,{workspacePath:v.workspace||null,resumeSessionId:v.providerSessionId||null})},[p,N]);return{machineAction:{state:a,message:c},resetMachineAction:u,handleLaunchDetectedIde:p,handleAddWorkspace:m,handleMachineUpgrade:y,handleLaunchWorkspaceProvider:N,handleListSavedSessions:h,handleBrowseDirectory:j,handleOpenRecent:x}}function Gx({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:c,setSelectedMachineId:l,setSection:d,setMachineBackTarget:f}){const u=i.useCallback(x=>{o(x.tabKey),c("chat"),n(x)},[n,c,o]),p=i.useCallback(x=>{const b=e.find(v=>v.routeId===x.routeId&&v.streamSource==="native");b&&(o(b.tabKey),c("chat"),n(b))},[e,n,c,o]),m=i.useCallback(()=>{n(t),c("inbox")},[n,t,c]),y=i.useCallback((x,b="inbox")=>{l(x),a(),d("machines"),f(b),c("machine")},[a,f,c,d,l]),N=i.useCallback(x=>{const b=xs(x);b&&y(b,"chat")},[y]),h=i.useCallback(()=>{a(),c(r)},[r,a,c]),j=i.useCallback(x=>{d(x),c("inbox")},[c,d]);return{openConversation:u,openNativeConversation:p,backFromConversation:m,openMachine:y,openConversationMachine:N,backFromMachine:h,changeMachineSection:j}}function ps(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function qx(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function Yx({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,userName:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:f,requestedMachineId:u,onRequestedMachineConsumed:p,requestedMobileSection:m,onRequestedMobileSectionConsumed:y,onOpenHistory:N,onOpenRemote:h,onStopCli:j,wsStatus:x,isConnected:b,onShowAllHiddenConversations:v,onHideConversation:A,onOpenNewSession:g,liveSessionInboxState:M,setCliViewModeOverrides:T}){const[k,w]=i.useState(()=>{var Z;return((Z=e[0])==null?void 0:Z.tabKey)||null}),[K,R]=i.useState(()=>e[0]?"chat":"inbox"),[S,O]=i.useState("chats"),[H,P]=i.useState(null),[C,I]=i.useState("inbox"),W=i.useRef([]),E=Ps(),$="0.9.60",z=i.useMemo(()=>e.find(Z=>Z.tabKey===k)||e[0]||null,[e,k]),J=i.useMemo(()=>z?r.find(Z=>Z.id===z.routeId):void 0,[r,z]),he=i.useMemo(()=>!z||Xe(z)||!et(z)?null:Es(z),[z]),ce=i.useMemo(()=>r.filter(Z=>Z.type==="adhdev-daemon").sort(Wa),[r]),te=i.useMemo(()=>ce.find(Z=>Z.id===H)||null,[ce,H]),ye=mn({sendDaemonCommand:a,activeConv:z||void 0,setActionLogs:o,isStandalone:c}),fe=Vx({sendDaemonCommand:a,navigate:E,ides:r,conversations:e}),be=i.useMemo(()=>e.map(Z=>{const Ce=K==="chat"&&(z==null?void 0:z.tabKey)===Z.tabKey,Ee=dn(Z,M,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Ce}),We=ss(Z),Fe=Wc(Z);return{conversation:Z,timestamp:We,preview:Fe,unread:Ee.unread,requiresAction:Ee.requiresAction,isWorking:Ee.isWorking,inboxBucket:Ee.inboxBucket}}),[e,M,K,z]),{markConversationRead:X}=Hx({conversations:e,machineEntries:ce,items:be,selectedConversation:z,selectedTabKey:k,screen:K,liveSessionInboxState:M,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:f,requestedMachineId:u,onRequestedMachineConsumed:p,requestedMobileSection:m,onRequestedMobileSectionConsumed:y,setSelectedTabKey:w,setScreen:R,setSelectedMachineId:P,setSection:O,setMachineBackTarget:I,resetMachineAction:fe.resetMachineAction}),ae=Gx({conversations:e,selectedConversation:z,machineBackTarget:C,markConversationRead:X,resetMachineAction:fe.resetMachineAction,setSelectedTabKey:w,setScreen:R,setSelectedMachineId:P,setSection:O,setMachineBackTarget:I}),ge=i.useMemo(()=>Wr(be.filter(Z=>Z.requiresAction)),[be]),ee=i.useMemo(()=>Wr(be.filter(Z=>Z.unread&&!Z.requiresAction)),[be]),de=i.useMemo(()=>Bx(be.filter(Z=>!Z.unread&&!Z.requiresAction&&Z.isWorking),W.current),[be]);i.useEffect(()=>{W.current=de.map(Z=>Z.conversation.tabKey)},[de]);const we=i.useMemo(()=>Wr(be.filter(Z=>!Z.unread&&!Z.requiresAction&&!Z.isWorking)),[be]),ue=i.useMemo(()=>te?be.filter(Z=>xs(Z.conversation)===te.id):[],[be,te]),xe=i.useMemo(()=>Ox(te,r),[r,te]),se=(te==null?void 0:te.version)||null,ie=!!te&&!!se&&!0&&se!==$,re=i.useMemo(()=>(te==null?void 0:te.availableProviders)||[],[te]),q=i.useMemo(()=>re.filter(Z=>ps(Z,"cli")).map(Z=>({type:Z.type,displayName:Z.displayName||Z.type,icon:Z.icon})),[re]),Y=i.useMemo(()=>re.filter(Z=>ps(Z,"acp")).map(Z=>({type:Z.type,displayName:Z.displayName||Z.type,icon:Z.icon})),[re]),le=i.useMemo(()=>Wx(ce,be),[be,ce]),ke=i.useCallback(async Z=>{te&&await fe.handleOpenRecent(te.id,Z)},[fe,te]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:K==="chat"&&z?s.jsx(Ax,{selectedConversation:z,isAcp:Xe(z),isStandalone:c,selectedIdeEntry:J,actionLogs:n,userName:l,isSendingChat:ye.isSendingChat,sendFeedbackMessage:ye.sendFeedbackMessage,isFocusingAgent:ye.isFocusingAgent,handleModalButton:ye.handleModalButton,handleRelaunch:ye.handleRelaunch,onBack:ae.backFromConversation,onOpenNativeConversation:ae.openNativeConversation,onOpenMachine:ae.openConversationMachine,onHideConversation:A,onOpenHistory:N,onOpenRemote:h,onStopCli:j,cliViewMode:he,onSetCliViewMode:async Z=>{await hl({conversation:z,mode:Z,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:T})},handleSendChat:ye.handleSendChat,handleFocusAgent:ye.handleFocusAgent}):K==="machine"&&te?s.jsx($x,{selectedMachineEntry:te,selectedMachineConversations:ue,selectedMachineRecentLaunches:xe,cliProviders:q,acpProviders:Y,selectedMachineNeedsUpgrade:ie,appVersion:$,machineAction:fe.machineAction,isStandalone:c,section:S,showBottomNav:C==="inbox",onBack:ae.backFromMachine,onSectionChange:ae.changeMachineSection,onOpenConversation:ae.openConversation,onOpenRecent:ke,onOpenMachineDetails:()=>E(`/machines/${te.id}`),onMachineUpgrade:()=>fe.handleMachineUpgrade(te.id),onLaunchDetectedIde:(Z,Ce)=>fe.handleLaunchDetectedIde(te.id,Z,Ce),onAddWorkspace:(Z,Ce)=>fe.handleAddWorkspace(te.id,Z,Ce),onBrowseDirectory:Z=>fe.handleBrowseDirectory(te.id,Z),onLaunchWorkspaceProvider:(Z,Ce,Ee)=>fe.handleLaunchWorkspaceProvider(te.id,Z,Ce,Ee),onListSavedSessions:Z=>fe.handleListSavedSessions(te.id,Z)}):s.jsx(Lx,{section:S,attentionItems:ge,unreadItems:ee,workingItems:de,completedItems:we,hiddenConversations:t,machineCards:le,getAvatarText:qx,actionLogs:n,sendDaemonCommand:a,onOpenConversation:ae.openConversation,onShowAllHidden:v,onHideConversation:A,onOpenNewSession:g,onOpenMachine:ae.openMachine,onOpenSettings:()=>E("/settings"),onSectionChange:O,wsStatus:x,isConnected:b,isStandalone:c})})}function Fn(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function Xx({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const c=i.useRef(0),[l,d]=i.useState(!1),[f,u]=i.useState(null),p=i.useCallback(()=>{c.current=0,d(!1),u(null)},[]);i.useEffect(()=>(window.addEventListener("dragend",p),window.addEventListener("drop",p),()=>{window.removeEventListener("dragend",p),window.removeEventListener("drop",p)}),[p]);const m=i.useCallback(j=>{j.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,d(!0))},[]),y=i.useCallback(j=>{if(!j.dataTransfer.types.includes("text/tab-key"))return;if(j.preventDefault(),!Fn(t,r)){u("merge");return}const x=j.currentTarget.getBoundingClientRect(),b=j.clientX-x.left,v=x.width/3;b<v?u("split-left"):b>v*2?u("split-right"):u("merge")},[t,r]),N=i.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,d(!1),u(null))},[]),h=i.useCallback(j=>{c.current=0,d(!1);const x=j.dataTransfer.getData("text/tab-key"),b=x?e.some(A=>A.tabKey===x):!1,v=f;if(u(null),o(),!!x){if(j.preventDefault(),v==="split-left"&&Fn(t,r)){r==null||r(x,"split-left");return}if(v==="split-right"&&Fn(t,r)){r==null||r(x,"split-right");return}if(b){a(x);return}n==null||n(x)}},[e,f,t,r,n,a,o]);return{dragOver:l,dropAction:f,resetDragState:p,handleDragEnter:m,handleDragOver:y,handleDragLeave:N,handleDrop:h}}function Jx(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 Qx({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,c]=i.useState(t??null),[l,d]=i.useState(r??[]),[f,u]=i.useState(null),p=i.useRef(null),m=i.useRef(null),y=i.useRef(n),N=i.useRef(a);i.useEffect(()=>{y.current=n},[n]),i.useEffect(()=>{N.current=a},[a]),i.useEffect(()=>{t&&t!==o&&c(t)},[t,o]),i.useEffect(()=>{d(T=>{const k=Jx(T,e);return k.length===T.length&&k.every((w,K)=>w===T[K])?T:k})},[e]);const h=i.useMemo(()=>{const T=f??l;if(T.length===0)return e;const k=new Map(T.map((w,K)=>[w,K]));return[...e].sort((w,K)=>{const R=k.get(w.tabKey)??999,S=k.get(K.tabKey)??999;return R-S})},[e,f,l]);i.useEffect(()=>{var k,w;if(h.length===0){o!==null&&(c(null),(k=y.current)==null||k.call(y,null));return}if(o&&h.some(K=>K.tabKey===o))return;const T=h[0].tabKey;T!==o&&(c(T),(w=y.current)==null||w.call(y,T))},[h,o]);const j=i.useMemo(()=>h.find(T=>T.tabKey===o),[h,o]),x=i.useCallback(T=>{var k;c(T),(k=y.current)==null||k.call(y,T)},[]),b=i.useCallback((T,k,w)=>{d(K=>{var H;const R=K.filter(P=>P!==T),S=R.indexOf(k);if(S<0)return K;const O=w==="left"?S:S+1;return R.splice(O,0,T),(H=N.current)==null||H.call(N,R),R}),u(null)},[]),v=i.useCallback((T,k,w)=>{const R=(l.length>0?l:e.map(H=>H.tabKey)).filter(H=>H!==T),S=R.indexOf(k);if(S<0)return;const O=w==="left"?S:S+1;R.splice(O,0,T),p.current=R,u(R)},[l,e]),A=i.useCallback(()=>{var k;const T=p.current;T&&(d(T),(k=N.current)==null||k.call(N,T))},[]),g=i.useCallback(()=>{p.current=null,u(null)},[]),M=i.useCallback(T=>{d(k=>{var K;const w=k.filter(R=>R!==T);return w.push(T),(K=N.current)==null||K.call(N,w),w})},[]);return{activeTabId:o,activeConv:j,sortedConversations:h,previewOrderRef:p,draggingTabRef:m,selectTab:x,handleTabReorder:b,updatePreviewOrder:v,commitPreviewOrder:A,clearPreviewOrder:g,moveTabToEnd:M,setDraggingTabKey:T=>{m.current=T}}}function Zx({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 po({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 c=!r&&!n,l=n&&!!o,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",f=n?zc: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:f}),l&&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:Et,"aria-label":Et,children:[s.jsx(Zi,{size:14}),s.jsx("span",{children:Et})]})}),c&&s.jsx(jl,{}),c&&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 Cl="adhdev-tab-shortcuts";function Tl(){try{return JSON.parse(localStorage.getItem(Cl)||"{}")}catch{return{}}}function Ml({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,c]=i.useState(()=>Tl()),[l,d]=i.useState(null),f=i.useCallback(p=>{const m=[];return p.metaKey&&m.push(a?"⌘":"Meta"),p.ctrlKey&&m.push("Ctrl"),p.altKey&&m.push(a?"⌥":"Alt"),p.shiftKey&&m.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(m.push(p.key.length===1?p.key.toUpperCase():p.key),m.join("+"))},[a]),u=i.useCallback(p=>{c(p);try{localStorage.setItem(Cl,JSON.stringify(p))}catch{}},[]);return i.useEffect(()=>{if(!e||!l)return;const p=m=>{if(m.preventDefault(),m.stopPropagation(),m.key==="Escape"){d(null);return}const y=f(m);if(!y)return;const N={...o};for(const[h,j]of Object.entries(N))j===y&&delete N[h];N[l]=y,u(N),d(null)};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[e,l,o,u,f]),i.useEffect(()=>{if(!e)return;const p=m=>{if(!(!m.ctrlKey&&!m.metaKey&&!m.altKey)){for(const[y,N]of Object.entries(o))if(t.includes(y)&&f(m)===N){m.preventDefault(),r(),n(y);return}}};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[e,o,t,r,n,f]),{isMac:a,tabShortcuts:o,shortcutListening:l,setShortcutListening:d,saveShortcuts:u}}const Hn=e=>{e.preventDefault()},eb=i.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:c,draggingTabRef:l,onFocus:d,onSelectTab:f,onConversationActivated:u,onPreviewReorder:p,onReorderTab:m,onCommitPreviewOrder:y,onClearPreviewOrder:N,onDragStateReset:h,onDragTabKeyChange:j,onReceiveTab:x,onOpenContextMenu:b,longPressTimer:v,isGroupActive:A}){const g=Ds(t),M=g.isGenerating?"agent-tab-generating":g.isWaiting?"agent-tab-waiting":"",T=g.isReconnecting,k=i.useCallback(I=>{l.current=t.tabKey,j(t.tabKey),I.dataTransfer.setData("text/tab-key",t.tabKey),I.dataTransfer.effectAllowed="move"},[t.tabKey,l,j]),w=i.useCallback(()=>{l.current=null,j(null),y(),N(),h()},[l,j,y,N,h]),K=i.useCallback(I=>{const W=l.current;if(!(!W||W===t.tabKey)&&I.dataTransfer.types.includes("text/tab-key")){I.preventDefault(),I.stopPropagation();const E=I.currentTarget.getBoundingClientRect(),$=I.clientX<E.left+E.width/2?"left":"right";p(W,t.tabKey,$)}},[t.tabKey,l,p]),R=i.useCallback(I=>{I.preventDefault(),I.stopPropagation();const W=I.dataTransfer.getData("text/tab-key");if(W&&W!==t.tabKey){const E=I.currentTarget.getBoundingClientRect(),$=I.clientX<E.left+E.width/2?"left":"right";c.includes(W)?m(W,t.tabKey,$):x&&x(W)}N()},[t.tabKey,c,m,x,N]),S=i.useCallback(I=>{I.stopPropagation(),d(),f(t.tabKey),u(t)},[t,u,d,f]),O=i.useCallback(I=>{I.preventDefault(),b(I.clientX,I.clientY,t.tabKey)},[t.tabKey,b]),H=i.useCallback(I=>{const W=I.touches[0];v.current=setTimeout(()=>{b(W.clientX,W.clientY,t.tabKey)},600)},[t.tabKey,v,b]),P=i.useCallback(()=>{v.current&&clearTimeout(v.current)},[v]),C=["adhdev-dockview-tab",M,r&&"is-active",A&&"is-group-active",T&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:C,draggable:!0,onDragStart:k,onDragEnd:w,onDragOver:K,onDrop:R,onClick:S,onContextMenu:O,onTouchStart:H,onTouchEnd:P,onTouchMove:P,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:g.isGenerating?s.jsx("div",{className:"tab-spinner"}):g.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):T?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):g.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:it(t),children:it(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[T?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:rs(t)}):g.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[rs(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:rs(t)}),s.jsx(Is,{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 tb({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:f,onCommitPreviewOrder:u,onClearPreviewOrder:p,onDragStateReset:m,onDragTabKeyChange:y,onReceiveTab:N,onHideTab:h,isGroupActive:j,allowTabShortcuts:x=!0}){const[b,v]=i.useState(null),A=i.useRef(null),g=i.useRef(null),M=i.useMemo(()=>e.map(O=>O.tabKey),[e]);dr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(b==null?void 0:b.tabKey)||null});const{isMac:T,tabShortcuts:k,shortcutListening:w,setShortcutListening:K,saveShortcuts:R}=Ml({enabled:x,sortedTabKeys:e.map(O=>O.tabKey),onFocus:o,onSelectTab:c});i.useEffect(()=>{if(!b)return;const O=H=>{const P=document.querySelector("[data-pane-context-menu]");P&&P.contains(H.target)||v(null)};return window.addEventListener("mousedown",O,!0),()=>window.removeEventListener("mousedown",O,!0)},[b]),i.useEffect(()=>{const O=g.current;if(!O)return;const H=P=>{Math.abs(P.deltaY)<=Math.abs(P.deltaX)||(P.preventDefault(),O.scrollLeft+=P.deltaY)};return O.addEventListener("wheel",H,{passive:!1}),()=>O.removeEventListener("wheel",H)},[]);const S=i.useCallback((O,H,P)=>{v({x:O,y:H,tabKey:P})},[]);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:g,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(O=>s.jsx(eb,{conv:O,isActive:t===O.tabKey,isDraggedTab:a.current===O.tabKey,isTaskCompleteUnread:n.has(O.tabKey),shortcut:x?k[O.tabKey]:void 0,conversationKeys:M,draggingTabRef:a,onFocus:o,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:f,onCommitPreviewOrder:u,onClearPreviewOrder:p,onDragStateReset:m,onDragTabKeyChange:y,onReceiveTab:N,onOpenContextMenu:S,longPressTimer:A,isGroupActive:j},O.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),b&&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:b.x,top:b.y},children:[x&&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:Hn,onClick:O=>{O.stopPropagation(),K(b.tabKey),v(null)},children:["⌨ ",k[b.tabKey]?`Change shortcut (${k[b.tabKey]})`:"Set shortcut"]}),k[b.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:Hn,onClick:()=>{const O={...k};delete O[b.tabKey],R(O),v(null)},children:"✕ Remove shortcut"})]}),h&&s.jsxs(s.Fragment,{children:[x&&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:Hn,onClick:()=>{h(b.tabKey),v(null)},children:"🚫 Hide from Dashboard"})]})]}),x&&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:()=>K(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:O=>O.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. ",T?"⌘+1":"Ctrl+1",", ",T?"⌥+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 sb({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,hasRegisteredMachines:l,userName:d,groupIndex:f,onFocus:u,isSplitMode:p,numGroups:m,onMoveTab:y,onReceiveTab:N,style:h,onActiveTabChange:j,initialActiveTabId:x,initialTabOrder:b,onTabOrderChange:v,onHideTab:A,isFocused:g,allowTabShortcuts:M=!0,onOpenNewSession:T,liveSessionInboxState:k}){const{sendCommand:w}=mt(),K=i.useRef(null),{activeTabId:R,activeConv:S,sortedConversations:O,draggingTabRef:H,selectTab:P,handleTabReorder:C,updatePreviewOrder:I,commitPreviewOrder:W,clearPreviewOrder:E,moveTabToEnd:$,setDraggingTabKey:z}=Qx({conversations:e,initialActiveTabId:x,initialTabOrder:b,onActiveTabChange:j,onTabOrderChange:v}),J=mn({sendDaemonCommand:a,activeConv:S,setActionLogs:o,isStandalone:c}),{dragOver:he,dropAction:ce,resetDragState:te,handleDragEnter:ye,handleDragOver:fe,handleDragLeave:be,handleDrop:X}=Xx({conversations:e,numGroups:m,onMoveTab:y,onReceiveTab:N,onOwnTabDrop:$,onClearPreviewOrder:E}),ae=S&&!Xe(S)&&Es(S)==="terminal",ge=i.useMemo(()=>S?t.find(ue=>ue.id===S.routeId):void 0,[t,S]),ee=i.useMemo(()=>S?n.filter(ue=>ue.routeId===S.tabKey):[],[n,S]),de=i.useMemo(()=>new Set(O.filter(ue=>qu(ue,k,{isOpenConversation:ue.tabKey===R})).map(ue=>ue.tabKey)),[R,k,O]);dr("PaneGroup",{groupIndex:f,conversationCount:e.length,activeTabId:R,dragOver:he});const we=i.useCallback(ue=>{ue.streamSource==="agent-stream"&&ue.agentType&&w(ue.routeId,jc(),{agentType:ue.agentType,...ue.sessionId&&{targetSessionId:ue.sessionId}}).catch(()=>{})},[w]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...h,outline:he?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(tb,{conversations:O,activeTabId:R,groupIndex:f,numGroups:m,unreadTabKeys:de,draggingTabRef:H,onFocus:u,onSelectTab:P,onConversationActivated:we,onPreviewReorder:I,onReorderTab:C,onCommitPreviewOrder:W,onClearPreviewOrder:E,onDragStateReset:te,onDragTabKeyChange:z,onMoveTab:y,onReceiveTab:N,onHideTab:A,isGroupActive:g??!1,allowTabShortcuts:M}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ye,onDragOver:fe,onDragLeave:be,onDrop:X,children:[he&&s.jsx(Zx,{dropAction:ce,canSplit:!!(m<4&&y)}),S?s.jsx(fo,{activeConv:S,clearToken:r[S.tabKey]||0,isCliTerminal:!!ae,ideEntry:ge,terminalRef:K,handleModalButton:J.handleModalButton,handleRelaunch:J.handleRelaunch,handleSendChat:J.handleSendChat,isSendingChat:J.isSendingChat,sendFeedbackMessage:J.sendFeedbackMessage,handleFocusAgent:J.handleFocusAgent,isFocusingAgent:J.isFocusingAgent,actionLogs:ee,userName:d,isInputActive:!p||!!g}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(po,{conversationsCount:e.length,isSplitMode:p,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:T})})]})]})}function rb({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:f,isStandalone:u,hasRegisteredMachines:p,userName:m,focusedGroup:y,focusGroup:N,moveTabToGroup:h,splitTabRelative:j,closeGroup:x,handleResizeStart:b,groupActiveTabIds:v,setGroupActiveTab:A,groupTabOrders:g,setGroupTabOrder:M,toggleHiddenTab:T,onOpenNewSession:k,allowTabShortcuts:w=!0,liveSessionInboxState:K}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((R,S)=>{const O=t&&n.length===r?`${n[S]}%`:void 0;return s.jsxs(kt.Fragment,{children:[t&&S>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=>b(S-1,H),onDoubleClick:()=>x(S),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(sb,{style:t?{flexBasis:O??`${100/r}%`,flexGrow:O?0:1,flexShrink:O?0:1}:void 0,conversations:R,clearedTabs:o,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:f,isStandalone:u,hasRegisteredMachines:p,userName:m,groupIndex:S,isFocused:t&&y===S,onFocus:()=>N(S),isSplitMode:t,numGroups:r,onMoveTab:(H,P)=>{P==="left"&&S>0?h(H,S-1):P==="right"&&S<r-1?h(H,S+1):P==="split-left"&&r<4?j(H,S,"left"):P==="split-right"&&r<4&&j(H,S,"right")},onReceiveTab:H=>h(H,S),onActiveTabChange:H=>A(S,H),initialActiveTabId:v[S],initialTabOrder:g[S],onTabOrderChange:H=>M(S,H),onHideTab:T,onOpenNewSession:k,allowTabShortcuts:w,liveSessionInboxState:K})]},S)})})}function Al({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=i.useState(null),[c,l]=i.useState(null);i.useEffect(()=>e?ot.onScreenshot("ide-page",(u,p)=>{if(u!==e)return;const m=new FileReader;m.onload=()=>o(m.result),m.readAsDataURL(p)}):void 0,[e]),i.useEffect(()=>{r!=="connected"&&o(null)},[r]),i.useEffect(()=>{var u;return e?((u=ot.onStatus)==null?void 0:u.call(ot,(p,m)=>{p===e&&m!=null&&m.screenshotUsage&&l(m.screenshotUsage)}))||(()=>{}):void 0},[e]),i.useEffect(()=>{o(null)},[e,t]),i.useEffect(()=>{const f=e?ot.get(e):null;if(!(!f||r!=="connected"))return n!=="chat"&&t?f.startScreenshots(t):f.stopScreenshots(t),()=>{f.stopScreenshots(t)}},[n,r,t,e]);const d=i.useCallback(async(f,u)=>{const p=e?ot.get(e):null;return!p||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):p.sendInput(f,u,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:d}}const Il="adhdev-dashboard-action-shortcuts",nb=1200,ab=[["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 ob(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function st(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 Ll(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:st("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:st("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:st("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:st("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:st("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:st("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:st("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:st("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:st("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:st("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:st("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:st("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:st("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:st("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:st("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:st("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:st("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:st("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:st("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:st("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:st("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:st("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:st("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:st("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:st("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:st("toggleCliView",e)}]}function Ca(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function nn(e){const t=Object.fromEntries(Ll(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Il)||"{}"),n={...t,...r};for(const[a,o]of ab)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function Rl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function ib({enabled:e=!0,onTrigger:t}){const r=ob(),[n,a]=i.useState(()=>nn(r)),[o,c]=i.useState(null),[l,d]=i.useState([]),f=i.useRef({parts:[],timer:null}),u=i.useCallback(h=>{const j=[];return h.metaKey&&j.push(r?"⌘":"Meta"),h.ctrlKey&&j.push("Ctrl"),h.altKey&&j.push(r?"⌥":"Alt"),h.shiftKey&&h.key.length!==1&&j.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(j.push(Rl(h.key)),j.join("+"))},[r]),p=i.useCallback(h=>{a(h);try{localStorage.setItem(Il,JSON.stringify(h))}catch{}},[]);i.useEffect(()=>{const h=nn(r),j=Object.entries(n),x=Object.entries(h);j.length===x.length&&j.every(([b,v])=>h[b]===v)||p(h)},[n,r,p]);const m=i.useCallback(()=>{typeof window<"u"&&f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current={parts:[],timer:null}},[]),y=i.useCallback(()=>{typeof window>"u"||(f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current.timer=window.setTimeout(()=>{f.current={parts:[],timer:null}},nb))},[]);i.useEffect(()=>{if(!o)return;const h=j=>{if(j.preventDefault(),j.stopPropagation(),j.key==="Escape"){c(null),d([]);return}const x=u(j);if(!x)return;const v=!(j.metaKey||j.ctrlKey||j.altKey)&&/^[A-Z0-9]$/.test(x);if(l.length===0&&v){d([x]);return}const g=[...l,x].slice(0,2).join(" "),M={...n};for(const[T,k]of Object.entries(M))k===g&&delete M[T];M[o]=g,p(M),c(null),d([])};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[n,u,p,o,l]),i.useEffect(()=>{if(!e||o)return;const h=j=>{if(j.defaultPrevented)return;const x=u(j);if(!x)return;const b=j.metaKey||j.ctrlKey||j.altKey;if(Ca(j.target))return;const v=f.current.parts,A=b?[x]:[...v.slice(-1),x].slice(-2),g=A.join(" "),M=A[A.length-1],T=Object.entries(n).filter(([,S])=>!!S),k=T.find(([,S])=>S===g);if(k){j.preventDefault(),m(),t(k[0]);return}if(T.some(([,S])=>S.startsWith(`${g} `))){j.preventDefault(),f.current.parts=A,y();return}const K=T.find(([,S])=>S===M);if(K){j.preventDefault(),m(),t(K[0]);return}if(T.some(([,S])=>S.startsWith(`${M} `))){j.preventDefault(),f.current.parts=[M],y();return}m()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[n,y,e,u,t,m,o]),i.useEffect(()=>()=>m(),[m]);const N=i.useMemo(()=>Ll(r),[r]);return{isMac:r,actionDefinitions:N,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:d,saveShortcuts:p}}function cb({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 _l(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function xi({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!_l(n):!0}function lb({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:_l(r)}const Pl=1e3,db=4;function bi(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function gi(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function ub({detachDelayMs:e=Pl,stillnessThresholdPx:t=db,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,c=null,l=null,d=null,f=null,u=!1;const p=()=>{f!=null&&(a(f),f=null)},m=()=>{p(),l=null},y=()=>{p(),o=null,c=null,l=null,d=null,u=!1},N=()=>{!o||!l||!d||u||f!=null||(f=n(()=>{f=null,!(!o||!l||!d||u)&&bi(d,c)&&(gi(l,d,t)||(u=!0,r({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},h=x=>{if(!(!o||u)){if(!bi(x,c)){d={clientX:x.clientX,clientY:x.clientY},m();return}(!l||gi(l,x,t))&&(p(),l={clientX:x.clientX,clientY:x.clientY}),d={clientX:x.clientX,clientY:x.clientY},N()}},j=x=>{!o||u||(x&&(d={clientX:x.clientX,clientY:x.clientY}),m())};return{startDrag:x=>{p(),o=x.panelId,c=x.selfPanelBounds??null,l=null,d={clientX:x.clientX,clientY:x.clientY},u=!1},markSelfPanel:h,markNonSelfPanel:j,markNoDropTarget:j,markDockTarget:j,endDrag:y,isDragging:()=>o!=null,hasDetached:()=>u,dispose:y}}function fb(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}const Dl=i.createContext(null);function gn(){const e=i.useContext(Dl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Fr(e){return it(e)||e.tabKey}function mb(e){return`remote:${e}`}function Lt(e){return e.startsWith("remote:")}function yi(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function pb(e){e.preventDefault()}function Un(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 zn(e,t){e.classList.remove(aa.className,oa.className),e.classList.add(t==="light"?aa.className:oa.className)}function vi(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 hb(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 xb(e,t,r){var c;const n=[t];let a;for(const l of n){let d;for(const f of l){const u=e.addPanel({id:f.tabKey,component:"conversation",title:Fr(f),params:{kind:"conversation",tabKey:f.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??((c=t[0])==null?void 0:c.tabKey)??null}function wi(e,t){const r=new Set(t.map(n=>n.tabKey));for(const n of[...e.panels])Lt(n.id)||r.has(n.id)||e.removePanel(n);for(const n of t){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==Fr(n)&&a.api.setTitle(Fr(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Fr(n),params:{kind:"conversation",tabKey:n.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 ji(e,t,r){var d,f;const n=r?mb(r):null;for(const u of[...e.panels])Lt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=Pt(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),c=Uc(a);if(o){o.title!==c&&o.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((f=e.panels.find(u=>!Lt(u.id)))==null?void 0:f.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function bb({params:e,api:t}){var p;const r=gn(),n=i.useRef(null),[a,o]=i.useState(t.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=mn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});i.useEffect(()=>{o(t.isActive);const m=[t.onDidActiveChange(y=>o(y.isActive)),t.onDidActiveGroupChange(y=>{if(!t.isActive&&!y.isActive){o(!1);return}o(t.isActive)})];return()=>{for(const y of m)y.dispose()}},[t]);const d=i.useMemo(()=>c?r.ides.find(m=>m.id===c.routeId):void 0,[r.ides,c]),f=i.useMemo(()=>c?r.actionLogs.filter(m=>m.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(po,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const u=!Xe(c)&&Es(c)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(fo,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:u,ideEntry:d,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((p=r.scrollToBottomRequest)==null?void 0:p.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:a})})}function gb({params:e}){var d;const t=gn(),r=i.useMemo(()=>Pt([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=i.useMemo(()=>t.ides.find(f=>f.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:c,handleRemoteAction:l}=Al({doId:a,targetSessionId:r?wc(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:c,transportType:r.transport,onAction:l})}):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 yb(){const e=gn();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(po,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function vb(e){var y,N;hb(e);const t=gn(),r=i.useCallback(h=>{"button"in h&&h.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const h=Pt([...t.conversationsByTabKey.values()],e.params.routeId),j=((y=e.api.group.activePanel)==null?void 0:y.id)===e.api.id,x=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${j?" is-active":""}${x?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(h==null?void 0:h.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:h!=null&&h.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:h.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=((N=e.api.group.activePanel)==null?void 0:N.id)===e.api.id,o=e.api.isGroupActive,c=dn(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,d=c.isConnecting,f=c.isGenerating,u=c.isWaiting,p=c.unread,m=t.tabShortcuts[n.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${o?" is-group-active":""}${l?" is-reconnecting":""}`,title:it(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:h=>{var j;h.preventDefault(),r(h),t.openTabContextMenu({x:h.clientX,y:h.clientY,tabKey:n.tabKey,sourceDocument:((j=h.target)==null?void 0:j.ownerDocument)??document})},children:[p&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:f?s.jsx("div",{className:"tab-spinner"}):u?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?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:it(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:rs(n)}):d?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:rs(n)}):s.jsx("span",{children:rs(n)})})]}),m&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:m,children:m})]})}function wb({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:d,userName:f,toggleHiddenTab:u,actionShortcuts:p,registerActionHandlers:m,onActiveTabChange:y,onOpenNewSession:N,onRequestScrollToBottom:h,requestedActiveTabKey:j,requestedRemoteIdeId:x,onRequestedActiveTabConsumed:b,scrollToBottomRequest:v,liveSessionInboxState:A,layoutProfile:g}){var Ze,qe,tt;const{theme:M}=ao(),{sendCommand:T}=mt(),k=i.useRef(null),w=i.useRef(null),K=i.useRef(null),R=i.useRef(!1),S=i.useRef(!1),O=i.useRef(!1),H=i.useRef(null),P=i.useRef([]),[C,I]=i.useState(null),[W,E]=i.useState(0),$=i.useRef(typeof window>"u"?{}:Vh(g)),z=i.useMemo(()=>new Map(e.map(F=>[F.tabKey,F])),[e]),J=i.useMemo(()=>{const F=k.current;return F?F.groups.some(V=>{try{const L=V.model.location.type;return L!=="floating"&&L!=="popout"?!1:V.panels.some(G=>z.has(G.id))}catch{return!1}}):!1},[z,W,e]),he=i.useCallback(()=>{var F;(F=k.current)==null||F.focus()},[]),ce=i.useCallback((F,V)=>{h==null||h(F,V)},[h]),te=i.useCallback(F=>{const V=document,L=F.document;for(const ne of V.querySelectorAll('link[rel="stylesheet"]')){const ve=L.createElement("link");ve.rel="stylesheet",ve.href=ne.href,ne.crossOrigin&&(ve.crossOrigin=ne.crossOrigin),L.head.appendChild(ve)}for(const ne of V.querySelectorAll("style")){const ve=L.createElement("style");ve.textContent=ne.textContent,L.head.appendChild(ve)}const G=[];for(const ne of V.styleSheets)try{for(const ve of ne.cssRules)ve instanceof CSSStyleRule&&(ve.selectorText===":root"||ve.selectorText==="html")&&G.push(ve.cssText)}catch{}if(G.length>0){const ne=L.createElement("style");ne.textContent=G.join(`
52
+ `),L.head.appendChild(ne)}const _=V.documentElement.getAttribute("data-theme");_&&L.documentElement.setAttribute("data-theme",_),L.documentElement.style.colorScheme=_==="light"?"light":"dark",L.body.className=V.body.className;const U=V.documentElement.getAttribute("style");U&&L.documentElement.setAttribute("style",U);const Q=L.getElementById("dv-popout-window");Q instanceof HTMLElement&&(Q.classList.add("adhdev-dockview"),zn(Q,M))},[M]),ye=i.useCallback(()=>{var V;const F=k.current;if(F)for(const L of F.groups)try{const G=(V=L.element)==null?void 0:V.ownerDocument;if(!G||G===document)continue;const _=G.getElementById("dv-popout-window");_ instanceof HTMLElement&&(_.classList.add("adhdev-dockview"),zn(_,M));const U=document.documentElement.getAttribute("data-theme");U&&G.documentElement.setAttribute("data-theme",U),G.documentElement.style.colorScheme=U==="light"?"light":"dark",G.body.className=document.body.className;const Q=document.documentElement.getAttribute("style");Q?G.documentElement.setAttribute("style",Q):G.documentElement.removeAttribute("style")}catch{}},[M]),fe=i.useCallback(F=>{const V=k.current;if(!V)return;const L=V.getPanel(F);L&&V.addPopoutGroup(L,{popoutUrl:"/popout.html",onDidOpen:({window:G})=>{te(G),xe();const _=z.get(F);G.document.title=_?`${it(_)} — ADHDev`:"ADHDev — Popout"}})},[z,te]),be=i.useCallback(F=>{const V=k.current,L=V==null?void 0:V.getPanel(F);if(!V||!L)return;const G=V.groups.filter(_=>{var U;try{return((U=_.element)==null?void 0:U.ownerDocument)===document}catch{return!0}});G.length>0?L.api.moveTo({group:G[0],position:"center"}):L.api.moveTo({position:"center"}),L.api.setActive()},[]),X=i.useCallback(F=>{var G;const V=k.current;if(!V)return!1;const L=V.getPanel(F);if(!L)return!1;try{return((G=L.group.element)==null?void 0:G.ownerDocument)!==document}catch{return!1}},[]),ae=i.useCallback(F=>{X(F)&&be(F),u(F)},[X,be,u]),ge=i.useCallback(F=>{const V=k.current,L=V==null?void 0:V.getPanel(F);!V||!L||V.addFloatingGroup(L,{width:600,height:500})},[]),ee=i.useCallback(F=>{var L;const V=(L=k.current)==null?void 0:L.getPanel(F);if(!V)return!1;try{return V.group.model.location.type==="floating"}catch{return!1}},[]),de=i.useCallback(()=>{var V,L;const F=(L=(V=k.current)==null?void 0:V.activePanel)==null?void 0:L.id;return!F||Lt(F)?null:z.has(F)?F:null},[z]),we=i.useCallback(F=>{const V=k.current,L=V==null?void 0:V.getPanel(F);if(!V||!L)return;const G=V.groups.filter(_=>{try{return _.model.location.type==="grid"}catch{return!0}});G.length>0?L.api.moveTo({group:G[0],position:"center"}):L.api.moveTo({position:"center"}),L.api.setActive()},[]),ue=i.useCallback(()=>{var U;const F=k.current;if(!F)return;const L=F.groups.filter(Q=>{var ne;try{return((ne=Q.element)==null?void 0:ne.ownerDocument)===document&&Q.model.location.type==="grid"}catch{return!1}})[0]||null,G=[...F.panels];for(const Q of G){const ne=(U=Q.group.element)==null?void 0:U.ownerDocument,ve=Q.group.model.location.type;ne===document&&ve==="grid"||(L&&L.id!==Q.group.id?Q.api.moveTo({group:L,position:"center"}):Q.api.moveTo({position:"center"}))}const _=F.activePanel;_&&(_.group.model.openPanel(_),_.api.setActive()),Un(document)},[]),xe=i.useCallback(()=>{var V,L;const F=k.current;if(F)for(const G of F.groups){const _=(V=G.element)==null?void 0:V.ownerDocument;if(!_||_===document)continue;const U=_.getElementById("dv-popout-window");if(!(U instanceof HTMLElement))continue;let Q=null,ne=_.title||"ADHDev",ve="Popout workspace";const Me=G.activePanel;if(Me)if(Q=Me.id,Lt(Me.id)){const Re=((L=Me.params)==null?void 0:L.routeId)||Me.id.slice(7),ze=Pt([...z.values()],Re);ne=Uc(ze),ve=ze!=null&&ze.machineName?`Remote view · ${ze.machineName}`:"Remote view"}else{const Re=z.get(Me.id);ne=Re?it(Re):Me.title||Me.id,ve=Re?rs(Re):"Dockview panel"}_.title=`${ne} — ADHDev`;const _e=Array.from(_.querySelectorAll("#adhdev-popout-header"));for(const Re of _e)Re.remove();const Ne=_.createElement("div");Ne.id="adhdev-popout-header",_.body.appendChild(Ne),Ne.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(";")),Ne.innerHTML=`
53
53
  <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
54
54
  <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
55
55
  <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${yi(ne)}</div>
@@ -59,36 +59,36 @@ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Mach
59
59
  <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>
60
60
  <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>
61
61
  </div>
62
- `,z.style.top="52px",z.style.height="calc(100% - 52px)";const Ee=Ce.querySelector("[data-adhdev-popout-focus]");Ee&&(Ee.onclick=()=>{window.focus()});const Be=Ce.querySelector("[data-adhdev-popout-dock]");Be&&(Be.disabled=!Q,Be.style.opacity=Q?"1":"0.5",Be.style.cursor=Q?"pointer":"default",Be.onclick=()=>{var _e;Q&&be(Q),(_e=_.defaultView)==null||_e.focus()})}},[F,be]),se=i.useCallback(H=>{var G;const V=k.current,L=V==null?void 0:V.getPanel(H);if(!(!V||!L)){L.group.model.openPanel(L),L.api.setActive(),le(H,"dockview-shortcut");try{const _=L.group.model.location;_.type==="popout"?_.getWindow().focus():Un((G=L.group.element)==null?void 0:G.ownerDocument)}catch{}}},[le]),ie=i.useCallback(H=>{const V=k.current,L=V==null?void 0:V.activePanel,G=(V==null?void 0:V.activeGroup)||(L==null?void 0:L.group);if(!V||!L||!G)return;const _=G.panels||[];if(_.length<=1)return;const z=_.findIndex(ve=>ve.id===L.id);if(z<0)return;const Q=(z+H+_.length)%_.length,ne=_[Q];ne&&(ne.group.model.openPanel(ne),ne.api.setActive(),Lt(ne.id)||le(ne.id,"dockview-shortcut"))},[le]),re=i.useCallback(H=>{var Ee;const V=k.current,L=(V==null?void 0:V.activeGroup)||((Ee=V==null?void 0:V.activePanel)==null?void 0:Ee.group);if(!V||!L)return;const G=V.groups||[],_=G.find(Be=>Be.id===L.id);if(!_)return;const z=_.element.getBoundingClientRect(),Q=z.left+z.width/2,ne=z.top+z.height/2,ve=(Be,_e,ze,Je)=>Math.max(0,Math.min(_e,Je)-Math.max(Be,ze)),Ae=Be=>{const _e=Be.element.getBoundingClientRect(),ze=_e.left+_e.width/2,Je=_e.top+_e.height/2;let ft=0,pt=0,ht=0,me=!1;if(H==="left"?(me=ze<Q,ft=Math.max(0,z.left-_e.right),pt=Math.abs(Je-ne),ht=ve(z.top,z.bottom,_e.top,_e.bottom)):H==="right"?(me=ze>Q,ft=Math.max(0,_e.left-z.right),pt=Math.abs(Je-ne),ht=ve(z.top,z.bottom,_e.top,_e.bottom)):H==="above"?(me=Je<ne,ft=Math.max(0,z.top-_e.bottom),pt=Math.abs(ze-Q),ht=ve(z.left,z.right,_e.left,_e.right)):(me=Je>ne,ft=Math.max(0,_e.top-z.bottom),pt=Math.abs(ze-Q),ht=ve(z.left,z.right,_e.left,_e.right)),!me)return Number.POSITIVE_INFINITY;const je=ht>0?0:120;return ft*3+pt+je};let Pe=null,Ce=Number.POSITIVE_INFINITY;for(const Be of G){if(Be.id===_.id)continue;const _e=Ae(Be);Number.isFinite(_e)&&(_e>=Ce||(Ce=_e,Pe=Be))}return Pe||void 0},[]),q=i.useCallback(H=>{var G;const V=re(H);if(!V)return;const L=V.activePanel||V.panels[0];L&&(V.model.openPanel(L),L.api.setActive(),Lt(L.id)||le(L.id,"dockview-focus"),Un((G=V.element)==null?void 0:G.ownerDocument))},[re,le]),Y=i.useCallback((H,V)=>{const L=k.current,G=L==null?void 0:L.activePanel,_=(L==null?void 0:L.activeGroup)||(G==null?void 0:G.group);if(!L||!G||!_)return;let z=re(H);!z&&(V!=null&&V.createGroupIfMissing)&&(z=L.addGroup({referenceGroup:_,direction:H})),z&&(G.api.moveTo({group:z,position:"center"}),G.group.model.openPanel(G),G.api.setActive(),Lt(G.id)||le(G.id,V!=null&&V.createGroupIfMissing?"dockview-split":"dockview-move"))},[re,le]),{isMac:ce,tabShortcuts:ke,shortcutListening:Z,setShortcutListening:Se,saveShortcuts:Me}=Tl({sortedTabKeys:e.map(H=>H.tabKey),onFocus:he,onSelectTab:se}),We=i.useCallback(()=>{var L;const H=k.current;if(!H)return;const V=H.activePanel;if(V){if(Lt(V.id)){const G=((L=V.params)==null?void 0:L.routeId)||V.id.slice(7),_=Pt(e,G);_!=null&&_.tabKey&&Se(_.tabKey);return}F.has(V.id)&&Se(V.id)}},[F,se,Se,e]),Fe=i.useCallback(H=>{const V=[];return H.metaKey&&V.push(ce?"⌘":"Meta"),H.ctrlKey&&V.push("Ctrl"),H.altKey&&V.push(ce?"⌥":"Alt"),H.shiftKey&&H.key.length!==1&&V.push(ce?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(H.key)?null:(V.push(Ll(H.key)),V.join("+"))},[ce]),D=i.useCallback(H=>{var V,L;switch(H){case"splitActiveTabRight":Y("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":Y("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const G=de();G&&ge(G);return}case"popoutActiveTab":{const G=de();G&&fe(G);return}case"dockActiveTab":{const G=de();if(!G)return;X(G)?be(G):ee(G)&&we(G);return}case"focusLeftPane":q("left");return;case"focusRightPane":q("right");return;case"focusUpPane":q("above");return;case"focusDownPane":q("below");return;case"moveActiveTabToLeftPane":Y("left");return;case"moveActiveTabToRightPane":Y("right");return;case"moveActiveTabToUpPane":Y("above");return;case"moveActiveTabToDownPane":Y("below");return;case"selectPreviousGroupTab":ie(-1);return;case"selectNextGroupTab":ie(1);return;case"setActiveTabShortcut":We();return;case"hideCurrentTab":{const G=(L=(V=k.current)==null?void 0:V.activePanel)==null?void 0:L.id;G&&!Lt(G)&&ae(G);return}default:return}},[ie,we,q,ge,de,ae,ee,X,be,Y,fe,We]);i.useEffect(()=>{if(!C)return;const H=C.sourceDocument,V=H.defaultView??window,L=G=>{const _=H.querySelector("[data-dockview-tab-context-menu]");_&&_.contains(G.target)||I(null)};return V.addEventListener("mousedown",L,!0),V!==window&&window.addEventListener("mousedown",()=>I(null),!0),()=>{V.removeEventListener("mousedown",L,!0),V!==window&&window.removeEventListener("mousedown",()=>I(null),!0)}},[C]);const Ne=i.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:F,hasDetachedConversationPanels:J,ides:r,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:N,liveSessionInboxState:A,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:ae,userName:f,scrollToBottomRequest:v,tabShortcuts:ke,openTabContextMenu:({x:H,y:V,tabKey:L,sourceDocument:G})=>I({x:H,y:V,tabKey:L,sourceDocument:G??document}),popoutTab:fe,moveTabBackToMain:be,isTabInPopout:X,floatTab:ge,isTabFloating:ee}),[n,t,F,J,r,c,l,N,A,a,o,ae,f,v,ke,fe,be,X,ge,ee]),Ie=C?ib({isTabInPopout:X(C.tabKey),isTabFloating:ee(C.tabKey),tabShortcut:ke[C.tabKey],actionShortcuts:p}):[],Re=i.useCallback(H=>{var G;const V=k.current;if((((G=V==null?void 0:V.activePanel)==null?void 0:G.id)??null)===H.id){H.group.model.openPanel(H);return}H.group.model.openPanel(H),H.api.setActive()},[]),De=i.useCallback((H,V="requested-tab")=>{if(!H)return!1;const L=k.current;if(!L)return!1;const G=L.getPanel(H);return G?(Re(G),le(H,V),b==null||b(),!0):!1},[Re,b,le]),He=i.useCallback(()=>{if(O.current)return!1;const H=De(U.current,"stored-layout-restore");return H&&(O.current=!0),H},[De]),Ue=i.useCallback(()=>{var V;const H=k.current;H&&Uh(g,{activeTabId:((V=H.activePanel)==null?void 0:V.id)??null,layout:H.toJSON()})},[g]),Qe=i.useCallback(()=>{Vh(g,$.current)},[g]),lt=i.useCallback(H=>{var G,_,z,Q;const V=k.current;if(!V)return{kind:"grid"};const L=V.toJSON();for(const ne of L.floatingGroups||[])if((_=(G=ne.data)==null?void 0:G.views)!=null&&_.includes(H)&&ne.position)return{kind:"floating",position:ne.position};for(const ne of L.popoutGroups||[])if((Q=(z=ne.data)==null?void 0:z.views)!=null&&Q.includes(H))return{kind:"popout",position:ne.position,popoutUrl:ne.url};return{kind:"grid"}},[]),dt=i.useCallback(H=>{const V=k.current;if(!V)return;const L=V.getPanel(H),G=$.current[H];if(!L||!G||G.kind==="grid")return;if(L.group.model.location.type===G.kind){delete $.current[H],Qe();return}if(G.kind==="floating"){V.addFloatingGroup(L,{x:G.position.left??24,y:G.position.top??24,width:G.position.width,height:G.position.height}),delete $.current[H],Qe();return}delete $.current[H],Qe()},[Qe]);i.useEffect(()=>(m==null||m({setShortcutForActiveTab:We,restoreHiddenTabToSavedLocation:dt,activateConversationTab:se,resetAllPanelsToMain:ue,activatePreviousTabInGroup:()=>ie(-1),activateNextTabInGroup:()=>ie(1),floatActiveTab:()=>{const H=de();H&&ge(H)},popoutActiveTab:()=>{const H=de();H&&fe(H)},dockActiveTab:()=>{const H=de();H&&(X(H)?be(H):ee(H)&&we(H))},splitActiveTabRight:()=>Y("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>Y("below",{createGroupIfMissing:!0}),focusLeftPane:()=>q("left"),focusRightPane:()=>q("right"),focusUpPane:()=>q("above"),focusDownPane:()=>q("below"),moveActiveTabToLeftPane:()=>Y("left"),moveActiveTabToRightPane:()=>Y("right"),moveActiveTabToUpPane:()=>Y("above"),moveActiveTabToDownPane:()=>Y("below")}),()=>m==null?void 0:m(null)),[ie,we,ge,q,de,ee,X,Y,be,fe,m,ue,dt,se,We]),i.useEffect(()=>()=>{var H;(H=K.current)==null||H.call(K),K.current=null},[]);const ut=i.useCallback(H=>{var L,G;k.current=H.api,(L=K.current)==null||L.call(K),K.current=null;const V=Hh(g);if(U.current=(V==null?void 0:V.activeTabId)??null,V!=null&&V.layout&&H.api.fromJSON(V.layout,{reuseExistingPanels:!1}),S.current=xi({hasStoredLayout:!!(V!=null&&V.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),S.current||(wi(H.api,e),ji(H.api,e,x)),H.api.totalPanels===0&&e.length>0){const _=hb(H.api,e,j);if(_){const z=H.api.getPanel(_);z&&Re(z)}}else!S.current&&!De(j)&&He();if(R.current=!0,H.api.onDidActivePanelChange(_=>{var Q;if(U.current=(_==null?void 0:_.id)??null,O.current=!0,xe(),_&&Lt(_.id)){const ne=((Q=_.params)==null?void 0:Q.routeId)||_.id.slice(7),ve=Pt(e,ne);y((ve==null?void 0:ve.tabKey)??null),Ue();return}if(y((_==null?void 0:_.id)??null),Ue(),!_)return;const z=F.get(_.id);(z==null?void 0:z.streamSource)==="agent-stream"&&z.agentType&&T(z.routeId,jc(),{agentType:z.agentType,...z.sessionId&&{targetSessionId:z.sessionId}}).catch(()=>{})}),H.api.onDidLayoutChange(()=>{Ue(),xe(),E(_=>_+1)}),ub()){const _=Ce=>({clientX:Ce.clientX,clientY:Ce.clientY}),z=Ce=>{const Ee=Ce==null?void 0:Ce.getBoundingClientRect();return Ee?{left:Ee.left,right:Ee.right,top:Ee.top,bottom:Ee.bottom}:null},Q=Ce=>{var Be;const Ee=(Be=w.current)==null?void 0:Be.getBoundingClientRect();return Ee?Ce.clientX<Ee.left||Ce.clientX>Ee.right||Ce.clientY<Ee.top||Ce.clientY>Ee.bottom:!1},ne=db({detachDelayMs:_l,onDetach:({panelId:Ce,clientX:Ee,clientY:Be})=>{var ht,me;const _e=H.api.getPanel(Ce);if(!_e)return;try{if(_e.group.model.location.type!=="grid")return}catch{return}const ze=(ht=w.current)==null?void 0:ht.getBoundingClientRect(),Je=(me=_e.group.element)==null?void 0:me.getBoundingClientRect(),ft=Math.round(Math.min(Math.max((Je==null?void 0:Je.width)??600,360),720)),pt=Math.round(Math.min(Math.max((Je==null?void 0:Je.height)??500,260),640));H.api.addFloatingGroup(_e,{x:ze?Math.max(0,Ee-ze.left-32):void 0,y:ze?Math.max(0,Be-ze.top-18):void 0,width:ft,height:pt}),_e.api.setActive(),Ue(),xe(),E(je=>je+1)}}),ve=[H.api.onWillDragPanel(Ce=>{if(!(Ce.nativeEvent.defaultPrevented||Ce.nativeEvent.shiftKey)){try{if(Ce.panel.group.model.location.type!=="grid")return}catch{return}ne.startDrag({panelId:Ce.panel.id,selfPanelBounds:z(Ce.panel.group.element),..._(Ce.nativeEvent)})}}),H.api.onWillShowOverlay(Ce=>{if(ne.hasDetached()){Ce.preventDefault();return}ne.markDockTarget(_(Ce.nativeEvent))}),H.api.onWillDrop(Ce=>{if(ne.hasDetached()){Ce.preventDefault(),ne.endDrag();return}ne.markDockTarget(_(Ce.nativeEvent))}),H.api.onDidDrop(()=>ne.endDrag()),H.api.onUnhandledDragOverEvent(Ce=>{ne.isDragging()&&ne.markSelfPanel(_(Ce.nativeEvent))})],Ae=Ce=>{if(!ne.isDragging())return;const Ee=_(Ce);Q(Ee)&&ne.markNonSelfPanel(Ee)},Pe=()=>ne.endDrag();window.addEventListener("dragover",Ae,!0),window.addEventListener("drop",Pe,!0),window.addEventListener("dragend",Pe,!0),K.current=()=>{ne.dispose();for(const Ce of ve)Ce.dispose();window.removeEventListener("dragover",Ae,!0),window.removeEventListener("drop",Pe,!0),window.removeEventListener("dragend",Pe,!0)}}H.api.onDidAddGroup(_=>{requestAnimationFrame(()=>{var z,Q;try{const ne=(z=_.element)==null?void 0:z.ownerDocument;if(!ne||ne===document)return;(Q=ne.getElementById("dv-popout-window"))==null||Q.classList.add("adhdev-dockview");const ve=document.documentElement.getAttribute("data-theme");ve&&ne.documentElement.setAttribute("data-theme",ve),ne.body.className=document.body.className;const Ae=document.documentElement.getAttribute("style");Ae&&ne.documentElement.setAttribute("style",Ae)}catch{}xe(),E(ne=>ne+1)})}),y(((G=H.api.activePanel)==null?void 0:G.id)??null)},[Re,De,F,r,d,g,y,Ue,j,x,T,xe,e]);i.useLayoutEffect(()=>{const H=k.current;if(!H||!R.current||S.current&&xi({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;S.current&&(S.current=!1);const V=P.current,L=new Set(V),G=e.map(Pe=>Pe.tabKey),_=new Set(G),z=cb({previousVisibleConversationCount:V.length,visibleConversationCount:e.length,ides:r});let Q=!1;for(const Pe of V)_.has(Pe)||z||($.current[Pe]=lt(Pe),Q=!0);Q&&Qe(),z||(wi(H,e),ji(H,e,x));const ne=G.filter(Pe=>!L.has(Pe));let ve=!1;for(const Pe of ne){const Ce=H.getPanel(Pe),Ee=$.current[Pe];if(!Ce||!Ee||Ee.kind==="grid")continue;if(Ce.group.model.location.type===Ee.kind){delete $.current[Pe],ve=!0;continue}if(Ee.kind==="floating"){H.addFloatingGroup(Ce,{x:Ee.position.left??24,y:Ee.position.top??24,width:Ee.position.width,height:Ee.position.height}),delete $.current[Pe],ve=!0;continue}}if(ve&&Qe(),P.current=G,j&&De(j))return;!H.activePanel&&H.panels[0]&&Re(H.panels[0]),!!(H.activePanel&&H.getPanel(H.activePanel.id))||He()},[Re,De,He,r,d,Qe,lt,j,x,e]),i.useEffect(()=>{R.current&&De(j)},[De,j]),i.useEffect(()=>{const H=L=>{const G=L.target;if(!G)return;const _=G.querySelector("[data-tab-key]")||G.closest("[data-tab-key]");if(_){const z=_.getAttribute("data-tab-key");if(z&&L.dataTransfer){const Q=G.closest(".dv-tab")||_.closest(".dv-tab")||_;L.dataTransfer.effectAllowed="move",L.dataTransfer.setData("text/tab-key",z),Q instanceof HTMLElement&&L.dataTransfer.setDragImage(Q,Math.max(12,Math.round(Q.clientWidth/2)),Math.max(10,Math.round(Q.clientHeight/2)))}}};window.addEventListener("dragstart",H);const V=vi(k.current);for(const L of V)L.addEventListener("dragstart",H);return()=>{window.removeEventListener("dragstart",H);for(const L of V)L.removeEventListener("dragstart",H)}},[W]),i.useEffect(()=>{var V;const H=(V=w.current)==null?void 0:V.querySelector(".adhdev-dockview");H instanceof HTMLElement&&zn(H,M),ye(),xe()},[xe,ye,M]),i.useEffect(()=>{xe()},[xe]),i.useEffect(()=>{const H=V=>{if(V.defaultPrevented||Z)return;const L=Fe(V);if(!L)return;const G=V.metaKey||V.ctrlKey||V.altKey;Ca(V.target)&&!G||nn(ce).setActiveTabShortcut!==L||(V.preventDefault(),V.stopPropagation(),We())};return window.addEventListener("keydown",H,!0),()=>window.removeEventListener("keydown",H,!0)},[Fe,ce,Z,We]),i.useEffect(()=>{const H=w.current;if(!H)return;const V=L=>{var ne,ve;if(!L.isTrusted)return;const G=(ve=(ne=L.target)==null?void 0:ne.closest)==null?void 0:ve.call(ne,".dv-scrollable");if(!G)return;L.preventDefault(),L.stopPropagation();const _=Math.abs(L.deltaX),z=Math.abs(L.deltaY),Q=_>z?L.deltaX:L.deltaY;G.dispatchEvent(new WheelEvent("wheel",{deltaY:Q,deltaMode:L.deltaMode,bubbles:!1,cancelable:!0}))};return H.addEventListener("wheel",V,{passive:!1,capture:!0}),()=>H.removeEventListener("wheel",V,{capture:!0})},[]),i.useEffect(()=>{const H=vi(k.current);if(H.length===0)return;const V=H.map(L=>{let G=[],_=null;const z=()=>{_!=null&&L.clearTimeout(_),_=null,G=[]},Q=()=>{_!=null&&L.clearTimeout(_),_=L.setTimeout(()=>{_=null,G=[]},1200)},ne=Ae=>{if(!Ae.ctrlKey&&!Ae.metaKey&&!Ae.altKey)return;const Pe=Fe(Ae);if(!Pe)return;const Ce=Cl();for(const[Ee,Be]of Object.entries(Ce))if(e.some(_e=>_e.tabKey===Ee)&&Be===Pe){Ae.preventDefault(),se(Ee);return}},ve=Ae=>{if(Ae.defaultPrevented||Z)return;const Pe=Fe(Ae);if(!Pe)return;const Ce=Ae.metaKey||Ae.ctrlKey||Ae.altKey;if(Ca(Ae.target))return;const Ee=nn(ce),Be=Object.entries(Ee).filter(([je,wt])=>!!wt&&(je==="splitActiveTabRight"||je==="splitActiveTabDown"||je==="floatActiveTab"||je==="popoutActiveTab"||je==="dockActiveTab"||je==="focusLeftPane"||je==="focusRightPane"||je==="focusUpPane"||je==="focusDownPane"||je==="moveActiveTabToLeftPane"||je==="moveActiveTabToRightPane"||je==="moveActiveTabToUpPane"||je==="moveActiveTabToDownPane"||je==="selectPreviousGroupTab"||je==="selectNextGroupTab"||je==="setActiveTabShortcut"||je==="hideCurrentTab")),_e=Ce?[Pe]:[...G.slice(-1),Pe].slice(-2),ze=_e.join(" "),Je=_e[_e.length-1],ft=Be.find(([,je])=>je===ze);if(ft){Ae.preventDefault(),z(),D(ft[0]);return}if(Be.some(([,je])=>je.startsWith(`${ze} `))){Ae.preventDefault(),G=_e,Q();return}const ht=Be.find(([,je])=>je===Je);if(ht){Ae.preventDefault(),z(),D(ht[0]);return}if(Be.some(([,je])=>je.startsWith(`${Je} `))){Ae.preventDefault(),G=[Je],Q();return}z()};return L.addEventListener("keydown",ne),L.addEventListener("keydown",ve),()=>{z(),L.removeEventListener("keydown",ne),L.removeEventListener("keydown",ve)}});return()=>{for(const L of V)L()}},[Fe,ce,W,se,Z,D,e]);const Te=M==="light"?aa:oa,Ge=((tt=(qe=(Ze=k.current)==null?void 0:Ze.activePanel)==null?void 0:qe.group.element)==null?void 0:tt.ownerDocument)??document;return s.jsxs(Pl.Provider,{value:Ne,children:[s.jsx("div",{ref:w,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(Nd,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:xb,remote:bb},defaultTabComponent:yb,watermarkComponent:gb,onReady:ut,singleTabMode:"default",tabAnimation:"smooth",theme:Te,popoutUrl:"/popout.html"})}),C&&sr.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:Ie.map(H=>{if(H.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},H.id);let V=s.jsx(yu,{size:13,className:"shrink-0 opacity-70"}),L=()=>{};switch(H.id){case"dockInWindow":case"dockBackToGrid":V=s.jsx(wu,{size:13,className:"shrink-0 opacity-70"}),L=()=>{we(C.tabKey),I(null)};break;case"moveBackToMain":V=s.jsx(gu,{size:13,className:"shrink-0 opacity-70"}),L=()=>{be(C.tabKey),I(null)};break;case"floatAsPanel":V=s.jsx(vu,{size:13,className:"shrink-0 opacity-70"}),L=()=>{ge(C.tabKey),I(null)};break;case"openInNewWindow":V=s.jsx(bu,{size:13,className:"shrink-0 opacity-70"}),L=()=>{fe(C.tabKey),I(null)};break;case"setShortcut":L=G=>{G.stopPropagation(),Se(C.tabKey),I(null)};break;case"removeShortcut":V=s.jsx(St,{size:13,className:"shrink-0 opacity-70"}),L=()=>{const G={...ke};delete G[C.tabKey],Me(G),I(null)};break;case"hideTab":V=s.jsx(Da,{size:13,className:"shrink-0 opacity-70"}),L=()=>{ae(C.tabKey),I(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 ${H.tone==="muted"?"text-text-muted":""}`,onMouseDown:mb,onClick:L,children:[V,s.jsx("span",{className:"flex-1 min-w-0",children:H.label}),H.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:H.shortcut}):null]},H.id)})}),C.sourceDocument.body),Z&&sr.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:()=>Se(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:H=>H.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. ",ce?"⌘+1":"Ctrl+1",", ",ce?"⌥+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"})]})}),Ge.body)]})}const Dl="adhdev-recent-launch-args-v1",wb=8;function jb(e){return String(e||"").trim().replace(/\s+/g," ")}function El(e,t){return`${e.trim()}::${t.trim()}`}function $l(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Dl)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function kb(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Dl,JSON.stringify(e))}catch{}}function Bl(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=$l().byKey[El(r,n)])==null?void 0:o.items)||[]}function Kl(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=jb(r);if(!n||!a||!o)return;const c=$l(),l=El(n,a),d=((u=c.byKey[l])==null?void 0:u.items)||[],f=[o,...d.filter(p=>p!==o)].slice(0,wb);c.byKey[l]={items:f},kb(c)}function Ol(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Hr({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 Sb({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 Wl({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:c,onOpenHistory:l,onClearSelection:d}){const f=o?kl(o):null,u=Sb({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Hr,{title:"Saved history",description:eo(),action:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:c,children:t?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:l,children:Tp()})]}),children:[f?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:f.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:f.providerSessionId}),s.jsx("div",{className:"mt-1",children:f.metaLine}),f.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:f.updatedLabel}),f.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:f.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 Vn(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>ps(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>ps(a,"acp"))?"acp":null}function Rr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Nb({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:c,onListSavedSessions:l}){var H,V;const d=fr(),f=i.useMemo(()=>[...e].sort(Wa),[e]),[u,p]=i.useState(((H=f[0])==null?void 0:H.id)||""),m=i.useMemo(()=>f.find(L=>L.id===u)||f[0],[u,f]),y=i.useMemo(()=>((m==null?void 0:m.workspaces)||[]).map(L=>({id:L.id,path:L.path,label:L.label})),[m]),N=(m==null?void 0:m.defaultWorkspaceId)||null,[h,j]=i.useState(""),[x,b]=i.useState(""),[v,A]=i.useState(Vn(f[0])),[g,M]=i.useState(""),[T,k]=i.useState(""),[w,K]=i.useState([]),[R,S]=i.useState(""),[O,U]=i.useState([]),[P,C]=i.useState(!1),[I,W]=i.useState(!1),[E,$]=i.useState(""),[F,J]=i.useState(!1),[he,le]=i.useState(()=>xt()),[te,ye]=i.useState(null),[fe,be]=i.useState(!1),[X,ae]=i.useState(""),[ge,ee]=i.useState(!1),[de,we]=i.useState(""),[ue,xe]=i.useState([]),[se,ie]=i.useState(!1),[re,q]=i.useState(""),[Y,ce]=i.useState(!1),ke=i.useRef(null),Z=i.useRef(0);i.useEffect(()=>{var L;!u&&((L=f[0])!=null&&L.id)&&p(f[0].id)},[u,f]),i.useEffect(()=>{!m||!(!m.workspaces||!m.availableProviders||!m.detectedIdes||!m.recentLaunches)||d(m.id,{minFreshMs:3e4}).catch(()=>{})},[d,m]);const Se=i.useMemo(()=>((m==null?void 0:m.availableProviders)||[]).filter(L=>ps(L,"cli")),[m]),Me=i.useMemo(()=>((m==null?void 0:m.availableProviders)||[]).filter(L=>ps(L,"acp")),[m]),We=i.useMemo(()=>((m==null?void 0:m.detectedIdes)||[]).map(L=>({id:L.type,label:L.name||L.type,meta:L.running?"Detected locally":"Available to open"})),[m]),Fe=i.useMemo(()=>v==="cli"?Se.map(L=>({id:L.type,label:L.displayName||L.type,meta:"CLI provider"})):v==="acp"?Me.map(L=>({id:L.type,label:L.displayName||L.type,meta:"ACP provider"})):We,[Me,v,Se,We]);i.useEffect(()=>{var G;if(!m)return;if(ke.current!==m.id){ke.current=m.id,j(N||((G=y[0])==null?void 0:G.id)||"__home__"),b(""),A(Vn(m)),M(""),k(""),S(""),U([]),W(!1),$(""),le(xt()),ae("");return}j(_=>{var z;return _==="__custom__"||_==="__home__"||y.some(Q=>Q.id===_)?_:N||((z=y[0])==null?void 0:z.id)||"__home__"}),A(_=>_==="ide"&&We.length>0||_==="cli"&&Se.length>0||_==="acp"&&Me.length>0?_:Vn(m))},[Me.length,Se.length,N,We.length,m,y]),i.useEffect(()=>{var L;v&&(Fe.some(G=>G.id===g)||M(((L=Fe[0])==null?void 0:L.id)||""))},[v,Fe,g]);const D=i.useCallback(async(L,G)=>{const _=Z.current+1;return Z.current=_,C(!0),$(""),l(L,G).then(z=>{Z.current===_&&U(z)}).catch(z=>{Z.current===_&&(U([]),$(z instanceof Error?z.message:"Could not load saved sessions"))}).finally(()=>{Z.current===_&&(C(!1),W(!0))})},[l]),Ne=i.useCallback((L,G)=>{K(Bl(L,G))},[]);i.useEffect(()=>{Z.current+=1,S(""),le(xt()),!m||!g||v==="ide"?K([]):Ne(m.id,g),W(!1),U([]),$(""),C(!1)},[v,Ne,D,m,g]),i.useEffect(()=>{if(!R)return;const L=O.find(G=>G.providerSessionId===R);L!=null&&L.canResume||S("")},[O,R]);const Ie=h==="__custom__"?x.trim():h==="__home__"?"":((V=y.find(L=>L.id===h))==null?void 0:V.path)||"",Re=i.useMemo(()=>m?t.filter(L=>L.id!==m.id&&L.daemonId===m.id).map(L=>L.workspace):[],[t,m]),De=i.useMemo(()=>((m==null?void 0:m.recentLaunches)||[]).map(L=>L.workspace),[m]),He=i.useCallback(L=>{const G=String(L.workspace||"").trim();if(!G)return;const _=y.find(z=>Rr(z.path)===Rr(G));if(_){j(_.id),b("");return}j("__custom__"),b(G)},[y]),Ue=i.useCallback(L=>{const G=String(L.workspace||"").trim();if(!G)return{workspaceId:null,workspacePath:null};const _=y.find(z=>Rr(z.path)===Rr(G));return _?{workspaceId:_.id,workspacePath:null}:{workspaceId:null,workspacePath:G}},[y]),Qe=i.useMemo(()=>O.find(L=>L.providerSessionId===R)||null,[O,R]),lt=i.useMemo(()=>{var G;if(v!=="cli"||!m||!g)return null;const L=((G=Se.find(_=>_.type===g))==null?void 0:G.displayName)||g;return{routeId:m.id,daemonId:m.id,providerSessionId:R||void 0,transport:"pty",mode:"chat",agentName:L,agentType:g,status:"idle",title:L,messages:[],ideType:g,workspaceName:Ie,workspacePath:Ie,displayPrimary:L,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${m.id}:${g}`,machineName:Ct(m,{fallbackId:m.id})}},[v,Se,Ie,m,R,g]),dt=i.useCallback(()=>{var G;if(!m)return;j("__custom__"),ee(!0),q("");const L=hn(m.platform,pn(x.trim(),Ie,Re,De,m.defaultWorkspacePath,(G=y.find(_=>_.id===N))==null?void 0:G.path,y.map(_=>_.path)));ie(!0),n(m.id,L).then(_=>{we(_.path),b(_.path),xe(_.directories)}).catch(_=>{q(_ instanceof Error?_.message:"Could not load folder")}).finally(()=>ie(!1))},[x,N,De,Re,n,Ie,m,y]),ut=i.useCallback(L=>{m&&(ie(!0),q(""),n(m.id,L).then(G=>{we(G.path),b(G.path),xe(G.directories)}).catch(G=>{q(G instanceof Error?G.message:"Could not load folder")}).finally(()=>ie(!1)))},[n,m]),Te=i.useCallback(async()=>{if(!m||!Ie)return;ce(!0),ae("");const L=await a(m.id,Ie);if(ce(!1),!L.ok){ae(L.error||"Could not save workspace");return}ae("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,Ie,m]),Ge=i.useCallback(async()=>{if(!m||!v||!g)return;be(!0),ae("");const L=T.trim()?T.trim().split(/\s+/).filter(Boolean):[],G=v==="ide"?await o(m.id,g,{workspacePath:Ie||null}):await c(m.id,v,g,{workspaceId:h!=="__home__"&&h!=="__custom__"?h:null,workspacePath:h==="__custom__"&&Ie||null,resumeSessionId:v==="cli"&&R?R:null,cliArgs:L});if(be(!1),!G.ok){ae(G.error||"Could not start session");return}v!=="ide"&&T.trim()&&(Kl(m.id,g,T),Ne(m.id,g)),r()},[v,T,Ne,r,o,c,Ie,m,R,g,h]),Ze=v?Vc(v,v==="cli"&&!!R):"Start",qe=v?Gc(v,v==="cli"&&!!R):"Starting…",tt=f.length>5;return m?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(St,{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(Hr,{title:"Machine",children:tt?s.jsx("select",{"aria-label":"Machine",value:m.id,onChange:L=>p(L.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:fe,children:f.map(L=>s.jsx("option",{value:L.id,children:Ct(L,{fallbackId:L.id})},L.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:f.map(L=>{const G=Ct(L,{fallbackId:L.id}),_=m.id===L.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${G}`,"aria-pressed":_,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${_?"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:()=>p(L.id),disabled:fe,title:G,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${L.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:G})]},L.id)})})}),s.jsxs(Hr,{title:"Workspace",description:"Saved workspace is preferred. Home and custom folders are still available.",action:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:dt,disabled:fe,children:"Browse…"}),children:[s.jsxs("select",{value:h,onChange:L=>{const G=L.target.value;j(G),G==="__custom__"?dt():ae("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:fe,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),y.map(L=>s.jsxs("option",{value:L.id,children:[L.id===N?"⭐ ":"",un(L.path,L.label)||L.path]},L.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:h==="__home__"?"Launch without a workspace.":Ie||"Select a workspace folder."}),h==="__custom__"&&Ie&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:dt,disabled:fe,children:[s.jsx(Cs,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Te,disabled:fe||Y,children:Y?"Saving…":"Save workspace"})]})]}),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:Se.length>0},{id:"ide",label:"IDE",enabled:We.length>0},{id:"acp",label:"ACP",enabled:Me.length>0}].map(L=>s.jsx("button",{type:"button",className:`btn btn-sm ${v===L.id?"btn-primary":"btn-secondary"}`,onClick:()=>A(L.id),disabled:!L.enabled||fe,children:L.label},L.id))})]}),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:v==="ide"?"Choose IDE":v==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Fe.map(L=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${g===L.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>M(L.id),disabled:fe,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.meta})]},L.id)),Fe.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!=="ide"&&s.jsxs(Hr,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:T,onChange:L=>k(L.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:fe}),w.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:w.map(L=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>k(L),disabled:fe,title:L,children:L},L))})]}),v==="cli"&&s.jsx(Wl,{busy:fe,savedSessionsLoading:P,savedSessionsError:E,selectedSession:Qe,onRefresh:()=>{!m||!g||D(m.id,g)},onOpenHistory:()=>{!m||!g||(J(!0),Ol({hasLoadedInitialResults:I,isLoading:P})&&D(m.id,g))},onClearSelection:()=>S("")}),X&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${X.includes("saved")||X.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:X})]}),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:fe,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:Ge,disabled:fe||!v||!g||h==="__custom__"&&!Ie,children:[s.jsx($a,{size:14}),fe?qe:Ze]})]})]})}),ge&&s.jsx(bn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:de,directories:ue,busy:se,error:re,onClose:()=>ee(!1),onNavigate:ut,onConfirm:L=>{b(L),we(L),j("__custom__"),ee(!1)}}),F&&lt&&s.jsx(ro,{activeConv:lt,ides:[],isCreatingChat:!1,isRefreshingHistory:P,savedSessions:O,isSavedSessionsLoading:P,isResumingSavedSessionId:te,savedHistoryFilters:he,missingWorkspaceResumePath:Ie||null,onSavedHistoryFiltersChange:le,onClose:()=>J(!1),onNewChat:()=>{S(""),J(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!m||!g||D(m.id,g)},onResumeSavedSession:L=>{if(!m||!g||te||!L.canResume)return;const G=Ue(L);S(L.providerSessionId),He(L),ye(L.providerSessionId),J(!1),be(!0),ae(""),c(m.id,"cli",g,{workspaceId:G.workspaceId,workspacePath:G.workspacePath,resumeSessionId:L.providerSessionId}).then(_=>{if(!_.ok){ae(_.error||"Could not resume session");return}r()}).finally(()=>{be(!1),ye(_=>_===L.providerSessionId?null:_)})}})]}):null}function Cb(e,t){const{sendCommand:r}=mt(),[n,a]=i.useState(null),[o,c]=i.useState(!1);i.useEffect(()=>{if(!e||!t){a(null);return}c(!0),r(e,"git_remote_url",{workspace:t}).then(d=>{const f=(d==null?void 0:d.result)??d;a(typeof(f==null?void 0:f.remoteUrl)=="string"?f.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>c(!1))},[e,t,r]);const l=Tb(n);return{remoteUrl:n,githubUrl:l,loading:o}}function Tb(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 Fl=5e3;function Mb(e){return`git:${e}`}function Ab({workspace:e,includeDiffSummary:t=!1,intervalMs:r=Fl}){return{type:"subscribe",topic:"workspace.git",key:Mb(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function ho(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function hs(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 Ib(e){const t=ho(e);return(t==null?void 0:t.success)===!1?{status:null,error:hs(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:hs(t,"Git status response did not include status")}}function Lb(e){const t=ho(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:hs(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:hs(t,"Git diff summary response did not include diffSummary")}}function Gn(e){return e===void 0||typeof e=="boolean"}function Rb(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Gn(t.binary)&&Gn(t.truncated)&&Gn(t.staged)}function _b(e){const t=ho(e);return(t==null?void 0:t.success)===!1?{diff:null,error:hs(t,"Git file diff request failed")}:Rb(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:hs(t,"Git file diff response did not include a valid diff object")}}function Pb({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=Fl}){const{sendCommand:o,sendData:c}=mt(),l=typeof t=="string"?t.trim():"",d=!!(r&&e&&l),[f,u]=i.useState(null),[p,m]=i.useState(null),[y,N]=i.useState(!1),[h,j]=i.useState(null),x=i.useCallback(async()=>{if(!(!d||!e||!l)){N(!0),j(null);try{const v=Ib(await o(e,"git_status",{workspace:l}));if(v.error){u(null),m(null),j(v.error);return}if(u(v.status),!n){m(null);return}const A=Lb(await o(e,"git_diff_summary",{workspace:l}));if(A.error){m(null),j(A.error);return}m(A.diffSummary)}catch(v){j(hs(v,"Git status request failed"))}finally{N(!1)}}},[d,e,n,o,l]),b=i.useMemo(()=>l?Ab({workspace:l,includeDiffSummary:n,intervalMs:a}):null,[n,a,l]);return i.useEffect(()=>{if(!d||!e||!l||!b){u(null),m(null),N(!1),j(null);return}const v=c?Ht.subscribe({sendData:c},e,b,A=>{var g,M;A.workspace===l&&(u(A.status),m(A.diffSummary??null),j(((g=A.status)==null?void 0:g.error)||((M=A.diffSummary)==null?void 0:M.error)||null),N(!1))},{retryIntervalMs:1e3}):null;return x(),()=>{v==null||v()}},[d,e,x,b,c,l]),{status:f,diffSummary:p,loading:y,error:h,refresh:x}}const Db={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},Eb={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 ki(e){return e.split("/").pop()??e}function $b(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function Bb({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 c=n===o.path,l=Db[o.status]??"?",d=Eb[o.status]??"text-zinc-400",f=$b(o.path),u=ki(o.path),p=o.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 align-middle",title:"Staged"}):null;return s.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${c?"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:l}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[f&&s.jsxs("span",{className:"text-text-secondary",children:[f,"/"]}),s.jsx("span",{className:"text-text-primary",children:u}),o.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",ki(o.oldPath)]}),p]}),!o.binary&&(o.insertions>0||o.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[o.insertions>0&&s.jsxs("span",{className:"text-emerald-500",children:["+",o.insertions]}),o.insertions>0&&o.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),o.deletions>0&&s.jsxs("span",{className:"text-red-400",children:["-",o.deletions]})]}),o.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${o.path}-${o.staged?"S":"U"}`)})}),t&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",s.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function Kb(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 Ob({diff:e,binary:t,truncated:r,loading:n,error:a,className:o=""}){const c=i.useRef(null);if(i.useEffect(()=>{c.current&&(c.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 l=e.split(`
63
- `);return s.jsxs("div",{ref:c,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:l.map((d,f)=>Kb(d,f))}),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 Wb(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(`
64
- `)}function Hl({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=mt(),{status:a,diffSummary:o,loading:c,error:l,refresh:d}=Pb({daemonId:e,workspace:t,includeDiffSummary:!0}),[f,u]=i.useState(null),[p,m]=i.useState(null),[y,N]=i.useState(""),[h,j]=i.useState(!1),[x,b]=i.useState(!1),[v,A]=i.useState(null),[g,M]=i.useState(null),{githubUrl:T}=Cb(e,t),k=i.useCallback(async U=>{if(!((f==null?void 0:f.path)===U.path&&!f.loading)){u({path:U.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const P=await n(e,"git_diff_file",{workspace:t,path:U.path,staged:U.staged}),C=_b(P);if(C.error||!C.diff){u({path:U.path,diff:"",binary:!1,truncated:!1,loading:!1,error:C.error??"Failed to load diff"});return}u({path:U.path,diff:C.diff.diff,binary:C.diff.binary??!1,truncated:C.diff.truncated??!1,loading:!1,error:null})}catch(P){const C=P instanceof Error?P.message:"Failed to load diff";u({path:U.path,diff:"",binary:!1,truncated:!1,loading:!1,error:C})}}},[e,n,f,t]),w=i.useCallback(U=>{N(""),j(!1),A(null),M(null),m(U)},[]),K=i.useCallback(()=>{m(null),A(null),b(!1)},[]),R=i.useCallback(async()=>{var U,P,C;if(p){b(!0),A(null);try{let I;p==="checkpoint"?I=await n(e,"git_checkpoint",{workspace:t,message:y,includeUntracked:h}):p==="stash"?I=await n(e,"git_stash_push",{workspace:t,message:y,includeUntracked:h}):p==="stash_pop"?I=await n(e,"git_stash_pop",{workspace:t}):p==="checkout_files"&&f&&(I=await n(e,"git_checkout_files",{workspace:t,paths:[f.path]}));const W=(I==null?void 0:I.result)??I;if((W==null?void 0:W.success)===!1||W!=null&&W.error){A((W==null?void 0:W.error)??"Action failed"),b(!1);return}p==="checkpoint"?M(`Checkpoint created: ${((P=(U=W==null?void 0:W.checkpoint)==null?void 0:U.commit)==null?void 0:P.slice(0,7))??"done"}`):p==="stash"?M(`Stashed as ${((C=W==null?void 0:W.stash)==null?void 0:C.stashRef)??"stash@{0}"}`):p==="stash_pop"?M("Stash restored"):(M("File reverted"),u(null)),m(null),await d()}catch(I){A(I instanceof Error?I.message:"Action failed")}finally{b(!1)}}},[p,n,e,t,y,h,f,d]),S=!!(a!=null&&a.hasConflicts),O=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:U=>{U.target===U.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}),T&&s.jsx("a",{href:`${T}/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:c,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(St,{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"}),O===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]})]})]}),l&&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:l}),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:[c&&!o&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),o&&s.jsx(Bb,{files:o.files,truncated:o.truncated,selectedPath:(f==null?void 0:f.path)??null,onFileClick:k}),!c&&!o&&!l&&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:f?s.jsx(Ob,{diff:f.diff,binary:f.binary,truncated:f.truncated,loading:f.loading,error:f.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"})})]}),g&&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:g}),s.jsx("button",{onClick:()=>M(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:S,title:S?"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:S,title:S?"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:S||!(a!=null&&a.stashCount),title:S?"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:!f,title:f?`Revert changes to ${f.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 U=Wb((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(U),M("Copied to clipboard"),setTimeout(()=>M(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),p&&s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:s.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[s.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[p==="checkpoint"&&"Create checkpoint commit",p==="stash"&&"Stash changes",p==="stash_pop"&&"Restore latest stash?",p==="checkout_files"&&`Revert changes to ${(f==null?void 0:f.path)??"file"}?`]}),(p==="checkpoint"||p==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:y,onChange:U=>N(U.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:h,onChange:U=>j(U.target.checked)}),"Include untracked files"]})]}),v&&s.jsx("p",{className:"text-xs text-red-400",children:v}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:K,disabled:x,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:R,disabled:x||(p==="checkpoint"||p==="stash")&&!y.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:x?"Working…":"Confirm"})]})]})})]})})}function Fb({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=i.useState(!1),[o,c]=i.useState(!1),[l,d]=i.useState(!1),[f,u]=i.useState(!1),[p,m]=i.useState(!1),[y,N]=i.useState("quickstart"),[h,j]=i.useState("workspace"),x=i.useMemo(()=>!t&&!e,[t,e]),b=i.useCallback(k=>{a(k),k&&c(!1)},[]),v=i.useCallback(k=>{c(k),k&&a(!1)},[]),A=i.useCallback(()=>{N(r===0?"quickstart":"shortcuts"),j("workspace"),d(!0),a(!1),c(!1)},[r]),g=i.useCallback(()=>{d(!1)},[]),M=i.useCallback(()=>{u(!0)},[]),T=i.useCallback(()=>{u(!1)},[]);return i.useEffect(()=>{if(!x){m(!1);return}m(!0);const k=window.setTimeout(()=>{m(!1)},1e4);return()=>window.clearTimeout(k)},[x]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:l,newSessionOpen:f,guideNudgeVisible:p,guideTab:y,shortcutSection:h,isDesktopDashboard:x,setGuideTab:N,setShortcutSection:j,handleInboxOpenChange:b,handleHiddenOpenChange:v,handleOpenShortcutHelp:A,closeShortcutHelp:g,openNewSession:M,closeNewSession:T}}function Hb(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 Ub(e){return e instanceof Error?e.message:String(e||"")}function zb(e){const t=Ub(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Vb({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:c,onStopCli:l,activeCliViewMode:d,onSetActiveCliViewMode:f,mobileChatConversations:u,hiddenConversations:p,ides:m,actionLogs:y,sendDaemonCommand:N,setActionLogs:h,setCliViewModeOverrides:j,isStandalone:x,initialDataLoaded:b,userName:v,requestedMobileTabKey:A,onRequestedMobileTabConsumed:g,requestedMachineId:M,onRequestedMachineConsumed:T,requestedMobileSection:k,onRequestedMobileSectionConsumed:w,containerRef:K,isSplitMode:R,numGroups:S,groupSizes:O,groupedConvs:U,clearedTabs:P,focusedGroup:C,focusGroup:I,moveTabToGroup:W,splitTabRelative:E,closeGroup:$,handleResizeStart:F,groupActiveTabIds:J,setGroupActiveTab:he,groupTabOrders:le,setGroupTabOrder:te,toggleHiddenTab:ye,visibleConversations:fe,requestedDesktopTabKey:be,onRequestedDesktopTabConsumed:X,onDesktopActiveTabChange:ae,onRequestScrollToBottom:ge,onHideConversation:ee,onShowHiddenConversation:de,onShowAllHiddenConversations:we,scrollToBottomRequest:ue,machineEntries:xe,layoutProfile:se,onBrowseMachineDirectory:ie,onSaveMachineWorkspace:re,onLaunchMachineIde:q,onLaunchMachineProvider:Y,onListMachineSavedSessions:ce,notifications:ke,notificationUnreadCount:Z,liveSessionInboxState:Se,onMarkNotificationRead:Me,onMarkNotificationUnread:We,onDeleteNotification:Fe}){const D=kt.useRef(null),{inboxOpen:Ne,hiddenOpen:Ie,shortcutHelpOpen:Re,newSessionOpen:De,guideNudgeVisible:He,guideTab:Ue,shortcutSection:Qe,isDesktopDashboard:lt,setGuideTab:dt,setShortcutSection:ut,handleInboxOpenChange:Te,handleHiddenOpenChange:Ge,handleOpenShortcutHelp:Ze,closeShortcutHelp:qe,openNewSession:tt,closeNewSession:H}=Fb({isMobile:t,showMobileChatMode:e,visibleConversationCount:fe.length}),[V,L]=kt.useState(null),G=kt.useCallback((me,je)=>{L({daemonId:me,workspace:je})},[]),_=kt.useCallback(me=>{var je;sr.flushSync(()=>{de(me)}),(je=D.current)==null||je.restoreHiddenTabToSavedLocation(me.tabKey)},[de]),z=kt.useCallback(me=>{var wt;const je=u.find(bt=>ha(bt,me))||p.find(bt=>ha(bt,me));je&&(p.some(bt=>bt.tabKey===je.tabKey)&&_(je),ae(je.tabKey),(wt=D.current)==null||wt.activateConversationTab(je.tabKey),ge(je.tabKey,"notification-open")),Me(me.id),Te(!1)},[_,p,u,ae,Me,ge]),Q=kt.useCallback(()=>{var je;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((je=D.current)==null||je.resetAllPanelsToMain(),Ge(!1))},[Ge]),ne=kt.useCallback(async me=>{var oe;if(!r)return;const je=(oe=r.modalButtons)==null?void 0:oe[me];if(!je)return;const wt=Ms(r);if(!wt)return;const bt=je.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),B=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(bt);try{await N(wt,"resolve_action",{button:je,action:B?"approve":"reject",buttonIndex:me,...ts(r)})}catch(pe){zb(pe)||console.error("[Shortcut approval] Failed:",pe)}},[r,N]),{isMac:ve,actionDefinitions:Ae,actionShortcuts:Pe,shortcutListening:Ce,shortcutListeningDraft:Ee,setShortcutListening:Be,setShortcutListeningDraft:_e,saveShortcuts:ze}=ob({enabled:lt&&!Re,onTrigger:me=>{var je,wt,bt,B,oe,pe,Ke,Le,$e,nt,jt,ct,Vt,pr,hr,xr;if(me==="openShortcutHelp"){Ze();return}if(me==="openNewSession"){tt();return}if(me==="hideCurrentTab"){r&&ee(r);return}if(me==="toggleHiddenTabs"){Ge(!Ie);return}if(me==="openHistoryForActiveTab"){r&&!Xe(r)&&o(r);return}if(me==="openRemoteForActiveTab"){r&&!et(r)&&!Xe(r)&&c(r);return}if(me==="splitActiveTabRight"){(je=D.current)==null||je.splitActiveTabRight();return}if(me==="splitActiveTabDown"){(wt=D.current)==null||wt.splitActiveTabDown();return}if(me==="floatActiveTab"){(bt=D.current)==null||bt.floatActiveTab();return}if(me==="popoutActiveTab"){(B=D.current)==null||B.popoutActiveTab();return}if(me==="dockActiveTab"){(oe=D.current)==null||oe.dockActiveTab();return}if(me==="focusLeftPane"){(pe=D.current)==null||pe.focusLeftPane();return}if(me==="focusRightPane"){(Ke=D.current)==null||Ke.focusRightPane();return}if(me==="focusUpPane"){(Le=D.current)==null||Le.focusUpPane();return}if(me==="focusDownPane"){($e=D.current)==null||$e.focusDownPane();return}if(me==="moveActiveTabToLeftPane"){(nt=D.current)==null||nt.moveActiveTabToLeftPane();return}if(me==="moveActiveTabToRightPane"){(jt=D.current)==null||jt.moveActiveTabToRightPane();return}if(me==="moveActiveTabToUpPane"){(ct=D.current)==null||ct.moveActiveTabToUpPane();return}if(me==="moveActiveTabToDownPane"){(Vt=D.current)==null||Vt.moveActiveTabToDownPane();return}if(me==="triggerPrimaryApprovalAction"){ne(0);return}if(me==="triggerSecondaryApprovalAction"){ne(1);return}if(me==="triggerTertiaryApprovalAction"){ne(2);return}if(me==="setActiveTabShortcut"){(pr=D.current)==null||pr.setShortcutForActiveTab();return}if(me==="selectPreviousGroupTab"){(hr=D.current)==null||hr.activatePreviousTabInGroup();return}if(me==="selectNextGroupTab"){(xr=D.current)==null||xr.activateNextTabInGroup();return}!r||!et(r)||Xe(r)||me==="toggleCliView"&&f(d==="chat"?"terminal":"chat")}}),Je=kt.useCallback(()=>{qe(),Be(null),_e([])},[qe,Be,_e]),ft=kt.useMemo(()=>Qe==="all"?Ae:Ae.filter(me=>Hb(me)===Qe),[Ae,Qe]),pt=kt.useCallback(()=>{const me=Object.fromEntries(Ae.map(je=>[je.id,""]));ze(me)},[Ae,ze]),ht=kt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const me=Object.fromEntries(Ae.map(je=>[je.id,je.defaultShortcut]));ze(me)},[Ae,ze]);return kt.useEffect(()=>{const me=je=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?je.metaKey&&je.key.toLowerCase()==="w":je.ctrlKey&&je.key.toLowerCase()==="w")&&(je.preventDefault(),r&&ee&&ee(r))};return window.addEventListener("keydown",me),()=>window.removeEventListener("keydown",me)},[r,ee]),kt.useEffect(()=>{if(!Re||Ce)return;const me=je=>{je.key==="Escape"&&(je.preventDefault(),Je())};return window.addEventListener("keydown",me,!0),()=>window.removeEventListener("keydown",me,!0)},[Je,Re,Ce]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(wp,{activeConv:r,wsStatus:n,isConnected:a,conversations:fe,hiddenConversations:p,onOpenHistory:o,onHideConversation:ee,onShowConversation:_,onShowAllHidden:we,onResetPanelsToMain:Q,notifications:ke,notificationUnreadCount:Z,onOpenNotification:z,onMarkNotificationRead:Me,onMarkNotificationUnread:We,onDeleteNotification:Fe,inboxOpen:Ne,onInboxOpenChange:Te,hiddenOpen:Ie,onHiddenOpenChange:Ge,onOpenNewSession:t?void 0:tt,onOpenDashboardGuide:Ze,guideNudgeVisible:He,actionShortcuts:Pe,onOpenRemote:()=>{!r||et(r)||Xe(r)||c(r)},onStopCli:l,activeCliViewMode:d,onSetCliViewMode:f,onOpenGitDialog:G}),e?s.jsx(qx,{conversations:u,hiddenConversations:p,ides:m,actionLogs:y,sendDaemonCommand:N,setActionLogs:h,setCliViewModeOverrides:j,isStandalone:x,userName:v,requestedActiveTabKey:A,onRequestedActiveTabConsumed:g,requestedMachineId:M,onRequestedMachineConsumed:T,requestedMobileSection:k,onRequestedMobileSectionConsumed:w,onOpenHistory:o,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowAllHiddenConversations:we,onHideConversation:ee,onOpenNewSession:tt,liveSessionInboxState:Se}):t?s.jsx(sb,{containerRef:K,isSplitMode:R,numGroups:S,groupSizes:O,groupedConvs:U,clearedTabs:P,ides:m,actionLogs:y,sendDaemonCommand:N,setActionLogs:h,isStandalone:x,hasRegisteredMachines:xe.length>0,userName:v,focusedGroup:C,focusGroup:I,moveTabToGroup:W,splitTabRelative:E,closeGroup:$,handleResizeStart:F,groupActiveTabIds:J,setGroupActiveTab:he,groupTabOrders:le,setGroupTabOrder:te,toggleHiddenTab:ye,onOpenNewSession:tt,allowTabShortcuts:!1,liveSessionInboxState:Se}):s.jsx(vb,{visibleConversations:fe,clearedTabs:P,ides:m,actionLogs:y,sendDaemonCommand:N,setActionLogs:h,isStandalone:x,hasRegisteredMachines:xe.length>0,initialDataLoaded:b,userName:v,toggleHiddenTab:ye,actionShortcuts:Pe,registerActionHandlers:me=>{D.current=me},onActiveTabChange:ae,requestedActiveTabKey:be,onRequestedActiveTabConsumed:X,onRequestScrollToBottom:ge,scrollToBottomRequest:ue,onOpenNewSession:tt,liveSessionInboxState:Se,layoutProfile:se}),De&&s.jsx(Nb,{machines:xe,ides:m,onClose:H,onBrowseDirectory:ie,onSaveWorkspace:re,onLaunchIde:q,onLaunchProvider:Y,onListSavedSessions:ce}),V&&s.jsx(Hl,{daemonId:V.daemonId,workspace:V.workspace,onClose:()=>L(null)}),Re&&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:Je,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:me=>me.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:Je,"aria-label":"Close dashboard guide",children:s.jsx(St,{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(me=>s.jsx("button",{type:"button",className:`btn btn-sm ${Ue===me.id?"btn-primary":"btn-secondary"}`,onClick:()=>dt(me.id),children:me.label},me.id))}),Ue==="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 ",ve?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),Ue==="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."]})]})]})]}),Ue==="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(me=>s.jsx("button",{type:"button",className:`btn btn-sm ${Qe===me.id?"btn-primary":"btn-secondary"}`,onClick:()=>ut(me.id),children:me.label},me.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:pt,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:ht,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:ft.map(me=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${Ce===me.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:me.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:me.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:me.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:Ce===me.id?Ee.length>0?`${Ee.join(" ")} ...`:"Listening...":Pe[me.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Be(me.id),_e([])},children:Ce===me.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const je={...Pe};je[me.id]="",ze(je)},children:"Disable"})]})]})},me.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",ve?"⌘⇧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 qn=[{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 Gb({onClose:e}){const[t,r]=i.useState(0),n=qn[t],a=t===qn.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(St,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:qn.map((o,c)=>s.jsx("div",{style:{width:c===t?24:8,height:8,borderRadius:4,background:c===t?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},c))}),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:`
62
+ `,U.style.top="52px",U.style.height="calc(100% - 52px)";const De=Ne.querySelector("[data-adhdev-popout-focus]");De&&(De.onclick=()=>{window.focus()});const Be=Ne.querySelector("[data-adhdev-popout-dock]");Be&&(Be.disabled=!Q,Be.style.opacity=Q?"1":"0.5",Be.style.cursor=Q?"pointer":"default",Be.onclick=()=>{var Re;Q&&be(Q),(Re=_.defaultView)==null||Re.focus()})}},[z,be]),se=i.useCallback(F=>{var G;const V=k.current,L=V==null?void 0:V.getPanel(F);if(!(!V||!L)){L.group.model.openPanel(L),L.api.setActive(),ce(F,"dockview-shortcut");try{const _=L.group.model.location;_.type==="popout"?_.getWindow().focus():Un((G=L.group.element)==null?void 0:G.ownerDocument)}catch{}}},[ce]),ie=i.useCallback(F=>{const V=k.current,L=V==null?void 0:V.activePanel,G=(V==null?void 0:V.activeGroup)||(L==null?void 0:L.group);if(!V||!L||!G)return;const _=G.panels||[];if(_.length<=1)return;const U=_.findIndex(ve=>ve.id===L.id);if(U<0)return;const Q=(U+F+_.length)%_.length,ne=_[Q];ne&&(ne.group.model.openPanel(ne),ne.api.setActive(),Lt(ne.id)||ce(ne.id,"dockview-shortcut"))},[ce]),re=i.useCallback(F=>{var De;const V=k.current,L=(V==null?void 0:V.activeGroup)||((De=V==null?void 0:V.activePanel)==null?void 0:De.group);if(!V||!L)return;const G=V.groups||[],_=G.find(Be=>Be.id===L.id);if(!_)return;const U=_.element.getBoundingClientRect(),Q=U.left+U.width/2,ne=U.top+U.height/2,ve=(Be,Re,ze,Je)=>Math.max(0,Math.min(Re,Je)-Math.max(Be,ze)),Me=Be=>{const Re=Be.element.getBoundingClientRect(),ze=Re.left+Re.width/2,Je=Re.top+Re.height/2;let ft=0,pt=0,ht=0,me=!1;if(F==="left"?(me=ze<Q,ft=Math.max(0,U.left-Re.right),pt=Math.abs(Je-ne),ht=ve(U.top,U.bottom,Re.top,Re.bottom)):F==="right"?(me=ze>Q,ft=Math.max(0,Re.left-U.right),pt=Math.abs(Je-ne),ht=ve(U.top,U.bottom,Re.top,Re.bottom)):F==="above"?(me=Je<ne,ft=Math.max(0,U.top-Re.bottom),pt=Math.abs(ze-Q),ht=ve(U.left,U.right,Re.left,Re.right)):(me=Je>ne,ft=Math.max(0,Re.top-U.bottom),pt=Math.abs(ze-Q),ht=ve(U.left,U.right,Re.left,Re.right)),!me)return Number.POSITIVE_INFINITY;const je=ht>0?0:120;return ft*3+pt+je};let _e=null,Ne=Number.POSITIVE_INFINITY;for(const Be of G){if(Be.id===_.id)continue;const Re=Me(Be);Number.isFinite(Re)&&(Re>=Ne||(Ne=Re,_e=Be))}return _e||void 0},[]),q=i.useCallback(F=>{var G;const V=re(F);if(!V)return;const L=V.activePanel||V.panels[0];L&&(V.model.openPanel(L),L.api.setActive(),Lt(L.id)||ce(L.id,"dockview-focus"),Un((G=V.element)==null?void 0:G.ownerDocument))},[re,ce]),Y=i.useCallback((F,V)=>{const L=k.current,G=L==null?void 0:L.activePanel,_=(L==null?void 0:L.activeGroup)||(G==null?void 0:G.group);if(!L||!G||!_)return;let U=re(F);!U&&(V!=null&&V.createGroupIfMissing)&&(U=L.addGroup({referenceGroup:_,direction:F})),U&&(G.api.moveTo({group:U,position:"center"}),G.group.model.openPanel(G),G.api.setActive(),Lt(G.id)||ce(G.id,V!=null&&V.createGroupIfMissing?"dockview-split":"dockview-move"))},[re,ce]),{isMac:le,tabShortcuts:ke,shortcutListening:Z,setShortcutListening:Ce,saveShortcuts:Ee}=Ml({sortedTabKeys:e.map(F=>F.tabKey),onFocus:he,onSelectTab:se}),We=i.useCallback(()=>{var L;const F=k.current;if(!F)return;const V=F.activePanel;if(V){if(Lt(V.id)){const G=((L=V.params)==null?void 0:L.routeId)||V.id.slice(7),_=Pt(e,G);_!=null&&_.tabKey&&Ce(_.tabKey);return}z.has(V.id)&&Ce(V.id)}},[z,se,Ce,e]),Fe=i.useCallback(F=>{const V=[];return F.metaKey&&V.push(le?"⌘":"Meta"),F.ctrlKey&&V.push("Ctrl"),F.altKey&&V.push(le?"⌥":"Alt"),F.shiftKey&&F.key.length!==1&&V.push(le?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(F.key)?null:(V.push(Rl(F.key)),V.join("+"))},[le]),D=i.useCallback(F=>{var V,L;switch(F){case"splitActiveTabRight":Y("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":Y("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const G=de();G&&ge(G);return}case"popoutActiveTab":{const G=de();G&&fe(G);return}case"dockActiveTab":{const G=de();if(!G)return;X(G)?be(G):ee(G)&&we(G);return}case"focusLeftPane":q("left");return;case"focusRightPane":q("right");return;case"focusUpPane":q("above");return;case"focusDownPane":q("below");return;case"moveActiveTabToLeftPane":Y("left");return;case"moveActiveTabToRightPane":Y("right");return;case"moveActiveTabToUpPane":Y("above");return;case"moveActiveTabToDownPane":Y("below");return;case"selectPreviousGroupTab":ie(-1);return;case"selectNextGroupTab":ie(1);return;case"setActiveTabShortcut":We();return;case"hideCurrentTab":{const G=(L=(V=k.current)==null?void 0:V.activePanel)==null?void 0:L.id;G&&!Lt(G)&&ae(G);return}default:return}},[ie,we,q,ge,de,ae,ee,X,be,Y,fe,We]);i.useEffect(()=>{if(!C)return;const F=C.sourceDocument,V=F.defaultView??window,L=G=>{const _=F.querySelector("[data-dockview-tab-context-menu]");_&&_.contains(G.target)||I(null)};return V.addEventListener("mousedown",L,!0),V!==window&&window.addEventListener("mousedown",()=>I(null),!0),()=>{V.removeEventListener("mousedown",L,!0),V!==window&&window.removeEventListener("mousedown",()=>I(null),!0)}},[C]);const Se=i.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:z,hasDetachedConversationPanels:J,ides:r,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:N,liveSessionInboxState:A,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:ae,userName:f,scrollToBottomRequest:v,tabShortcuts:ke,openTabContextMenu:({x:F,y:V,tabKey:L,sourceDocument:G})=>I({x:F,y:V,tabKey:L,sourceDocument:G??document}),popoutTab:fe,moveTabBackToMain:be,isTabInPopout:X,floatTab:ge,isTabFloating:ee}),[n,t,z,J,r,c,l,N,A,a,o,ae,f,v,ke,fe,be,X,ge,ee]),Ae=C?cb({isTabInPopout:X(C.tabKey),isTabFloating:ee(C.tabKey),tabShortcut:ke[C.tabKey],actionShortcuts:p}):[],Le=i.useCallback(F=>{var G;const V=k.current;if((((G=V==null?void 0:V.activePanel)==null?void 0:G.id)??null)===F.id){F.group.model.openPanel(F);return}F.group.model.openPanel(F),F.api.setActive()},[]),Pe=i.useCallback((F,V="requested-tab")=>{if(!F)return!1;const L=k.current;if(!L)return!1;const G=L.getPanel(F);return G?(Le(G),ce(F,V),b==null||b(),!0):!1},[Le,b,ce]),He=i.useCallback(()=>{if(O.current)return!1;const F=Pe(H.current,"stored-layout-restore");return F&&(O.current=!0),F},[Pe]),Ue=i.useCallback(()=>{var V;const F=k.current;F&&zh(g,{activeTabId:((V=F.activePanel)==null?void 0:V.id)??null,layout:F.toJSON()})},[g]),Qe=i.useCallback(()=>{Gh(g,$.current)},[g]),lt=i.useCallback(F=>{var G,_,U,Q;const V=k.current;if(!V)return{kind:"grid"};const L=V.toJSON();for(const ne of L.floatingGroups||[])if((_=(G=ne.data)==null?void 0:G.views)!=null&&_.includes(F)&&ne.position)return{kind:"floating",position:ne.position};for(const ne of L.popoutGroups||[])if((Q=(U=ne.data)==null?void 0:U.views)!=null&&Q.includes(F))return{kind:"popout",position:ne.position,popoutUrl:ne.url};return{kind:"grid"}},[]),dt=i.useCallback(F=>{const V=k.current;if(!V)return;const L=V.getPanel(F),G=$.current[F];if(!L||!G||G.kind==="grid")return;if(L.group.model.location.type===G.kind){delete $.current[F],Qe();return}if(G.kind==="floating"){V.addFloatingGroup(L,{x:G.position.left??24,y:G.position.top??24,width:G.position.width,height:G.position.height}),delete $.current[F],Qe();return}delete $.current[F],Qe()},[Qe]);i.useEffect(()=>(m==null||m({setShortcutForActiveTab:We,restoreHiddenTabToSavedLocation:dt,activateConversationTab:se,resetAllPanelsToMain:ue,activatePreviousTabInGroup:()=>ie(-1),activateNextTabInGroup:()=>ie(1),floatActiveTab:()=>{const F=de();F&&ge(F)},popoutActiveTab:()=>{const F=de();F&&fe(F)},dockActiveTab:()=>{const F=de();F&&(X(F)?be(F):ee(F)&&we(F))},splitActiveTabRight:()=>Y("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>Y("below",{createGroupIfMissing:!0}),focusLeftPane:()=>q("left"),focusRightPane:()=>q("right"),focusUpPane:()=>q("above"),focusDownPane:()=>q("below"),moveActiveTabToLeftPane:()=>Y("left"),moveActiveTabToRightPane:()=>Y("right"),moveActiveTabToUpPane:()=>Y("above"),moveActiveTabToDownPane:()=>Y("below")}),()=>m==null?void 0:m(null)),[ie,we,ge,q,de,ee,X,Y,be,fe,m,ue,dt,se,We]),i.useEffect(()=>()=>{var F;(F=K.current)==null||F.call(K),K.current=null},[]);const ut=i.useCallback(F=>{var L,G;k.current=F.api,(L=K.current)==null||L.call(K),K.current=null;const V=Uh(g);if(H.current=(V==null?void 0:V.activeTabId)??null,V!=null&&V.layout&&F.api.fromJSON(V.layout,{reuseExistingPanels:!1}),S.current=xi({hasStoredLayout:!!(V!=null&&V.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),S.current||(wi(F.api,e),ji(F.api,e,x)),F.api.totalPanels===0&&e.length>0){const _=xb(F.api,e,j);if(_){const U=F.api.getPanel(_);U&&Le(U)}}else!S.current&&!Pe(j)&&He();if(R.current=!0,F.api.onDidActivePanelChange(_=>{var Q;if(H.current=(_==null?void 0:_.id)??null,O.current=!0,xe(),_&&Lt(_.id)){const ne=((Q=_.params)==null?void 0:Q.routeId)||_.id.slice(7),ve=Pt(e,ne);y((ve==null?void 0:ve.tabKey)??null),Ue();return}if(y((_==null?void 0:_.id)??null),Ue(),!_)return;const U=z.get(_.id);(U==null?void 0:U.streamSource)==="agent-stream"&&U.agentType&&T(U.routeId,jc(),{agentType:U.agentType,...U.sessionId&&{targetSessionId:U.sessionId}}).catch(()=>{})}),F.api.onDidLayoutChange(()=>{Ue(),xe(),E(_=>_+1)}),fb()){const _=Ne=>({clientX:Ne.clientX,clientY:Ne.clientY}),U=Ne=>{const De=Ne==null?void 0:Ne.getBoundingClientRect();return De?{left:De.left,right:De.right,top:De.top,bottom:De.bottom}:null},Q=Ne=>{var Be;const De=(Be=w.current)==null?void 0:Be.getBoundingClientRect();return De?Ne.clientX<De.left||Ne.clientX>De.right||Ne.clientY<De.top||Ne.clientY>De.bottom:!1},ne=ub({detachDelayMs:Pl,onDetach:({panelId:Ne,clientX:De,clientY:Be})=>{var ht,me;const Re=F.api.getPanel(Ne);if(!Re)return;try{if(Re.group.model.location.type!=="grid")return}catch{return}const ze=(ht=w.current)==null?void 0:ht.getBoundingClientRect(),Je=(me=Re.group.element)==null?void 0:me.getBoundingClientRect(),ft=Math.round(Math.min(Math.max((Je==null?void 0:Je.width)??600,360),720)),pt=Math.round(Math.min(Math.max((Je==null?void 0:Je.height)??500,260),640));F.api.addFloatingGroup(Re,{x:ze?Math.max(0,De-ze.left-32):void 0,y:ze?Math.max(0,Be-ze.top-18):void 0,width:ft,height:pt}),Re.api.setActive(),Ue(),xe(),E(je=>je+1)}}),ve=[F.api.onWillDragPanel(Ne=>{if(!(Ne.nativeEvent.defaultPrevented||Ne.nativeEvent.shiftKey)){try{if(Ne.panel.group.model.location.type!=="grid")return}catch{return}ne.startDrag({panelId:Ne.panel.id,selfPanelBounds:U(Ne.panel.group.element),..._(Ne.nativeEvent)})}}),F.api.onWillShowOverlay(Ne=>{if(ne.hasDetached()){Ne.preventDefault();return}ne.markDockTarget(_(Ne.nativeEvent))}),F.api.onWillDrop(Ne=>{if(ne.hasDetached()){Ne.preventDefault(),ne.endDrag();return}ne.markDockTarget(_(Ne.nativeEvent))}),F.api.onDidDrop(()=>ne.endDrag()),F.api.onUnhandledDragOverEvent(Ne=>{ne.isDragging()&&ne.markSelfPanel(_(Ne.nativeEvent))})],Me=Ne=>{if(!ne.isDragging())return;const De=_(Ne);Q(De)&&ne.markNonSelfPanel(De)},_e=()=>ne.endDrag();window.addEventListener("dragover",Me,!0),window.addEventListener("drop",_e,!0),window.addEventListener("dragend",_e,!0),K.current=()=>{ne.dispose();for(const Ne of ve)Ne.dispose();window.removeEventListener("dragover",Me,!0),window.removeEventListener("drop",_e,!0),window.removeEventListener("dragend",_e,!0)}}F.api.onDidAddGroup(_=>{requestAnimationFrame(()=>{var U,Q;try{const ne=(U=_.element)==null?void 0:U.ownerDocument;if(!ne||ne===document)return;(Q=ne.getElementById("dv-popout-window"))==null||Q.classList.add("adhdev-dockview");const ve=document.documentElement.getAttribute("data-theme");ve&&ne.documentElement.setAttribute("data-theme",ve),ne.body.className=document.body.className;const Me=document.documentElement.getAttribute("style");Me&&ne.documentElement.setAttribute("style",Me)}catch{}xe(),E(ne=>ne+1)})}),y(((G=F.api.activePanel)==null?void 0:G.id)??null)},[Le,Pe,z,r,d,g,y,Ue,j,x,T,xe,e]);i.useLayoutEffect(()=>{const F=k.current;if(!F||!R.current||S.current&&xi({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;S.current&&(S.current=!1);const V=P.current,L=new Set(V),G=e.map(_e=>_e.tabKey),_=new Set(G),U=lb({previousVisibleConversationCount:V.length,visibleConversationCount:e.length,ides:r});let Q=!1;for(const _e of V)_.has(_e)||U||($.current[_e]=lt(_e),Q=!0);Q&&Qe(),U||(wi(F,e),ji(F,e,x));const ne=G.filter(_e=>!L.has(_e));let ve=!1;for(const _e of ne){const Ne=F.getPanel(_e),De=$.current[_e];if(!Ne||!De||De.kind==="grid")continue;if(Ne.group.model.location.type===De.kind){delete $.current[_e],ve=!0;continue}if(De.kind==="floating"){F.addFloatingGroup(Ne,{x:De.position.left??24,y:De.position.top??24,width:De.position.width,height:De.position.height}),delete $.current[_e],ve=!0;continue}}if(ve&&Qe(),P.current=G,j&&Pe(j))return;!F.activePanel&&F.panels[0]&&Le(F.panels[0]),!!(F.activePanel&&F.getPanel(F.activePanel.id))||He()},[Le,Pe,He,r,d,Qe,lt,j,x,e]),i.useEffect(()=>{R.current&&Pe(j)},[Pe,j]),i.useEffect(()=>{const F=L=>{const G=L.target;if(!G)return;const _=G.querySelector("[data-tab-key]")||G.closest("[data-tab-key]");if(_){const U=_.getAttribute("data-tab-key");if(U&&L.dataTransfer){const Q=G.closest(".dv-tab")||_.closest(".dv-tab")||_;L.dataTransfer.effectAllowed="move",L.dataTransfer.setData("text/tab-key",U),Q instanceof HTMLElement&&L.dataTransfer.setDragImage(Q,Math.max(12,Math.round(Q.clientWidth/2)),Math.max(10,Math.round(Q.clientHeight/2)))}}};window.addEventListener("dragstart",F);const V=vi(k.current);for(const L of V)L.addEventListener("dragstart",F);return()=>{window.removeEventListener("dragstart",F);for(const L of V)L.removeEventListener("dragstart",F)}},[W]),i.useEffect(()=>{var V;const F=(V=w.current)==null?void 0:V.querySelector(".adhdev-dockview");F instanceof HTMLElement&&zn(F,M),ye(),xe()},[xe,ye,M]),i.useEffect(()=>{xe()},[xe]),i.useEffect(()=>{const F=V=>{if(V.defaultPrevented||Z)return;const L=Fe(V);if(!L)return;const G=V.metaKey||V.ctrlKey||V.altKey;Ca(V.target)&&!G||nn(le).setActiveTabShortcut!==L||(V.preventDefault(),V.stopPropagation(),We())};return window.addEventListener("keydown",F,!0),()=>window.removeEventListener("keydown",F,!0)},[Fe,le,Z,We]),i.useEffect(()=>{const F=w.current;if(!F)return;const V=L=>{var ne,ve;if(!L.isTrusted)return;const G=(ve=(ne=L.target)==null?void 0:ne.closest)==null?void 0:ve.call(ne,".dv-scrollable");if(!G)return;L.preventDefault(),L.stopPropagation();const _=Math.abs(L.deltaX),U=Math.abs(L.deltaY),Q=_>U?L.deltaX:L.deltaY;G.dispatchEvent(new WheelEvent("wheel",{deltaY:Q,deltaMode:L.deltaMode,bubbles:!1,cancelable:!0}))};return F.addEventListener("wheel",V,{passive:!1,capture:!0}),()=>F.removeEventListener("wheel",V,{capture:!0})},[]),i.useEffect(()=>{const F=vi(k.current);if(F.length===0)return;const V=F.map(L=>{let G=[],_=null;const U=()=>{_!=null&&L.clearTimeout(_),_=null,G=[]},Q=()=>{_!=null&&L.clearTimeout(_),_=L.setTimeout(()=>{_=null,G=[]},1200)},ne=Me=>{if(!Me.ctrlKey&&!Me.metaKey&&!Me.altKey)return;const _e=Fe(Me);if(!_e)return;const Ne=Tl();for(const[De,Be]of Object.entries(Ne))if(e.some(Re=>Re.tabKey===De)&&Be===_e){Me.preventDefault(),se(De);return}},ve=Me=>{if(Me.defaultPrevented||Z)return;const _e=Fe(Me);if(!_e)return;const Ne=Me.metaKey||Me.ctrlKey||Me.altKey;if(Ca(Me.target))return;const De=nn(le),Be=Object.entries(De).filter(([je,wt])=>!!wt&&(je==="splitActiveTabRight"||je==="splitActiveTabDown"||je==="floatActiveTab"||je==="popoutActiveTab"||je==="dockActiveTab"||je==="focusLeftPane"||je==="focusRightPane"||je==="focusUpPane"||je==="focusDownPane"||je==="moveActiveTabToLeftPane"||je==="moveActiveTabToRightPane"||je==="moveActiveTabToUpPane"||je==="moveActiveTabToDownPane"||je==="selectPreviousGroupTab"||je==="selectNextGroupTab"||je==="setActiveTabShortcut"||je==="hideCurrentTab")),Re=Ne?[_e]:[...G.slice(-1),_e].slice(-2),ze=Re.join(" "),Je=Re[Re.length-1],ft=Be.find(([,je])=>je===ze);if(ft){Me.preventDefault(),U(),D(ft[0]);return}if(Be.some(([,je])=>je.startsWith(`${ze} `))){Me.preventDefault(),G=Re,Q();return}const ht=Be.find(([,je])=>je===Je);if(ht){Me.preventDefault(),U(),D(ht[0]);return}if(Be.some(([,je])=>je.startsWith(`${Je} `))){Me.preventDefault(),G=[Je],Q();return}U()};return L.addEventListener("keydown",ne),L.addEventListener("keydown",ve),()=>{U(),L.removeEventListener("keydown",ne),L.removeEventListener("keydown",ve)}});return()=>{for(const L of V)L()}},[Fe,le,W,se,Z,D,e]);const Te=M==="light"?aa:oa,Ge=((tt=(qe=(Ze=k.current)==null?void 0:Ze.activePanel)==null?void 0:qe.group.element)==null?void 0:tt.ownerDocument)??document;return s.jsxs(Dl.Provider,{value:Se,children:[s.jsx("div",{ref:w,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(Cd,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:bb,remote:gb},defaultTabComponent:vb,watermarkComponent:yb,onReady:ut,singleTabMode:"default",tabAnimation:"smooth",theme:Te,popoutUrl:"/popout.html"})}),C&&sr.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:Ae.map(F=>{if(F.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},F.id);let V=s.jsx(vu,{size:13,className:"shrink-0 opacity-70"}),L=()=>{};switch(F.id){case"dockInWindow":case"dockBackToGrid":V=s.jsx(ju,{size:13,className:"shrink-0 opacity-70"}),L=()=>{we(C.tabKey),I(null)};break;case"moveBackToMain":V=s.jsx(yu,{size:13,className:"shrink-0 opacity-70"}),L=()=>{be(C.tabKey),I(null)};break;case"floatAsPanel":V=s.jsx(wu,{size:13,className:"shrink-0 opacity-70"}),L=()=>{ge(C.tabKey),I(null)};break;case"openInNewWindow":V=s.jsx(gu,{size:13,className:"shrink-0 opacity-70"}),L=()=>{fe(C.tabKey),I(null)};break;case"setShortcut":L=G=>{G.stopPropagation(),Ce(C.tabKey),I(null)};break;case"removeShortcut":V=s.jsx(St,{size:13,className:"shrink-0 opacity-70"}),L=()=>{const G={...ke};delete G[C.tabKey],Ee(G),I(null)};break;case"hideTab":V=s.jsx(Da,{size:13,className:"shrink-0 opacity-70"}),L=()=>{ae(C.tabKey),I(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 ${F.tone==="muted"?"text-text-muted":""}`,onMouseDown:pb,onClick:L,children:[V,s.jsx("span",{className:"flex-1 min-w-0",children:F.label}),F.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:F.shortcut}):null]},F.id)})}),C.sourceDocument.body),Z&&sr.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:()=>Ce(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:F=>F.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. ",le?"⌘+1":"Ctrl+1",", ",le?"⌥+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"})]})}),Ge.body)]})}const El="adhdev-recent-launch-args-v1",jb=8;function kb(e){return String(e||"").trim().replace(/\s+/g," ")}function $l(e,t){return`${e.trim()}::${t.trim()}`}function Bl(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(El)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function Sb(e){if(!(typeof window>"u"))try{window.localStorage.setItem(El,JSON.stringify(e))}catch{}}function Kl(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=Bl().byKey[$l(r,n)])==null?void 0:o.items)||[]}function Ol(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=kb(r);if(!n||!a||!o)return;const c=Bl(),l=$l(n,a),d=((u=c.byKey[l])==null?void 0:u.items)||[],f=[o,...d.filter(p=>p!==o)].slice(0,jb);c.byKey[l]={items:f},Sb(c)}function Wl(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Hr({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 Nb({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 Fl({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:c,onOpenHistory:l,onClearSelection:d}){const f=o?Sl(o):null,u=Nb({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Hr,{title:"Saved history",description:eo(),action:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:c,children:t?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:l,children:Mp()})]}),children:[f?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:f.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:f.providerSessionId}),s.jsx("div",{className:"mt-1",children:f.metaLine}),f.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:f.updatedLabel}),f.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:f.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 Vn(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>ps(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>ps(a,"acp"))?"acp":null}function Rr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Cb({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:c,onListSavedSessions:l}){var F,V;const d=fr(),f=i.useMemo(()=>[...e].sort(Wa),[e]),[u,p]=i.useState(((F=f[0])==null?void 0:F.id)||""),m=i.useMemo(()=>f.find(L=>L.id===u)||f[0],[u,f]),y=i.useMemo(()=>((m==null?void 0:m.workspaces)||[]).map(L=>({id:L.id,path:L.path,label:L.label})),[m]),N=(m==null?void 0:m.defaultWorkspaceId)||null,[h,j]=i.useState(""),[x,b]=i.useState(""),[v,A]=i.useState(Vn(f[0])),[g,M]=i.useState(""),[T,k]=i.useState(""),[w,K]=i.useState([]),[R,S]=i.useState(""),[O,H]=i.useState([]),[P,C]=i.useState(!1),[I,W]=i.useState(!1),[E,$]=i.useState(""),[z,J]=i.useState(!1),[he,ce]=i.useState(()=>xt()),[te,ye]=i.useState(null),[fe,be]=i.useState(!1),[X,ae]=i.useState(""),[ge,ee]=i.useState(!1),[de,we]=i.useState(""),[ue,xe]=i.useState([]),[se,ie]=i.useState(!1),[re,q]=i.useState(""),[Y,le]=i.useState(!1),ke=i.useRef(null),Z=i.useRef(0);i.useEffect(()=>{var L;!u&&((L=f[0])!=null&&L.id)&&p(f[0].id)},[u,f]),i.useEffect(()=>{!m||!(!m.workspaces||!m.availableProviders||!m.detectedIdes||!m.recentLaunches)||d(m.id,{minFreshMs:3e4}).catch(()=>{})},[d,m]);const Ce=i.useMemo(()=>((m==null?void 0:m.availableProviders)||[]).filter(L=>ps(L,"cli")),[m]),Ee=i.useMemo(()=>((m==null?void 0:m.availableProviders)||[]).filter(L=>ps(L,"acp")),[m]),We=i.useMemo(()=>((m==null?void 0:m.detectedIdes)||[]).map(L=>({id:L.type,label:L.name||L.type,meta:L.running?"Detected locally":"Available to open"})),[m]),Fe=i.useMemo(()=>v==="cli"?Ce.map(L=>({id:L.type,label:L.displayName||L.type,meta:"CLI provider"})):v==="acp"?Ee.map(L=>({id:L.type,label:L.displayName||L.type,meta:"ACP provider"})):We,[Ee,v,Ce,We]);i.useEffect(()=>{var G;if(!m)return;if(ke.current!==m.id){ke.current=m.id,j(N||((G=y[0])==null?void 0:G.id)||"__home__"),b(""),A(Vn(m)),M(""),k(""),S(""),H([]),W(!1),$(""),ce(xt()),ae("");return}j(_=>{var U;return _==="__custom__"||_==="__home__"||y.some(Q=>Q.id===_)?_:N||((U=y[0])==null?void 0:U.id)||"__home__"}),A(_=>_==="ide"&&We.length>0||_==="cli"&&Ce.length>0||_==="acp"&&Ee.length>0?_:Vn(m))},[Ee.length,Ce.length,N,We.length,m,y]),i.useEffect(()=>{var L;v&&(Fe.some(G=>G.id===g)||M(((L=Fe[0])==null?void 0:L.id)||""))},[v,Fe,g]);const D=i.useCallback(async(L,G)=>{const _=Z.current+1;return Z.current=_,C(!0),$(""),l(L,G).then(U=>{Z.current===_&&H(U)}).catch(U=>{Z.current===_&&(H([]),$(U instanceof Error?U.message:"Could not load saved sessions"))}).finally(()=>{Z.current===_&&(C(!1),W(!0))})},[l]),Se=i.useCallback((L,G)=>{K(Kl(L,G))},[]);i.useEffect(()=>{Z.current+=1,S(""),ce(xt()),!m||!g||v==="ide"?K([]):Se(m.id,g),W(!1),H([]),$(""),C(!1)},[v,Se,D,m,g]),i.useEffect(()=>{if(!R)return;const L=O.find(G=>G.providerSessionId===R);L!=null&&L.canResume||S("")},[O,R]);const Ae=h==="__custom__"?x.trim():h==="__home__"?"":((V=y.find(L=>L.id===h))==null?void 0:V.path)||"",Le=i.useMemo(()=>m?t.filter(L=>L.id!==m.id&&L.daemonId===m.id).map(L=>L.workspace):[],[t,m]),Pe=i.useMemo(()=>((m==null?void 0:m.recentLaunches)||[]).map(L=>L.workspace),[m]),He=i.useCallback(L=>{const G=String(L.workspace||"").trim();if(!G)return;const _=y.find(U=>Rr(U.path)===Rr(G));if(_){j(_.id),b("");return}j("__custom__"),b(G)},[y]),Ue=i.useCallback(L=>{const G=String(L.workspace||"").trim();if(!G)return{workspaceId:null,workspacePath:null};const _=y.find(U=>Rr(U.path)===Rr(G));return _?{workspaceId:_.id,workspacePath:null}:{workspaceId:null,workspacePath:G}},[y]),Qe=i.useMemo(()=>O.find(L=>L.providerSessionId===R)||null,[O,R]),lt=i.useMemo(()=>{var G;if(v!=="cli"||!m||!g)return null;const L=((G=Ce.find(_=>_.type===g))==null?void 0:G.displayName)||g;return{routeId:m.id,daemonId:m.id,providerSessionId:R||void 0,transport:"pty",mode:"chat",agentName:L,agentType:g,status:"idle",title:L,messages:[],ideType:g,workspaceName:Ae,workspacePath:Ae,displayPrimary:L,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${m.id}:${g}`,machineName:Ct(m,{fallbackId:m.id})}},[v,Ce,Ae,m,R,g]),dt=i.useCallback(()=>{var G;if(!m)return;j("__custom__"),ee(!0),q("");const L=hn(m.platform,pn(x.trim(),Ae,Le,Pe,m.defaultWorkspacePath,(G=y.find(_=>_.id===N))==null?void 0:G.path,y.map(_=>_.path)));ie(!0),n(m.id,L).then(_=>{we(_.path),b(_.path),xe(_.directories)}).catch(_=>{q(_ instanceof Error?_.message:"Could not load folder")}).finally(()=>ie(!1))},[x,N,Pe,Le,n,Ae,m,y]),ut=i.useCallback(L=>{m&&(ie(!0),q(""),n(m.id,L).then(G=>{we(G.path),b(G.path),xe(G.directories)}).catch(G=>{q(G instanceof Error?G.message:"Could not load folder")}).finally(()=>ie(!1)))},[n,m]),Te=i.useCallback(async()=>{if(!m||!Ae)return;le(!0),ae("");const L=await a(m.id,Ae);if(le(!1),!L.ok){ae(L.error||"Could not save workspace");return}ae("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,Ae,m]),Ge=i.useCallback(async()=>{if(!m||!v||!g)return;be(!0),ae("");const L=T.trim()?T.trim().split(/\s+/).filter(Boolean):[],G=v==="ide"?await o(m.id,g,{workspacePath:Ae||null}):await c(m.id,v,g,{workspaceId:h!=="__home__"&&h!=="__custom__"?h:null,workspacePath:h==="__custom__"&&Ae||null,resumeSessionId:v==="cli"&&R?R:null,cliArgs:L});if(be(!1),!G.ok){ae(G.error||"Could not start session");return}v!=="ide"&&T.trim()&&(Ol(m.id,g,T),Se(m.id,g)),r()},[v,T,Se,r,o,c,Ae,m,R,g,h]),Ze=v?Gc(v,v==="cli"&&!!R):"Start",qe=v?qc(v,v==="cli"&&!!R):"Starting…",tt=f.length>5;return m?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(St,{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(Hr,{title:"Machine",children:tt?s.jsx("select",{"aria-label":"Machine",value:m.id,onChange:L=>p(L.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:fe,children:f.map(L=>s.jsx("option",{value:L.id,children:Ct(L,{fallbackId:L.id})},L.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:f.map(L=>{const G=Ct(L,{fallbackId:L.id}),_=m.id===L.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${G}`,"aria-pressed":_,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${_?"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:()=>p(L.id),disabled:fe,title:G,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${L.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:G})]},L.id)})})}),s.jsxs(Hr,{title:"Workspace",description:"Saved workspace is preferred. Home and custom folders are still available.",action:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:dt,disabled:fe,children:"Browse…"}),children:[s.jsxs("select",{value:h,onChange:L=>{const G=L.target.value;j(G),G==="__custom__"?dt():ae("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:fe,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),y.map(L=>s.jsxs("option",{value:L.id,children:[L.id===N?"⭐ ":"",un(L.path,L.label)||L.path]},L.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:h==="__home__"?"Launch without a workspace.":Ae||"Select a workspace folder."}),h==="__custom__"&&Ae&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:dt,disabled:fe,children:[s.jsx(Cs,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Te,disabled:fe||Y,children:Y?"Saving…":"Save workspace"})]})]}),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:Ce.length>0},{id:"ide",label:"IDE",enabled:We.length>0},{id:"acp",label:"ACP",enabled:Ee.length>0}].map(L=>s.jsx("button",{type:"button",className:`btn btn-sm ${v===L.id?"btn-primary":"btn-secondary"}`,onClick:()=>A(L.id),disabled:!L.enabled||fe,children:L.label},L.id))})]}),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:v==="ide"?"Choose IDE":v==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Fe.map(L=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${g===L.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>M(L.id),disabled:fe,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.meta})]},L.id)),Fe.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!=="ide"&&s.jsxs(Hr,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:T,onChange:L=>k(L.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:fe}),w.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:w.map(L=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>k(L),disabled:fe,title:L,children:L},L))})]}),v==="cli"&&s.jsx(Fl,{busy:fe,savedSessionsLoading:P,savedSessionsError:E,selectedSession:Qe,onRefresh:()=>{!m||!g||D(m.id,g)},onOpenHistory:()=>{!m||!g||(J(!0),Wl({hasLoadedInitialResults:I,isLoading:P})&&D(m.id,g))},onClearSelection:()=>S("")}),X&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${X.includes("saved")||X.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:X})]}),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:fe,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:Ge,disabled:fe||!v||!g||h==="__custom__"&&!Ae,children:[s.jsx($a,{size:14}),fe?qe:Ze]})]})]})}),ge&&s.jsx(bn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:de,directories:ue,busy:se,error:re,onClose:()=>ee(!1),onNavigate:ut,onConfirm:L=>{b(L),we(L),j("__custom__"),ee(!1)}}),z&&lt&&s.jsx(ro,{activeConv:lt,ides:[],isCreatingChat:!1,isRefreshingHistory:P,savedSessions:O,isSavedSessionsLoading:P,isResumingSavedSessionId:te,savedHistoryFilters:he,missingWorkspaceResumePath:Ae||null,onSavedHistoryFiltersChange:ce,onClose:()=>J(!1),onNewChat:()=>{S(""),J(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!m||!g||D(m.id,g)},onResumeSavedSession:L=>{if(!m||!g||te||!L.canResume)return;const G=Ue(L);S(L.providerSessionId),He(L),ye(L.providerSessionId),J(!1),be(!0),ae(""),c(m.id,"cli",g,{workspaceId:G.workspaceId,workspacePath:G.workspacePath,resumeSessionId:L.providerSessionId}).then(_=>{if(!_.ok){ae(_.error||"Could not resume session");return}r()}).finally(()=>{be(!1),ye(_=>_===L.providerSessionId?null:_)})}})]}):null}function Tb(e,t){const{sendCommand:r}=mt(),[n,a]=i.useState(null),[o,c]=i.useState(!1);i.useEffect(()=>{if(!e||!t){a(null);return}c(!0),r(e,"git_remote_url",{workspace:t}).then(d=>{const f=(d==null?void 0:d.result)??d;a(typeof(f==null?void 0:f.remoteUrl)=="string"?f.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>c(!1))},[e,t,r]);const l=Mb(n);return{remoteUrl:n,githubUrl:l,loading:o}}function Mb(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 Hl=5e3;function Ab(e){return`git:${e}`}function Ib({workspace:e,includeDiffSummary:t=!1,intervalMs:r=Hl}){return{type:"subscribe",topic:"workspace.git",key:Ab(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function ho(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function hs(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 Lb(e){const t=ho(e);return(t==null?void 0:t.success)===!1?{status:null,error:hs(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:hs(t,"Git status response did not include status")}}function Rb(e){const t=ho(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:hs(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:hs(t,"Git diff summary response did not include diffSummary")}}function Gn(e){return e===void 0||typeof e=="boolean"}function _b(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Gn(t.binary)&&Gn(t.truncated)&&Gn(t.staged)}function Pb(e){const t=ho(e);return(t==null?void 0:t.success)===!1?{diff:null,error:hs(t,"Git file diff request failed")}:_b(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:hs(t,"Git file diff response did not include a valid diff object")}}function Db({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=Hl}){const{sendCommand:o,sendData:c}=mt(),l=typeof t=="string"?t.trim():"",d=!!(r&&e&&l),[f,u]=i.useState(null),[p,m]=i.useState(null),[y,N]=i.useState(!1),[h,j]=i.useState(null),x=i.useCallback(async()=>{if(!(!d||!e||!l)){N(!0),j(null);try{const v=Lb(await o(e,"git_status",{workspace:l}));if(v.error){u(null),m(null),j(v.error);return}if(u(v.status),!n){m(null);return}const A=Rb(await o(e,"git_diff_summary",{workspace:l}));if(A.error){m(null),j(A.error);return}m(A.diffSummary)}catch(v){j(hs(v,"Git status request failed"))}finally{N(!1)}}},[d,e,n,o,l]),b=i.useMemo(()=>l?Ib({workspace:l,includeDiffSummary:n,intervalMs:a}):null,[n,a,l]);return i.useEffect(()=>{if(!d||!e||!l||!b){u(null),m(null),N(!1),j(null);return}const v=c?Ht.subscribe({sendData:c},e,b,A=>{var g,M;A.workspace===l&&(u(A.status),m(A.diffSummary??null),j(((g=A.status)==null?void 0:g.error)||((M=A.diffSummary)==null?void 0:M.error)||null),N(!1))},{retryIntervalMs:1e3}):null;return x(),()=>{v==null||v()}},[d,e,x,b,c,l]),{status:f,diffSummary:p,loading:y,error:h,refresh:x}}const Eb={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},$b={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 ki(e){return e.split("/").pop()??e}function Bb(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function Kb({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 c=n===o.path,l=Eb[o.status]??"?",d=$b[o.status]??"text-zinc-400",f=Bb(o.path),u=ki(o.path),p=o.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 align-middle",title:"Staged"}):null;return s.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${c?"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:l}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[f&&s.jsxs("span",{className:"text-text-secondary",children:[f,"/"]}),s.jsx("span",{className:"text-text-primary",children:u}),o.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",ki(o.oldPath)]}),p]}),!o.binary&&(o.insertions>0||o.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[o.insertions>0&&s.jsxs("span",{className:"text-emerald-500",children:["+",o.insertions]}),o.insertions>0&&o.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),o.deletions>0&&s.jsxs("span",{className:"text-red-400",children:["-",o.deletions]})]}),o.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${o.path}-${o.staged?"S":"U"}`)})}),t&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",s.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function Ob(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 Wb({diff:e,binary:t,truncated:r,loading:n,error:a,className:o=""}){const c=i.useRef(null);if(i.useEffect(()=>{c.current&&(c.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 l=e.split(`
63
+ `);return s.jsxs("div",{ref:c,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:l.map((d,f)=>Ob(d,f))}),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 Fb(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(`
64
+ `)}function Ul({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=mt(),{status:a,diffSummary:o,loading:c,error:l,refresh:d}=Db({daemonId:e,workspace:t,includeDiffSummary:!0}),[f,u]=i.useState(null),[p,m]=i.useState(null),[y,N]=i.useState(""),[h,j]=i.useState(!1),[x,b]=i.useState(!1),[v,A]=i.useState(null),[g,M]=i.useState(null),{githubUrl:T}=Tb(e,t),k=i.useCallback(async H=>{if(!((f==null?void 0:f.path)===H.path&&!f.loading)){u({path:H.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const P=await n(e,"git_diff_file",{workspace:t,path:H.path,staged:H.staged}),C=Pb(P);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(P){const C=P instanceof Error?P.message:"Failed to load diff";u({path:H.path,diff:"",binary:!1,truncated:!1,loading:!1,error:C})}}},[e,n,f,t]),w=i.useCallback(H=>{N(""),j(!1),A(null),M(null),m(H)},[]),K=i.useCallback(()=>{m(null),A(null),b(!1)},[]),R=i.useCallback(async()=>{var H,P,C;if(p){b(!0),A(null);try{let I;p==="checkpoint"?I=await n(e,"git_checkpoint",{workspace:t,message:y,includeUntracked:h}):p==="stash"?I=await n(e,"git_stash_push",{workspace:t,message:y,includeUntracked:h}):p==="stash_pop"?I=await n(e,"git_stash_pop",{workspace:t}):p==="checkout_files"&&f&&(I=await n(e,"git_checkout_files",{workspace:t,paths:[f.path]}));const W=(I==null?void 0:I.result)??I;if((W==null?void 0:W.success)===!1||W!=null&&W.error){A((W==null?void 0:W.error)??"Action failed"),b(!1);return}p==="checkpoint"?M(`Checkpoint created: ${((P=(H=W==null?void 0:W.checkpoint)==null?void 0:H.commit)==null?void 0:P.slice(0,7))??"done"}`):p==="stash"?M(`Stashed as ${((C=W==null?void 0:W.stash)==null?void 0:C.stashRef)??"stash@{0}"}`):p==="stash_pop"?M("Stash restored"):(M("File reverted"),u(null)),m(null),await d()}catch(I){A(I instanceof Error?I.message:"Action failed")}finally{b(!1)}}},[p,n,e,t,y,h,f,d]),S=!!(a!=null&&a.hasConflicts),O=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}),T&&s.jsx("a",{href:`${T}/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:c,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(St,{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"}),O===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]})]})]}),l&&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:l}),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:[c&&!o&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),o&&s.jsx(Kb,{files:o.files,truncated:o.truncated,selectedPath:(f==null?void 0:f.path)??null,onFileClick:k}),!c&&!o&&!l&&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:f?s.jsx(Wb,{diff:f.diff,binary:f.binary,truncated:f.truncated,loading:f.loading,error:f.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"})})]}),g&&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:g}),s.jsx("button",{onClick:()=>M(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:S,title:S?"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:S,title:S?"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:S||!(a!=null&&a.stashCount),title:S?"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:!f,title:f?`Revert changes to ${f.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=Fb((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(H),M("Copied to clipboard"),setTimeout(()=>M(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),p&&s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:s.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[s.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[p==="checkpoint"&&"Create checkpoint commit",p==="stash"&&"Stash changes",p==="stash_pop"&&"Restore latest stash?",p==="checkout_files"&&`Revert changes to ${(f==null?void 0:f.path)??"file"}?`]}),(p==="checkpoint"||p==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:y,onChange:H=>N(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:h,onChange:H=>j(H.target.checked)}),"Include untracked files"]})]}),v&&s.jsx("p",{className:"text-xs text-red-400",children:v}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:K,disabled:x,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:R,disabled:x||(p==="checkpoint"||p==="stash")&&!y.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:x?"Working…":"Confirm"})]})]})})]})})}function Hb({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=i.useState(!1),[o,c]=i.useState(!1),[l,d]=i.useState(!1),[f,u]=i.useState(!1),[p,m]=i.useState(!1),[y,N]=i.useState("quickstart"),[h,j]=i.useState("workspace"),x=i.useMemo(()=>!t&&!e,[t,e]),b=i.useCallback(k=>{a(k),k&&c(!1)},[]),v=i.useCallback(k=>{c(k),k&&a(!1)},[]),A=i.useCallback(()=>{N(r===0?"quickstart":"shortcuts"),j("workspace"),d(!0),a(!1),c(!1)},[r]),g=i.useCallback(()=>{d(!1)},[]),M=i.useCallback(()=>{u(!0)},[]),T=i.useCallback(()=>{u(!1)},[]);return i.useEffect(()=>{if(!x){m(!1);return}m(!0);const k=window.setTimeout(()=>{m(!1)},1e4);return()=>window.clearTimeout(k)},[x]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:l,newSessionOpen:f,guideNudgeVisible:p,guideTab:y,shortcutSection:h,isDesktopDashboard:x,setGuideTab:N,setShortcutSection:j,handleInboxOpenChange:b,handleHiddenOpenChange:v,handleOpenShortcutHelp:A,closeShortcutHelp:g,openNewSession:M,closeNewSession:T}}function Ub(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 zb(e){return e instanceof Error?e.message:String(e||"")}function Vb(e){const t=zb(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Gb({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:c,onStopCli:l,activeCliViewMode:d,onSetActiveCliViewMode:f,mobileChatConversations:u,hiddenConversations:p,ides:m,actionLogs:y,sendDaemonCommand:N,setActionLogs:h,setCliViewModeOverrides:j,isStandalone:x,initialDataLoaded:b,userName:v,requestedMobileTabKey:A,onRequestedMobileTabConsumed:g,requestedMachineId:M,onRequestedMachineConsumed:T,requestedMobileSection:k,onRequestedMobileSectionConsumed:w,containerRef:K,isSplitMode:R,numGroups:S,groupSizes:O,groupedConvs:H,clearedTabs:P,focusedGroup:C,focusGroup:I,moveTabToGroup:W,splitTabRelative:E,closeGroup:$,handleResizeStart:z,groupActiveTabIds:J,setGroupActiveTab:he,groupTabOrders:ce,setGroupTabOrder:te,toggleHiddenTab:ye,visibleConversations:fe,requestedDesktopTabKey:be,onRequestedDesktopTabConsumed:X,onDesktopActiveTabChange:ae,onRequestScrollToBottom:ge,onHideConversation:ee,onShowHiddenConversation:de,onShowAllHiddenConversations:we,scrollToBottomRequest:ue,machineEntries:xe,layoutProfile:se,onBrowseMachineDirectory:ie,onSaveMachineWorkspace:re,onLaunchMachineIde:q,onLaunchMachineProvider:Y,onListMachineSavedSessions:le,notifications:ke,notificationUnreadCount:Z,liveSessionInboxState:Ce,onMarkNotificationRead:Ee,onMarkNotificationUnread:We,onDeleteNotification:Fe}){const D=kt.useRef(null),{inboxOpen:Se,hiddenOpen:Ae,shortcutHelpOpen:Le,newSessionOpen:Pe,guideNudgeVisible:He,guideTab:Ue,shortcutSection:Qe,isDesktopDashboard:lt,setGuideTab:dt,setShortcutSection:ut,handleInboxOpenChange:Te,handleHiddenOpenChange:Ge,handleOpenShortcutHelp:Ze,closeShortcutHelp:qe,openNewSession:tt,closeNewSession:F}=Hb({isMobile:t,showMobileChatMode:e,visibleConversationCount:fe.length}),[V,L]=kt.useState(null),G=kt.useCallback((me,je)=>{L({daemonId:me,workspace:je})},[]),_=kt.useCallback(me=>{var je;sr.flushSync(()=>{de(me)}),(je=D.current)==null||je.restoreHiddenTabToSavedLocation(me.tabKey)},[de]),U=kt.useCallback(me=>{var wt;const je=u.find(bt=>ha(bt,me))||p.find(bt=>ha(bt,me));je&&(p.some(bt=>bt.tabKey===je.tabKey)&&_(je),ae(je.tabKey),(wt=D.current)==null||wt.activateConversationTab(je.tabKey),ge(je.tabKey,"notification-open")),Ee(me.id),Te(!1)},[_,p,u,ae,Ee,ge]),Q=kt.useCallback(()=>{var je;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((je=D.current)==null||je.resetAllPanelsToMain(),Ge(!1))},[Ge]),ne=kt.useCallback(async me=>{var oe;if(!r)return;const je=(oe=r.modalButtons)==null?void 0:oe[me];if(!je)return;const wt=Ms(r);if(!wt)return;const bt=je.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),B=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(bt);try{await N(wt,"resolve_action",{button:je,action:B?"approve":"reject",buttonIndex:me,...ts(r)})}catch(pe){Vb(pe)||console.error("[Shortcut approval] Failed:",pe)}},[r,N]),{isMac:ve,actionDefinitions:Me,actionShortcuts:_e,shortcutListening:Ne,shortcutListeningDraft:De,setShortcutListening:Be,setShortcutListeningDraft:Re,saveShortcuts:ze}=ib({enabled:lt&&!Le,onTrigger:me=>{var je,wt,bt,B,oe,pe,Ke,Ie,$e,nt,jt,ct,Vt,pr,hr,xr;if(me==="openShortcutHelp"){Ze();return}if(me==="openNewSession"){tt();return}if(me==="hideCurrentTab"){r&&ee(r);return}if(me==="toggleHiddenTabs"){Ge(!Ae);return}if(me==="openHistoryForActiveTab"){r&&!Xe(r)&&o(r);return}if(me==="openRemoteForActiveTab"){r&&!et(r)&&!Xe(r)&&c(r);return}if(me==="splitActiveTabRight"){(je=D.current)==null||je.splitActiveTabRight();return}if(me==="splitActiveTabDown"){(wt=D.current)==null||wt.splitActiveTabDown();return}if(me==="floatActiveTab"){(bt=D.current)==null||bt.floatActiveTab();return}if(me==="popoutActiveTab"){(B=D.current)==null||B.popoutActiveTab();return}if(me==="dockActiveTab"){(oe=D.current)==null||oe.dockActiveTab();return}if(me==="focusLeftPane"){(pe=D.current)==null||pe.focusLeftPane();return}if(me==="focusRightPane"){(Ke=D.current)==null||Ke.focusRightPane();return}if(me==="focusUpPane"){(Ie=D.current)==null||Ie.focusUpPane();return}if(me==="focusDownPane"){($e=D.current)==null||$e.focusDownPane();return}if(me==="moveActiveTabToLeftPane"){(nt=D.current)==null||nt.moveActiveTabToLeftPane();return}if(me==="moveActiveTabToRightPane"){(jt=D.current)==null||jt.moveActiveTabToRightPane();return}if(me==="moveActiveTabToUpPane"){(ct=D.current)==null||ct.moveActiveTabToUpPane();return}if(me==="moveActiveTabToDownPane"){(Vt=D.current)==null||Vt.moveActiveTabToDownPane();return}if(me==="triggerPrimaryApprovalAction"){ne(0);return}if(me==="triggerSecondaryApprovalAction"){ne(1);return}if(me==="triggerTertiaryApprovalAction"){ne(2);return}if(me==="setActiveTabShortcut"){(pr=D.current)==null||pr.setShortcutForActiveTab();return}if(me==="selectPreviousGroupTab"){(hr=D.current)==null||hr.activatePreviousTabInGroup();return}if(me==="selectNextGroupTab"){(xr=D.current)==null||xr.activateNextTabInGroup();return}!r||!et(r)||Xe(r)||me==="toggleCliView"&&f(d==="chat"?"terminal":"chat")}}),Je=kt.useCallback(()=>{qe(),Be(null),Re([])},[qe,Be,Re]),ft=kt.useMemo(()=>Qe==="all"?Me:Me.filter(me=>Ub(me)===Qe),[Me,Qe]),pt=kt.useCallback(()=>{const me=Object.fromEntries(Me.map(je=>[je.id,""]));ze(me)},[Me,ze]),ht=kt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const me=Object.fromEntries(Me.map(je=>[je.id,je.defaultShortcut]));ze(me)},[Me,ze]);return kt.useEffect(()=>{const me=je=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?je.metaKey&&je.key.toLowerCase()==="w":je.ctrlKey&&je.key.toLowerCase()==="w")&&(je.preventDefault(),r&&ee&&ee(r))};return window.addEventListener("keydown",me),()=>window.removeEventListener("keydown",me)},[r,ee]),kt.useEffect(()=>{if(!Le||Ne)return;const me=je=>{je.key==="Escape"&&(je.preventDefault(),Je())};return window.addEventListener("keydown",me,!0),()=>window.removeEventListener("keydown",me,!0)},[Je,Le,Ne]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(jp,{activeConv:r,wsStatus:n,isConnected:a,conversations:fe,hiddenConversations:p,onOpenHistory:o,onHideConversation:ee,onShowConversation:_,onShowAllHidden:we,onResetPanelsToMain:Q,notifications:ke,notificationUnreadCount:Z,onOpenNotification:U,onMarkNotificationRead:Ee,onMarkNotificationUnread:We,onDeleteNotification:Fe,inboxOpen:Se,onInboxOpenChange:Te,hiddenOpen:Ae,onHiddenOpenChange:Ge,onOpenNewSession:t?void 0:tt,onOpenDashboardGuide:Ze,guideNudgeVisible:He,actionShortcuts:_e,onOpenRemote:()=>{!r||et(r)||Xe(r)||c(r)},onStopCli:l,activeCliViewMode:d,onSetCliViewMode:f,onOpenGitDialog:G}),e?s.jsx(Yx,{conversations:u,hiddenConversations:p,ides:m,actionLogs:y,sendDaemonCommand:N,setActionLogs:h,setCliViewModeOverrides:j,isStandalone:x,userName:v,requestedActiveTabKey:A,onRequestedActiveTabConsumed:g,requestedMachineId:M,onRequestedMachineConsumed:T,requestedMobileSection:k,onRequestedMobileSectionConsumed:w,onOpenHistory:o,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowAllHiddenConversations:we,onHideConversation:ee,onOpenNewSession:tt,liveSessionInboxState:Ce}):t?s.jsx(rb,{containerRef:K,isSplitMode:R,numGroups:S,groupSizes:O,groupedConvs:H,clearedTabs:P,ides:m,actionLogs:y,sendDaemonCommand:N,setActionLogs:h,isStandalone:x,hasRegisteredMachines:xe.length>0,userName:v,focusedGroup:C,focusGroup:I,moveTabToGroup:W,splitTabRelative:E,closeGroup:$,handleResizeStart:z,groupActiveTabIds:J,setGroupActiveTab:he,groupTabOrders:ce,setGroupTabOrder:te,toggleHiddenTab:ye,onOpenNewSession:tt,allowTabShortcuts:!1,liveSessionInboxState:Ce}):s.jsx(wb,{visibleConversations:fe,clearedTabs:P,ides:m,actionLogs:y,sendDaemonCommand:N,setActionLogs:h,isStandalone:x,hasRegisteredMachines:xe.length>0,initialDataLoaded:b,userName:v,toggleHiddenTab:ye,actionShortcuts:_e,registerActionHandlers:me=>{D.current=me},onActiveTabChange:ae,requestedActiveTabKey:be,onRequestedActiveTabConsumed:X,onRequestScrollToBottom:ge,scrollToBottomRequest:ue,onOpenNewSession:tt,liveSessionInboxState:Ce,layoutProfile:se}),Pe&&s.jsx(Cb,{machines:xe,ides:m,onClose:F,onBrowseDirectory:ie,onSaveWorkspace:re,onLaunchIde:q,onLaunchProvider:Y,onListSavedSessions:le}),V&&s.jsx(Ul,{daemonId:V.daemonId,workspace:V.workspace,onClose:()=>L(null)}),Le&&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:Je,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:me=>me.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:Je,"aria-label":"Close dashboard guide",children:s.jsx(St,{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(me=>s.jsx("button",{type:"button",className:`btn btn-sm ${Ue===me.id?"btn-primary":"btn-secondary"}`,onClick:()=>dt(me.id),children:me.label},me.id))}),Ue==="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 ",ve?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),Ue==="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."]})]})]})]}),Ue==="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(me=>s.jsx("button",{type:"button",className:`btn btn-sm ${Qe===me.id?"btn-primary":"btn-secondary"}`,onClick:()=>ut(me.id),children:me.label},me.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:pt,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:ht,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:ft.map(me=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${Ne===me.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:me.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:me.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:me.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:Ne===me.id?De.length>0?`${De.join(" ")} ...`:"Listening...":_e[me.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Be(me.id),Re([])},children:Ne===me.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const je={..._e};je[me.id]="",ze(je)},children:"Disable"})]})]})},me.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",ve?"⌘⇧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 qn=[{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 qb({onClose:e}){const[t,r]=i.useState(0),n=qn[t],a=t===qn.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(St,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:qn.map((o,c)=>s.jsx("div",{style:{width:c===t?24:8,height:8,borderRadius:4,background:c===t?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},c))}),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:`
65
65
  @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
66
66
  @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
67
- `})]})}function qb({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 c=r===o.tabKey,l=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 ${c?"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:l?"var(--status-warning)":d?"var(--accent-primary)":"var(--text-muted)",boxShadow:d?"0 0 6px var(--accent-primary)":"none"}}),o.title,l&&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 Yb({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,c]=i.useState(()=>a||"native"),l=i.useMemo(()=>Yc(t),[t]),d=i.useMemo(()=>e?no(e,{machineNames:l,connectionStates:r,defaultConnectionState:"new"}):[],[e,l,r]),f=i.useMemo(()=>d.find(h=>h.streamSource==="native"),[d]),u=i.useMemo(()=>d.filter(h=>h.streamSource==="agent-stream"),[d]),p=i.useMemo(()=>e?Pt(d,e.id):null,[d,e]);i.useEffect(()=>{a&&c(a)},[a]),i.useEffect(()=>{if(a||!p)return;const h=p.streamSource==="native"?"native":p.tabKey;!h||o===h||o==="native"&&c(h)},[o,p,a]),i.useEffect(()=>{var h;o!=="native"&&(u.some(j=>j.tabKey===o)||c(((h=u[0])==null?void 0:h.tabKey)||"native"))},[o,u]),i.useEffect(()=>{o==="native"&&(f||u[0]&&c(u[0].tabKey))},[o,f,u]);const m=i.useMemo(()=>o==="native"&&f?f:u.find(h=>h.tabKey===o)||p||f||u[0],[o,f,p,u]),y=i.useMemo(()=>u.map(h=>({tabKey:h.tabKey,title:Fc(h)||n,status:h.status})),[u,n]),N=i.useCallback(h=>{if(h)return d.find(j=>ha(j,{sessionId:h,routeId:h,tabKey:h,providerSessionId:h}))},[d]);return{activeChatTab:o,setActiveChatTab:c,activeConv:m,conversations:d,extensionTabs:y,hasExtensions:y.length>0,resolveConversationByTarget:N}}function Xb({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:c,isStandalone:l,userName:d,onOpenHistory:f,onConversationChange:u,onClose:p}){const[m,y]=i.useState("split"),[N,h]=i.useState(()=>qt(e)?"native":e.tabKey),j=i.useRef(null),x=i.useMemo(()=>t||r.find(I=>I.id===e.routeId),[e.routeId,t,r]),b=i.useMemo(()=>at((x==null?void 0:x.type)||""),[x==null?void 0:x.type]),{conversations:v,extensionTabs:A,hasExtensions:g}=Yb({ideData:x,allIdes:r,connectionStates:n,ideName:b||"IDE",preferredTabKey:qt(e)?void 0:e.tabKey}),M=i.useMemo(()=>x?Pt(v,x.id):null,[x,v]);i.useEffect(()=>{const I=j.current,W={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(j.current=W,!(I&&I.routeId===W.routeId&&I.tabKey===W.tabKey&&I.streamSource===W.streamSource)){if(qt(e)){h("native");return}h(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),i.useEffect(()=>{if(N==="native"){if(v.some(I=>I.streamSource==="native"))return;(M==null?void 0:M.streamSource)==="agent-stream"&&h(M.tabKey);return}if(!v.some(I=>I.tabKey===N)){if((M==null?void 0:M.streamSource)==="agent-stream"){h(M.tabKey);return}h("native")}},[v,N,M]);const T=i.useMemo(()=>N==="native"?v.find(I=>I.streamSource==="native")||e:v.find(I=>I.tabKey===N)||e,[e,v,N]),k=ll(T),w=i.useMemo(()=>k.status||k.modalMessage||k.modalButtons?{...T,...k.status?{status:k.status}:{},...k.modalMessage!==void 0?{modalMessage:k.modalMessage}:{},...k.modalButtons!==void 0?{modalButtons:k.modalButtons}:{}}:T,[T,k]),K=$s(w),R=mn({sendDaemonCommand:o,activeConv:w,setActionLogs:c,isStandalone:l}),{connScreenshot:S,screenshotUsage:O,handleRemoteAction:U}=Ml({doId:K,targetSessionId:wc(w),connState:w.connectionState||"new",viewMode:m}),P=i.useMemo(()=>a.filter(I=>I.routeId===w.tabKey),[a,w.tabKey]);i.useEffect(()=>{u==null||u(w)},[w,u]),i.useEffect(()=>{const I=W=>{W.key==="Escape"&&p()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[p]);const C=i.useCallback(I=>{I.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:p,children:s.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick: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(Tt,{size:16})}),s.jsx("span",{className:"truncate",children:Ua(T)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:p,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(I=>{const W=m===I;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${W?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>y(I),title:I==="split"?"Split view":"Remote only",children:I==="split"?s.jsx(au,{size:15}):s.jsx(Tt,{size:15})},I)})}),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:()=>f(T),title:"Chat History",children:[s.jsx(Pa,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:"History"})]}),s.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:p,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${m==="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:[m!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${m==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(qb,{hasExtensions:g,ideName:b||"IDE",activeChatTab:N,extensionTabs:A,onSelectTab:h}),s.jsx(ic,{activeConv:w,onModalButton:R.handleModalButton}),s.jsx(wa,{activeConv:w,ideEntry:x,showMetaChips:!1,handleSendChat:R.handleSendChat,isSendingChat:R.isSendingChat,sendFeedbackMessage:R.sendFeedbackMessage,handleFocusAgent:R.handleFocusAgent,isFocusingAgent:R.isFocusingAgent,actionLogs:P,userName:d})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${m==="split"?"order-1 md:order-2":""}`,children:s.jsx(ac,{addLog:()=>{},connState:w.connectionState||"new",connScreenshot:S,screenshotUsage:O,transportType:w.transport,onAction:U})})]})]})})}function Jb({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=dp(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 Qb({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(hp,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(ro,{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(Xb,{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&&(et(r.targetConv)||Xe(r.targetConv))&&s.jsx(Jb,{activeConv:r.targetConv,canSaveAndStop:et(r.targetConv)&&!Xe(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(qc,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),o.open&&s.jsx(Gb,{onClose:o.onClose})]})}function Zb({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(lr,{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(c=>{const l=Ct(c,{fallbackId:c.id}),d=n[c.id],f=c.version||c.daemonVersion||"unknown",u=c.versionUpdateRequired===!0;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:l}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",f]}),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(c.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(c.id),children:u?"Update now":"Upgrade"})]},c.id)})]}),!r&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:o,title:"Dismiss",children:s.jsx(St,{size:16})})]})}function eg(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function tg(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 sg(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>tg(t)).map(t=>t.id)}}function rg(){var jo,ko,So,No;const{sendCommand:e}=mt(),t=fr(),r=cl(),n=La(),a=Ps(),[o,c]=Cd(),l=o.get("activeTab"),d=((jo=n.state)==null?void 0:jo.openRemoteForTabKey)||null,f=((ko=n.state)==null?void 0:ko.openMachineId)||null,u=((So=n.state)==null?void 0:So.mobileSection)||null,p=Bc(),m=p.ides||[],y=p.initialLoaded??!0,{updateRouteChats:N,setToasts:h}=p,[j,x]=i.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),b=p.toasts||[],v=p.wsStatus||"connected",A=p.isConnected??!0,g=p.connectionStates||{},M=p.showReconnected||!1,{layoutProfile:T,groupAssignments:k,updateGroupAssignments:w,focusedGroup:K,updateFocusedGroup:R,focusGroup:S,groupActiveTabIds:O,updateGroupActiveTabIds:U,setGroupActiveTab:P,groupTabOrders:C,updateGroupTabOrders:I,setGroupTabOrder:W,groupSizes:E,updateGroupSizes:$,isMobile:F,hasHydratedStoredLayout:J,hydrateStoredLayout:he,focusConversationTab:le}=Yh(),[te,ye]=i.useState(()=>co());i.useEffect(()=>mh(ye),[]);const fe=i.useMemo(()=>eg({isMobile:F,mobileViewMode:te}),[F,te]),[be,X]=i.useState([]),[ae,ge]=i.useState({}),[ee,de]=i.useState({});dr("Dashboard",{ideCount:m.length,toastCount:b.length,focusedGroup:K,groupCount:Object.keys(k).length,actionLogCount:be.length});const we=i.useMemo(()=>m.filter(Ve=>Ve.type==="adhdev-daemon").sort(Wa),[m]),ue=we[0],xe=!!ue;i.useEffect(()=>{const{metadataDaemonIds:Ve,runtimeDaemonIds:It}=sg(we);for(const Bs of Ve)t(Bs,{minFreshMs:3e4}).catch(()=>{});for(const Bs of It)r(Bs,{minFreshMs:3e4}).catch(()=>{})},[t,r,we]);const se=(ue==null?void 0:ue.terminalBackend)||null,ie=ue?Ct(ue,{fallbackId:ue.id}):null,re=(ue==null?void 0:ue.id)||null,q=i.useMemo(()=>Sh(m,ae),[m,ae]),{hiddenTabs:Y,hideTarget:ce,toggleTarget:ke,showTarget:Z,showAllTabs:Se}=kh(),{conversations:Me,visibleConversations:We,visibleTabKeys:Fe,resolveConversationBySessionId:D,resolveConversationByTarget:Ne}=Ph({ides:q,connectionStates:g,clearedTabs:ee,hiddenTabs:Y}),Ie=i.useMemo(()=>new Map(Me.map(Ve=>[Ve.tabKey,Ve])),[Me]),Re=$m(We,fe),De=i.useMemo(()=>Xo(Me,Re),[Me,Re]),He=i.useMemo(()=>Xo(We,Re),[We,Re]);i.useEffect(()=>{Object.keys(ae).length!==0&&ge(Ve=>Nh(Ve,m))},[m,ae]);const Ue=i.useMemo(()=>Vu(m),[m]),{notifications:Qe,unreadCount:lt}=dx({conversations:De,liveSessionInboxState:Ue}),{handleMarkDashboardNotificationRead:dt,handleMarkDashboardNotificationUnread:ut,handleDeleteDashboardNotification:Te}=ux({notifications:Qe,sendDaemonCommand:e}),{containerRef:Ge,normalizedGroupAssignments:Ze,numGroups:qe,isSplitMode:tt,groupedConvs:H,moveTabToGroup:V,closeGroup:L,handleResizeStart:G,splitTabRelative:_}=sx({groupAssignments:k,updateGroupAssignments:w,updateFocusedGroup:R,updateGroupActiveTabIds:U,updateGroupTabOrders:I,groupSizes:E,updateGroupSizes:$,isMobile:F,visibleConversations:He,visibleTabKeys:Fe}),{activeConv:z,openDesktopConversation:Q,requestScrollToBottom:ne,scrollToBottomRequest:ve,setDesktopActiveTab:Ae}=wx({isMobile:F,conversations:De,visibleConversations:He,groupActiveTabIds:O,focusedGroup:K,groupedConvs:H,setSearchParams:c});Sx({activeConv:z,isMobile:F,liveSessionInboxState:Ue,sendDaemonCommand:e});const{requestedDesktopTabKey:Pe,requestedMobileTabKey:Ce,consumeRequestedActiveTab:Ee}=Dh({isMobile:F,urlActiveTab:l,resolveConversationBySessionId:D,setSearchParams:c}),{remoteDialogConv:Be,remoteDialogIdeEntry:_e,remoteDialogActiveConv:ze,setRemoteDialogActiveConv:Je,openRemoteDialog:ft,closeRemoteDialog:pt,cliStopDialogOpen:ht,cliStopTargetConv:me,requestCliStop:je,cancelCliStop:wt,confirmCliStop:bt}=Tx({isMobile:F,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:Pe,conversations:Me,ides:m,resolveConversationByTarget:Ne,activeConv:z,sendDaemonCommand:e}),{historyModalOpen:B,openHistoryModal:oe,closeHistoryModal:pe,historyTargetConv:Ke,isSavedSessionHistoryTarget:Le,isHistoryCreatingChat:$e,isHistoryRefreshingHistory:nt,handleHistorySwitchSession:jt,handleHistoryNewChat:ct,handleHistoryRefresh:Vt,savedHistorySessions:pr,savedHistoryFilters:hr,setSavedHistoryFilters:xr,missingWorkspaceResumePath:ql,isSavedHistoryLoading:Yl,resumingSavedHistorySessionId:Xl,handleRefreshSavedHistory:Jl,handleResumeSavedHistorySession:Ql}=Nx({activeConv:z,remoteDialogConv:Be,remoteDialogActiveConv:ze,ides:m,sendDaemonCommand:e,updateRouteChats:N,setToasts:h,setClearedTabs:de,setSearchParams:c}),Zl=i.useMemo(()=>He,[He]),br=F&&te==="chat",ed=i.useMemo(()=>De.filter(Ve=>lo(Y,Ve)),[De,Y]),yo=i.useCallback(Ve=>{const It=new URLSearchParams(o);It.set("activeTab",Ve),c(It,{replace:!0})},[o,c]),{trackPendingLaunch:td}=bx({ides:m,conversations:Me,onOpenSession:yo}),{handleBrowseMachineDirectory:sd,handleSaveMachineWorkspace:rd,handleLaunchMachineIde:nd,handleLaunchMachineProvider:ad,handleListMachineSavedSessions:od,setActiveCliViewMode:id}=gx({sendDaemonCommand:e,trackPendingLaunch:td,onOpenSession:yo,activeConv:z,ides:m,setCliViewModeOverrides:ge});Ch({visibleConversations:We,clearedTabs:ee,setClearedTabs:de,setActionLogs:X}),Eh({ides:m,sendDaemonCommand:e,setToasts:h,resolveConversationByTarget:Ne});const{isRefreshingHistory:cd,handleRefreshHistory:ld}=yl({sendDaemonCommand:e,activeConv:z,chats:(No=m.find(Ve=>Ve.id===(z==null?void 0:z.routeId)))==null?void 0:No.chats,updateRouteChats:N,setToasts:h,setClearedTabs:de});Jh({urlActiveTab:F&&!br?l:null,conversations:Me,resolveConversationBySessionId:D,normalizedGroupAssignments:Ze,hasHydratedStoredLayout:F&&!br?J:!0,hydrateStoredLayout:F&&!br?he:()=>{},focusConversationTab:le,setSearchParams:c,historyModalOpen:B,activeConv:z,isRefreshingHistory:cd,ides:m,handleRefreshHistory:ld});const dd=i.useMemo(()=>!z||!et(z)||Xe(z)?null:Es(z),[z]),{versionMismatchDaemons:ud,hasRequiredVersionDaemons:vo,appVersion:fd,versionBannerDismissed:md,setVersionBannerDismissed:pd,upgradingDaemons:hd,handleBannerUpgrade:xd}=rx({ides:m,sendDaemonCommand:e}),wo=i.useCallback(Ve=>{Z(Ve),Q(Ve)},[Q,Z]),bd=i.useCallback(Ve=>{ce(Ve)},[ce]);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(xp,{terminalBackend:se,isStandalone:xe,machineLabel:ie,machineKey:re}),(!md||vo)&&s.jsx(Zb,{daemons:ud,targetVersion:fd,required:vo,upgradingDaemons:hd,onUpgrade:xd,onDismiss:()=>pd(!0)}),s.jsx(Vb,{showMobileChatMode:br,isMobile:F,activeConv:z,wsStatus:v,isConnected:A,onOpenHistory:Ve=>{Ve&&Je(Ve),oe()},onOpenRemote:ft,onStopCli:je,activeCliViewMode:dd,onSetActiveCliViewMode:id,mobileChatConversations:Zl,ides:m,actionLogs:be,sendDaemonCommand:e,setActionLogs:X,setCliViewModeOverrides:ge,isStandalone:xe,initialDataLoaded:y,userName:p.userName,requestedMobileTabKey:Ce,onRequestedMobileTabConsumed:Ee,requestedMachineId:f,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:u,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:Ge,isSplitMode:tt,numGroups:qe,groupSizes:E,groupedConvs:H,clearedTabs:ee,focusedGroup:K,focusGroup:S,moveTabToGroup:V,splitTabRelative:_,closeGroup:L,handleResizeStart:G,groupActiveTabIds:O,setGroupActiveTab:P,groupTabOrders:C,setGroupTabOrder:W,toggleHiddenTab:Ve=>ke(Ie.get(Ve)||{tabKey:Ve}),visibleConversations:He,hiddenConversations:ed,requestedDesktopTabKey:Pe,onRequestedDesktopTabConsumed:Ee,onDesktopActiveTabChange:Ae,onRequestScrollToBottom:ne,onHideConversation:bd,onShowHiddenConversation:wo,onShowAllHiddenConversations:Se,scrollToBottomRequest:ve,machineEntries:we,layoutProfile:T,onBrowseMachineDirectory:sd,onSaveMachineWorkspace:rd,onLaunchMachineIde:nd,onLaunchMachineProvider:ad,onListMachineSavedSessions:od,notifications:Qe,notificationUnreadCount:lt,liveSessionInboxState:Ue,onMarkNotificationRead:dt,onMarkNotificationUnread:ut,onDeleteNotification:Te}),s.jsx("style",{children:`
67
+ `})]})}function Yb({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 c=r===o.tabKey,l=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 ${c?"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:l?"var(--status-warning)":d?"var(--accent-primary)":"var(--text-muted)",boxShadow:d?"0 0 6px var(--accent-primary)":"none"}}),o.title,l&&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 Xb({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,c]=i.useState(()=>a||"native"),l=i.useMemo(()=>Xc(t),[t]),d=i.useMemo(()=>e?no(e,{machineNames:l,connectionStates:r,defaultConnectionState:"new"}):[],[e,l,r]),f=i.useMemo(()=>d.find(h=>h.streamSource==="native"),[d]),u=i.useMemo(()=>d.filter(h=>h.streamSource==="agent-stream"),[d]),p=i.useMemo(()=>e?Pt(d,e.id):null,[d,e]);i.useEffect(()=>{a&&c(a)},[a]),i.useEffect(()=>{if(a||!p)return;const h=p.streamSource==="native"?"native":p.tabKey;!h||o===h||o==="native"&&c(h)},[o,p,a]),i.useEffect(()=>{var h;o!=="native"&&(u.some(j=>j.tabKey===o)||c(((h=u[0])==null?void 0:h.tabKey)||"native"))},[o,u]),i.useEffect(()=>{o==="native"&&(f||u[0]&&c(u[0].tabKey))},[o,f,u]);const m=i.useMemo(()=>o==="native"&&f?f:u.find(h=>h.tabKey===o)||p||f||u[0],[o,f,p,u]),y=i.useMemo(()=>u.map(h=>({tabKey:h.tabKey,title:Hc(h)||n,status:h.status})),[u,n]),N=i.useCallback(h=>{if(h)return d.find(j=>ha(j,{sessionId:h,routeId:h,tabKey:h,providerSessionId:h}))},[d]);return{activeChatTab:o,setActiveChatTab:c,activeConv:m,conversations:d,extensionTabs:y,hasExtensions:y.length>0,resolveConversationByTarget:N}}function Jb({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:c,isStandalone:l,userName:d,onOpenHistory:f,onConversationChange:u,onClose:p}){const[m,y]=i.useState("split"),[N,h]=i.useState(()=>qt(e)?"native":e.tabKey),j=i.useRef(null),x=i.useMemo(()=>t||r.find(I=>I.id===e.routeId),[e.routeId,t,r]),b=i.useMemo(()=>at((x==null?void 0:x.type)||""),[x==null?void 0:x.type]),{conversations:v,extensionTabs:A,hasExtensions:g}=Xb({ideData:x,allIdes:r,connectionStates:n,ideName:b||"IDE",preferredTabKey:qt(e)?void 0:e.tabKey}),M=i.useMemo(()=>x?Pt(v,x.id):null,[x,v]);i.useEffect(()=>{const I=j.current,W={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(j.current=W,!(I&&I.routeId===W.routeId&&I.tabKey===W.tabKey&&I.streamSource===W.streamSource)){if(qt(e)){h("native");return}h(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),i.useEffect(()=>{if(N==="native"){if(v.some(I=>I.streamSource==="native"))return;(M==null?void 0:M.streamSource)==="agent-stream"&&h(M.tabKey);return}if(!v.some(I=>I.tabKey===N)){if((M==null?void 0:M.streamSource)==="agent-stream"){h(M.tabKey);return}h("native")}},[v,N,M]);const T=i.useMemo(()=>N==="native"?v.find(I=>I.streamSource==="native")||e:v.find(I=>I.tabKey===N)||e,[e,v,N]),k=dl(T),w=i.useMemo(()=>k.status||k.modalMessage||k.modalButtons?{...T,...k.status?{status:k.status}:{},...k.modalMessage!==void 0?{modalMessage:k.modalMessage}:{},...k.modalButtons!==void 0?{modalButtons:k.modalButtons}:{}}:T,[T,k]),K=$s(w),R=mn({sendDaemonCommand:o,activeConv:w,setActionLogs:c,isStandalone:l}),{connScreenshot:S,screenshotUsage:O,handleRemoteAction:H}=Al({doId:K,targetSessionId:wc(w),connState:w.connectionState||"new",viewMode:m}),P=i.useMemo(()=>a.filter(I=>I.routeId===w.tabKey),[a,w.tabKey]);i.useEffect(()=>{u==null||u(w)},[w,u]),i.useEffect(()=>{const I=W=>{W.key==="Escape"&&p()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[p]);const C=i.useCallback(I=>{I.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:p,children:s.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick: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(Tt,{size:16})}),s.jsx("span",{className:"truncate",children:Ua(T)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:p,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(I=>{const W=m===I;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${W?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>y(I),title:I==="split"?"Split view":"Remote only",children:I==="split"?s.jsx(ou,{size:15}):s.jsx(Tt,{size:15})},I)})}),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:()=>f(T),title:"Chat History",children:[s.jsx(Pa,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:"History"})]}),s.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:p,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${m==="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:[m!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${m==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(Yb,{hasExtensions:g,ideName:b||"IDE",activeChatTab:N,extensionTabs:A,onSelectTab:h}),s.jsx(ic,{activeConv:w,onModalButton:R.handleModalButton}),s.jsx(wa,{activeConv:w,ideEntry:x,showMetaChips:!1,handleSendChat:R.handleSendChat,isSendingChat:R.isSendingChat,sendFeedbackMessage:R.sendFeedbackMessage,handleFocusAgent:R.handleFocusAgent,isFocusingAgent:R.isFocusingAgent,actionLogs:P,userName:d})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${m==="split"?"order-1 md:order-2":""}`,children:s.jsx(ac,{addLog:()=>{},connState:w.connectionState||"new",connScreenshot:S,screenshotUsage:O,transportType:w.transport,onAction:H})})]})]})})}function Qb({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=up(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 Zb({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(xp,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(ro,{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(Jb,{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&&(et(r.targetConv)||Xe(r.targetConv))&&s.jsx(Qb,{activeConv:r.targetConv,canSaveAndStop:et(r.targetConv)&&!Xe(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(Yc,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),o.open&&s.jsx(qb,{onClose:o.onClose})]})}function eg({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(lr,{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(c=>{const l=Ct(c,{fallbackId:c.id}),d=n[c.id],f=c.version||c.daemonVersion||"unknown",u=c.versionUpdateRequired===!0;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:l}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",f]}),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(c.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(c.id),children:u?"Update now":"Upgrade"})]},c.id)})]}),!r&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:o,title:"Dismiss",children:s.jsx(St,{size:16})})]})}function tg(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function sg(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 rg(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>sg(t)).map(t=>t.id)}}function ng(){var jo,ko,So,No;const{sendCommand:e}=mt(),t=fr(),r=ll(),n=La(),a=Ps(),[o,c]=Td(),l=o.get("activeTab"),d=((jo=n.state)==null?void 0:jo.openRemoteForTabKey)||null,f=((ko=n.state)==null?void 0:ko.openMachineId)||null,u=((So=n.state)==null?void 0:So.mobileSection)||null,p=Kc(),m=p.ides||[],y=p.initialLoaded??!0,{updateRouteChats:N,setToasts:h}=p,[j,x]=i.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),b=p.toasts||[],v=p.wsStatus||"connected",A=p.isConnected??!0,g=p.connectionStates||{},M=p.showReconnected||!1,{layoutProfile:T,groupAssignments:k,updateGroupAssignments:w,focusedGroup:K,updateFocusedGroup:R,focusGroup:S,groupActiveTabIds:O,updateGroupActiveTabIds:H,setGroupActiveTab:P,groupTabOrders:C,updateGroupTabOrders:I,setGroupTabOrder:W,groupSizes:E,updateGroupSizes:$,isMobile:z,hasHydratedStoredLayout:J,hydrateStoredLayout:he,focusConversationTab:ce}=Xh(),[te,ye]=i.useState(()=>co());i.useEffect(()=>ph(ye),[]);const fe=i.useMemo(()=>tg({isMobile:z,mobileViewMode:te}),[z,te]),[be,X]=i.useState([]),[ae,ge]=i.useState({}),[ee,de]=i.useState({});dr("Dashboard",{ideCount:m.length,toastCount:b.length,focusedGroup:K,groupCount:Object.keys(k).length,actionLogCount:be.length});const we=i.useMemo(()=>m.filter(Ve=>Ve.type==="adhdev-daemon").sort(Wa),[m]),ue=we[0],xe=!!ue;i.useEffect(()=>{const{metadataDaemonIds:Ve,runtimeDaemonIds:It}=rg(we);for(const Bs of Ve)t(Bs,{minFreshMs:3e4}).catch(()=>{});for(const Bs of It)r(Bs,{minFreshMs:3e4}).catch(()=>{})},[t,r,we]);const se=(ue==null?void 0:ue.terminalBackend)||null,ie=ue?Ct(ue,{fallbackId:ue.id}):null,re=(ue==null?void 0:ue.id)||null,q=i.useMemo(()=>Nh(m,ae),[m,ae]),{hiddenTabs:Y,hideTarget:le,toggleTarget:ke,showTarget:Z,showAllTabs:Ce}=Sh(),{conversations:Ee,visibleConversations:We,visibleTabKeys:Fe,resolveConversationBySessionId:D,resolveConversationByTarget:Se}=Dh({ides:q,connectionStates:g,clearedTabs:ee,hiddenTabs:Y}),Ae=i.useMemo(()=>new Map(Ee.map(Ve=>[Ve.tabKey,Ve])),[Ee]),Le=Bm(We,fe),Pe=i.useMemo(()=>Xo(Ee,Le),[Ee,Le]),He=i.useMemo(()=>Xo(We,Le),[We,Le]);i.useEffect(()=>{Object.keys(ae).length!==0&&ge(Ve=>Ch(Ve,m))},[m,ae]);const Ue=i.useMemo(()=>Gu(m),[m]),{notifications:Qe,unreadCount:lt}=ux({conversations:Pe,liveSessionInboxState:Ue}),{handleMarkDashboardNotificationRead:dt,handleMarkDashboardNotificationUnread:ut,handleDeleteDashboardNotification:Te}=fx({notifications:Qe,sendDaemonCommand:e}),{containerRef:Ge,normalizedGroupAssignments:Ze,numGroups:qe,isSplitMode:tt,groupedConvs:F,moveTabToGroup:V,closeGroup:L,handleResizeStart:G,splitTabRelative:_}=rx({groupAssignments:k,updateGroupAssignments:w,updateFocusedGroup:R,updateGroupActiveTabIds:H,updateGroupTabOrders:I,groupSizes:E,updateGroupSizes:$,isMobile:z,visibleConversations:He,visibleTabKeys:Fe}),{activeConv:U,openDesktopConversation:Q,requestScrollToBottom:ne,scrollToBottomRequest:ve,setDesktopActiveTab:Me}=jx({isMobile:z,conversations:Pe,visibleConversations:He,groupActiveTabIds:O,focusedGroup:K,groupedConvs:F,setSearchParams:c});Nx({activeConv:U,isMobile:z,liveSessionInboxState:Ue,sendDaemonCommand:e});const{requestedDesktopTabKey:_e,requestedMobileTabKey:Ne,consumeRequestedActiveTab:De}=Eh({isMobile:z,urlActiveTab:l,resolveConversationBySessionId:D,setSearchParams:c}),{remoteDialogConv:Be,remoteDialogIdeEntry:Re,remoteDialogActiveConv:ze,setRemoteDialogActiveConv:Je,openRemoteDialog:ft,closeRemoteDialog:pt,cliStopDialogOpen:ht,cliStopTargetConv:me,requestCliStop:je,cancelCliStop:wt,confirmCliStop:bt}=Mx({isMobile:z,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:_e,conversations:Ee,ides:m,resolveConversationByTarget:Se,activeConv:U,sendDaemonCommand:e}),{historyModalOpen:B,openHistoryModal:oe,closeHistoryModal:pe,historyTargetConv:Ke,isSavedSessionHistoryTarget:Ie,isHistoryCreatingChat:$e,isHistoryRefreshingHistory:nt,handleHistorySwitchSession:jt,handleHistoryNewChat:ct,handleHistoryRefresh:Vt,savedHistorySessions:pr,savedHistoryFilters:hr,setSavedHistoryFilters:xr,missingWorkspaceResumePath:Yl,isSavedHistoryLoading:Xl,resumingSavedHistorySessionId:Jl,handleRefreshSavedHistory:Ql,handleResumeSavedHistorySession:Zl}=Cx({activeConv:U,remoteDialogConv:Be,remoteDialogActiveConv:ze,ides:m,sendDaemonCommand:e,updateRouteChats:N,setToasts:h,setClearedTabs:de,setSearchParams:c}),ed=i.useMemo(()=>He,[He]),br=z&&te==="chat",td=i.useMemo(()=>Pe.filter(Ve=>lo(Y,Ve)),[Pe,Y]),yo=i.useCallback(Ve=>{const It=new URLSearchParams(o);It.set("activeTab",Ve),c(It,{replace:!0})},[o,c]),{trackPendingLaunch:sd}=gx({ides:m,conversations:Ee,onOpenSession:yo}),{handleBrowseMachineDirectory:rd,handleSaveMachineWorkspace:nd,handleLaunchMachineIde:ad,handleLaunchMachineProvider:od,handleListMachineSavedSessions:id,setActiveCliViewMode:cd}=yx({sendDaemonCommand:e,trackPendingLaunch:sd,onOpenSession:yo,activeConv:U,ides:m,setCliViewModeOverrides:ge});Th({visibleConversations:We,clearedTabs:ee,setClearedTabs:de,setActionLogs:X}),$h({ides:m,sendDaemonCommand:e,setToasts:h,resolveConversationByTarget:Se});const{isRefreshingHistory:ld,handleRefreshHistory:dd}=vl({sendDaemonCommand:e,activeConv:U,chats:(No=m.find(Ve=>Ve.id===(U==null?void 0:U.routeId)))==null?void 0:No.chats,updateRouteChats:N,setToasts:h,setClearedTabs:de});Qh({urlActiveTab:z&&!br?l:null,conversations:Ee,resolveConversationBySessionId:D,normalizedGroupAssignments:Ze,hasHydratedStoredLayout:z&&!br?J:!0,hydrateStoredLayout:z&&!br?he:()=>{},focusConversationTab:ce,setSearchParams:c,historyModalOpen:B,activeConv:U,isRefreshingHistory:ld,ides:m,handleRefreshHistory:dd});const ud=i.useMemo(()=>!U||!et(U)||Xe(U)?null:Es(U),[U]),{versionMismatchDaemons:fd,hasRequiredVersionDaemons:vo,appVersion:md,versionBannerDismissed:pd,setVersionBannerDismissed:hd,upgradingDaemons:xd,handleBannerUpgrade:bd}=nx({ides:m,sendDaemonCommand:e}),wo=i.useCallback(Ve=>{Z(Ve),Q(Ve)},[Q,Z]),gd=i.useCallback(Ve=>{le(Ve)},[le]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[s.jsx(bp,{terminalBackend:se,isStandalone:xe,machineLabel:ie,machineKey:re}),(!pd||vo)&&s.jsx(eg,{daemons:fd,targetVersion:md,required:vo,upgradingDaemons:xd,onUpgrade:bd,onDismiss:()=>hd(!0)}),s.jsx(Gb,{showMobileChatMode:br,isMobile:z,activeConv:U,wsStatus:v,isConnected:A,onOpenHistory:Ve=>{Ve&&Je(Ve),oe()},onOpenRemote:ft,onStopCli:je,activeCliViewMode:ud,onSetActiveCliViewMode:cd,mobileChatConversations:ed,ides:m,actionLogs:be,sendDaemonCommand:e,setActionLogs:X,setCliViewModeOverrides:ge,isStandalone:xe,initialDataLoaded:y,userName:p.userName,requestedMobileTabKey:Ne,onRequestedMobileTabConsumed:De,requestedMachineId:f,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:u,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:Ge,isSplitMode:tt,numGroups:qe,groupSizes:E,groupedConvs:F,clearedTabs:ee,focusedGroup:K,focusGroup:S,moveTabToGroup:V,splitTabRelative:_,closeGroup:L,handleResizeStart:G,groupActiveTabIds:O,setGroupActiveTab:P,groupTabOrders:C,setGroupTabOrder:W,toggleHiddenTab:Ve=>ke(Ae.get(Ve)||{tabKey:Ve}),visibleConversations:He,hiddenConversations:td,requestedDesktopTabKey:_e,onRequestedDesktopTabConsumed:De,onDesktopActiveTabChange:Me,onRequestScrollToBottom:ne,onHideConversation:gd,onShowHiddenConversation:wo,onShowAllHiddenConversations:Ce,scrollToBottomRequest:ve,machineEntries:we,layoutProfile:T,onBrowseMachineDirectory:rd,onSaveMachineWorkspace:nd,onLaunchMachineIde:ad,onLaunchMachineProvider:od,onListMachineSavedSessions:id,notifications:Qe,notificationUnreadCount:lt,liveSessionInboxState:Ue,onMarkNotificationRead:dt,onMarkNotificationUnread:ut,onDeleteNotification:Te}),s.jsx("style",{children:`
68
68
  body { overflow: hidden; overscroll-behavior: none; }
69
- `}),s.jsx(Qb,{historyModal:{open:B,targetConv:Ke,ides:m,isCreatingChat:$e,isRefreshingHistory:Le?!1:nt,savedSessions:pr,savedHistoryFilters:hr,missingWorkspaceResumePath:ql||null,onSavedHistoryFiltersChange:xr,isSavedSessionsLoading:Yl,isResumingSavedSessionId:Xl,onClose:pe,onNewChat:ct,onSwitchSession:jt,onRefreshHistory:Le?Jl:Vt,onResumeSavedSession:Ql},remoteDialog:{conversation:Be,ideEntry:_e,ides:m,connectionStates:g,actionLogs:be,sendDaemonCommand:e,setActionLogs:X,isStandalone:xe,userName:p.userName,onOpenHistory:Ve=>{Ve&&Je(Ve),oe()},onConversationChange:Je,onClose:pt},cliStopDialog:{open:ht,targetConv:me,onCancel:wt,onStopNow:async()=>{await bt("hard")},onSaveAndStop:async()=>{await bt("save")}},connectionBanner:{wsStatus:v,showReconnected:M,loginUrl:p.connectionLoginUrl,onReconnect:p.retryServerConnection},toastOverlay:{toasts:b,onDismiss:Ve=>h(It=>It.filter(Bs=>Bs.id!==Ve)),onClick:Ve=>{if(Ve.targetKey){const It=Ne(Ve.targetKey);It&&(le(It.tabKey,Ze),wo(It),ne(It.tabKey,"toast-open"))}}},onboarding:{open:j,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}x(!1)}}})]})}function ng({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[o,c]=i.useState([]),[l,d]=i.useState(null),[f,u]=i.useState(null),[p,m]=i.useState(!1),[y,N]=i.useState(null),[h,j]=i.useState(!1),[x,b]=i.useState(""),v=i.useRef(null),A=i.useCallback(E=>{v.current=E},[]),g=i.useCallback((E,$,F=!1)=>{c(J=>[...J.slice(-100),{timestamp:Date.now(),level:E,message:$}]),setTimeout(()=>{var J;return(J=a.current)==null?void 0:J.scrollIntoView({behavior:"smooth"})},100),F&&rt.showToast($,E==="error"||E==="warn"?"warning":"success")},[a]),M=i.useCallback(E=>{const $=E instanceof Error?E.message:String(E||"");return $.includes("P2P command timeout")||$.includes("P2P not connected")||$.includes("P2P not available")},[]),T=i.useCallback(async(E,$)=>{var F;if(!e||l)return!1;d(E),g("info",`Launching ${at(E)}${$!=null&&$.workspace?` in ${$.workspace}`:""}...`);try{const J={ideType:E,enableCdp:!0};(F=$==null?void 0:$.workspace)!=null&&F.trim()?J.workspace=$.workspace.trim():$!=null&&$.useDefaultWorkspace&&(J.useDefaultWorkspace=!0);const he=await r(e,"launch_ide",J);return g(he!=null&&he.success?"info":"error",he!=null&&he.success?`${at(E)} launched`:`Failed: ${he==null?void 0:he.error}`,!0),!!(he!=null&&he.success)}catch(J){return g("error",`Launch error: ${J.message}`,!0),!1}finally{d(null)}},[e,l,g,r]),k=i.useCallback(async E=>{if(!e)return{success:!1};const{cliType:$,dir:F,workspaceId:J,useDefaultWorkspace:he,useHome:le,argsStr:te,model:ye,resumeSessionId:fe}=E;if(!$)return g("warn","Select a CLI or ACP provider first",!0),{success:!1};const be=te?te.split(/\s+/).filter(Boolean):void 0,X=(F==null?void 0:F.trim())||(J?"(saved id)":he?"(default workspace)":le?"(home)":"");g("info",`Launching ${$}${X?` in ${X}`:""}${ye?` (model: ${ye})`:""}...`),u($);try{const ae={cliType:$,cliArgs:be,initialModel:ye||void 0};F!=null&&F.trim()?ae.dir=F.trim():J?ae.workspaceId=J:he?ae.useDefaultWorkspace=!0:le&&(ae.useHome=!0),fe&&(ae.resumeSessionId=fe);const ge=await r(e,"launch_cli",ae),ee=(ge==null?void 0:ge.result)||ge;return ge!=null&&ge.success?(g("info",`${$} launched`,!0),(ee==null?void 0:ee.launchSource)==="home"?g("info","📂 Running in home directory (explicit choice)"):(ee==null?void 0:ee.launchSource)==="defaultWorkspace"&&g("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ee==null?void 0:ee.sessionId}):(g("error",`Failed: ${(ge==null?void 0:ge.error)||(ee==null?void 0:ee.error)}`,!0),(ge==null?void 0:ge.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&N({cliType:$,argsStr:te,model:ye}),{success:!1,sessionId:ee==null?void 0:ee.sessionId})}catch(ae){return M(ae)?(g("warn",`${$} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(g("error",`Launch error: ${ae.message}`,!0),{success:!1})}finally{u(null)}},[e,g,M,r]),w=i.useCallback(async(E,$,F,J)=>e?E?$.trim()?k({cliType:E,dir:$,argsStr:F,model:J}):(N({cliType:E,argsStr:F,model:J}),{success:!1}):(g("warn","Select a provider",!0),{success:!1}):{success:!1},[e,g,k]),K=i.useCallback(async(E,$,F)=>{if(e&&window.confirm(`Stop ${E}?
70
- This will terminate the process.`))try{const J=await r(e,"stop_cli",{cliType:E,dir:$,targetSessionId:F});J!=null&&J.success?g("info",`${E} stopped`,!0):g("error",`Stop failed: ${(J==null?void 0:J.error)||"Unknown error"}`,!0)}catch(J){g("error",`Stop failed: ${J.message}`,!0)}},[e,g,r]),R=i.useCallback(async E=>{try{await r(E.daemonId,"restart_ide",{ideType:E.type}),g("info",`${at(E.type)} restart initiated`,!0)}catch($){g("error",`Restart failed: ${$.message}`,!0)}},[g,r]),S=i.useCallback(async E=>{if(window.confirm(`Stop ${at(E.type)}?
71
- This will disconnect CDP and optionally kill the process.`))try{const $=await r(E.daemonId,"stop_ide",{ideType:E.type,killProcess:!0});$!=null&&$.success?g("info",`${at(E.type)} stopped`,!0):g("error",`Stop failed: ${($==null?void 0:$.error)||"Unknown error"}`,!0)}catch($){g("error",`Stop failed: ${$.message}`,!0)}},[g,r]),O=i.useCallback(async()=>{if(e)try{const E=await r(e,"detect_ides",{});g("info",`Found ${((E==null?void 0:E.result)||[]).length} IDE(s)`,!0)}catch(E){g("error",`Detection failed: ${E.message}`,!0)}},[e,g,r]),U=i.useCallback(async E=>{if(!e||!E.trim())return!1;m(!0);try{const $=await r(e,"workspace_add",{path:E.trim()});return $!=null&&$.success?(g("info",`Workspace added: ${E.trim()}`),!0):(g("error",($==null?void 0:$.error)||"workspace_add failed"),!1)}catch($){return g("error",$.message),!1}finally{m(!1)}},[e,g,r]),P=i.useCallback(async E=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){m(!0);try{const $=await r(e,"workspace_remove",{id:E});$!=null&&$.success?g("info","Workspace removed",!0):g("error",($==null?void 0:$.error)||"workspace_remove failed",!0)}catch($){g("error",$.message,!0)}finally{m(!1)}}},[e,g,r]),C=i.useCallback(async E=>{var $;if(e){m(!0);try{const F=await r(e,"workspace_set_default",E===null?{clear:!0}:{id:E});if(F!=null&&F.success){g("info",E?"Default workspace updated":"Default workspace cleared",!0);const J=typeof F.defaultWorkspacePath=="string"?F.defaultWorkspacePath:"";J&&(($=v.current)==null||$.call(v,J))}else g("error",(F==null?void 0:F.error)||"workspace_set_default failed",!0)}catch(F){g("error",F.message,!0)}finally{m(!1)}}},[e,g,r]),I=i.useCallback(async E=>{var F;if(!e||!E.trim())return;const $=E.trim();m(!0);try{const J=await r(e,"workspace_set_default",{path:$});J!=null&&J.success?(g("info","Default workspace set from history"),(F=v.current)==null||F.call(v,$)):g("error",(J==null?void 0:J.error)||"Could not set default (path missing on disk?)")}catch(J){g("error",J.message)}finally{m(!1)}},[e,g,r]),W=i.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:x}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:x})}catch(E){g("warn",`Live nickname updated, but account sync failed: ${E.message}`)}g("info",`Nickname set to "${x||"(cleared)"}"`),j(!1)}catch(E){g("error",`Failed: ${E.message}`)}},[e,x,t,g,n,r]);return{logs:o,launchingIde:l,launchingAgentType:f,workspaceBusy:p,launchPick:y,setLaunchPick:N,editingNickname:h,setEditingNickname:j,nicknameInput:x,setNicknameInput:b,addLog:g,handleLaunchIde:T,runLaunchCliCore:k,handleLaunchCli:w,handleStopCli:K,handleRestartIde:R,handleStopIde:S,handleDetectIdes:O,handleWorkspaceAdd:U,handleWorkspaceRemove:P,handleWorkspaceSetDefault:C,handleWorkspaceResumePath:I,handleSaveNickname:W,setOnDefaultWorkspaceChanged:A}}function ag({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:c}){var R;const{workspaceBusy:l,handleWorkspaceAdd:d,handleWorkspaceRemove:f,handleWorkspaceSetDefault:u}=o,[p,m]=i.useState(!1),[y,N]=i.useState(""),[h,j]=i.useState([]),[x,b]=i.useState(!1),[v,A]=i.useState(""),g=i.useCallback(async S=>{b(!0),A("");try{const O=await xn(c,e,S);N(O.path),j(O.directories)}catch(O){A(O instanceof Error?O.message:"Could not load folder")}finally{b(!1)}},[e,c]),M=i.useCallback(()=>{m(!0);const S=[...r.map(U=>U.workspace),...n.map(U=>U.workspace),...a.map(U=>U.workspace)],O=hn(t.platform,pn(S,t.defaultWorkspacePath,(t.workspaces||[]).map(U=>U.path)));g(O)},[a,n,r,g,t.defaultWorkspacePath,t.platform,t.workspaces]),T=typeof t.uptime=="number"||typeof t.freeMem=="number"||typeof t.availableMem=="number"||Array.isArray(t.loadavg)&&t.loadavg.length>0,k=t.availableMem??t.freeMem??t.totalMem,w=T&&t.totalMem>0?Math.min(100,Math.max(0,Math.round((t.totalMem-k)/t.totalMem*100))):0,K=((R=t.loadavg)==null?void 0:R[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(vr,{icon:s.jsx(Qi,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?Qu(t.uptime):"Waiting…"}),s.jsx(vr,{icon:s.jsx(Tt,{size:16}),label:"IDEs",value:`${r.length}`}),s.jsx(vr,{icon:s.jsx(Ea,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(vr,{icon:s.jsx(iu,{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(Po,{value:T?Math.min(Math.round(K/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:T?`${K.toFixed(2)} avg / ${t.cpus} cores`:"Polled from machine page"}),s.jsx(Po,{value:w,max:100,label:"Memory",color:"#3b82f6",detail:T?`${Nn(t.totalMem-k)} / ${Nn(t.totalMem)}${t.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Nn(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(Cs,{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:l,value:t.defaultWorkspaceId||"",onChange:S=>void u(S.target.value===""?null:S.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),(t.workspaces||[]).map(S=>s.jsx("option",{value:S.id,children:S.label||S.path},S.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:l,onClick:M,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(S=>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:[S.id===t.defaultWorkspaceId&&s.jsx("span",{className:"text-[10px]",children:"⭐"}),s.jsx("span",{className:"font-medium text-text-primary truncate",children:un(S.path,S.label)})]}),s.jsx("div",{className:"font-mono truncate text-[10px]",title:S.path,children:S.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void f(S.id),children:"Remove"})]},S.id))})]}),p&&s.jsx(bn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:y,directories:h,busy:x,error:v,confirmLabel:"Add workspace",onClose:()=>m(!1),onNavigate:S=>{g(S)},onConfirm:S=>{(async()=>{if(!S)return;await d(S)&&m(!1)})()}})]})}function og(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 ig(e,t,r){const n=[];for(const[a,o]of Object.entries(e.settings)){const c=r!=null&&r.filterSchema?r.filterSchema(o):o;if(c.length===0)continue;const l=t.find(d=>d.type===a);n.push({type:a,displayName:(l==null?void 0:l.displayName)||a,icon:(l==null?void 0:l.icon)||"",category:(l==null?void 0:l.category)||"unknown",schema:c,values:e.values[a]||{}})}return n}function Yn(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 Si(e){if(!e||typeof e!="object")return null;if(Yn(e))return e;const t=e,r=t.result;return Yn(r)?r:Yn(t.sourceConfig)?t.sourceConfig:null}function cg(e){const t=e.trim();return t||null}const Ni=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],lg=[{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 dg({machineId:e,provider:t,sendDaemonCommand:r,onClose:n}){const[a,o]=i.useState("config"),[c,l]=i.useState("codex-cli"),[d,f]=i.useState([]),[u,p]=i.useState(""),[m,y]=i.useState([]),[N,h]=i.useState(""),j=i.useRef(null),x=i.useRef(null),b=k=>{f(w=>w.includes(k)?w.filter(K=>K!==k):[...w,k])},v=()=>f([...Ni]),A=()=>f([]);i.useEffect(()=>{var k;(k=j.current)==null||k.scrollIntoView({behavior:"smooth"})},[m]),i.useEffect(()=>()=>{x.current&&clearInterval(x.current)},[]);const g=i.useCallback(()=>{x.current&&clearInterval(x.current),x.current=setInterval(async()=>{try{const k=await r(e,"provider_auto_fix_status",{providerType:t.type});(k==null?void 0:k.running)===!1&&a==="running"&&(o("done"),y(w=>[...w,`
69
+ `}),s.jsx(Zb,{historyModal:{open:B,targetConv:Ke,ides:m,isCreatingChat:$e,isRefreshingHistory:Ie?!1:nt,savedSessions:pr,savedHistoryFilters:hr,missingWorkspaceResumePath:Yl||null,onSavedHistoryFiltersChange:xr,isSavedSessionsLoading:Xl,isResumingSavedSessionId:Jl,onClose:pe,onNewChat:ct,onSwitchSession:jt,onRefreshHistory:Ie?Ql:Vt,onResumeSavedSession:Zl},remoteDialog:{conversation:Be,ideEntry:Re,ides:m,connectionStates:g,actionLogs:be,sendDaemonCommand:e,setActionLogs:X,isStandalone:xe,userName:p.userName,onOpenHistory:Ve=>{Ve&&Je(Ve),oe()},onConversationChange:Je,onClose:pt},cliStopDialog:{open:ht,targetConv:me,onCancel:wt,onStopNow:async()=>{await bt("hard")},onSaveAndStop:async()=>{await bt("save")}},connectionBanner:{wsStatus:v,showReconnected:M,loginUrl:p.connectionLoginUrl,onReconnect:p.retryServerConnection},toastOverlay:{toasts:b,onDismiss:Ve=>h(It=>It.filter(Bs=>Bs.id!==Ve)),onClick:Ve=>{if(Ve.targetKey){const It=Se(Ve.targetKey);It&&(ce(It.tabKey,Ze),wo(It),ne(It.tabKey,"toast-open"))}}},onboarding:{open:j,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}x(!1)}}})]})}function ag({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[o,c]=i.useState([]),[l,d]=i.useState(null),[f,u]=i.useState(null),[p,m]=i.useState(!1),[y,N]=i.useState(null),[h,j]=i.useState(!1),[x,b]=i.useState(""),v=i.useRef(null),A=i.useCallback(E=>{v.current=E},[]),g=i.useCallback((E,$,z=!1)=>{c(J=>[...J.slice(-100),{timestamp:Date.now(),level:E,message:$}]),setTimeout(()=>{var J;return(J=a.current)==null?void 0:J.scrollIntoView({behavior:"smooth"})},100),z&&rt.showToast($,E==="error"||E==="warn"?"warning":"success")},[a]),M=i.useCallback(E=>{const $=E instanceof Error?E.message:String(E||"");return $.includes("P2P command timeout")||$.includes("P2P not connected")||$.includes("P2P not available")},[]),T=i.useCallback(async(E,$)=>{var z;if(!e||l)return!1;d(E),g("info",`Launching ${at(E)}${$!=null&&$.workspace?` in ${$.workspace}`:""}...`);try{const J={ideType:E,enableCdp:!0};(z=$==null?void 0:$.workspace)!=null&&z.trim()?J.workspace=$.workspace.trim():$!=null&&$.useDefaultWorkspace&&(J.useDefaultWorkspace=!0);const he=await r(e,"launch_ide",J);return g(he!=null&&he.success?"info":"error",he!=null&&he.success?`${at(E)} launched`:`Failed: ${he==null?void 0:he.error}`,!0),!!(he!=null&&he.success)}catch(J){return g("error",`Launch error: ${J.message}`,!0),!1}finally{d(null)}},[e,l,g,r]),k=i.useCallback(async E=>{if(!e)return{success:!1};const{cliType:$,dir:z,workspaceId:J,useDefaultWorkspace:he,useHome:ce,argsStr:te,model:ye,resumeSessionId:fe}=E;if(!$)return g("warn","Select a CLI or ACP provider first",!0),{success:!1};const be=te?te.split(/\s+/).filter(Boolean):void 0,X=(z==null?void 0:z.trim())||(J?"(saved id)":he?"(default workspace)":ce?"(home)":"");g("info",`Launching ${$}${X?` in ${X}`:""}${ye?` (model: ${ye})`:""}...`),u($);try{const ae={cliType:$,cliArgs:be,initialModel:ye||void 0};z!=null&&z.trim()?ae.dir=z.trim():J?ae.workspaceId=J:he?ae.useDefaultWorkspace=!0:ce&&(ae.useHome=!0),fe&&(ae.resumeSessionId=fe);const ge=await r(e,"launch_cli",ae),ee=(ge==null?void 0:ge.result)||ge;return ge!=null&&ge.success?(g("info",`${$} launched`,!0),(ee==null?void 0:ee.launchSource)==="home"?g("info","📂 Running in home directory (explicit choice)"):(ee==null?void 0:ee.launchSource)==="defaultWorkspace"&&g("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ee==null?void 0:ee.sessionId}):(g("error",`Failed: ${(ge==null?void 0:ge.error)||(ee==null?void 0:ee.error)}`,!0),(ge==null?void 0:ge.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&N({cliType:$,argsStr:te,model:ye}),{success:!1,sessionId:ee==null?void 0:ee.sessionId})}catch(ae){return M(ae)?(g("warn",`${$} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(g("error",`Launch error: ${ae.message}`,!0),{success:!1})}finally{u(null)}},[e,g,M,r]),w=i.useCallback(async(E,$,z,J)=>e?E?$.trim()?k({cliType:E,dir:$,argsStr:z,model:J}):(N({cliType:E,argsStr:z,model:J}),{success:!1}):(g("warn","Select a provider",!0),{success:!1}):{success:!1},[e,g,k]),K=i.useCallback(async(E,$,z)=>{if(e&&window.confirm(`Stop ${E}?
70
+ This will terminate the process.`))try{const J=await r(e,"stop_cli",{cliType:E,dir:$,targetSessionId:z});J!=null&&J.success?g("info",`${E} stopped`,!0):g("error",`Stop failed: ${(J==null?void 0:J.error)||"Unknown error"}`,!0)}catch(J){g("error",`Stop failed: ${J.message}`,!0)}},[e,g,r]),R=i.useCallback(async E=>{try{await r(E.daemonId,"restart_ide",{ideType:E.type}),g("info",`${at(E.type)} restart initiated`,!0)}catch($){g("error",`Restart failed: ${$.message}`,!0)}},[g,r]),S=i.useCallback(async E=>{if(window.confirm(`Stop ${at(E.type)}?
71
+ This will disconnect CDP and optionally kill the process.`))try{const $=await r(E.daemonId,"stop_ide",{ideType:E.type,killProcess:!0});$!=null&&$.success?g("info",`${at(E.type)} stopped`,!0):g("error",`Stop failed: ${($==null?void 0:$.error)||"Unknown error"}`,!0)}catch($){g("error",`Stop failed: ${$.message}`,!0)}},[g,r]),O=i.useCallback(async()=>{if(e)try{const E=await r(e,"detect_ides",{});g("info",`Found ${((E==null?void 0:E.result)||[]).length} IDE(s)`,!0)}catch(E){g("error",`Detection failed: ${E.message}`,!0)}},[e,g,r]),H=i.useCallback(async E=>{if(!e||!E.trim())return!1;m(!0);try{const $=await r(e,"workspace_add",{path:E.trim()});return $!=null&&$.success?(g("info",`Workspace added: ${E.trim()}`),!0):(g("error",($==null?void 0:$.error)||"workspace_add failed"),!1)}catch($){return g("error",$.message),!1}finally{m(!1)}},[e,g,r]),P=i.useCallback(async E=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){m(!0);try{const $=await r(e,"workspace_remove",{id:E});$!=null&&$.success?g("info","Workspace removed",!0):g("error",($==null?void 0:$.error)||"workspace_remove failed",!0)}catch($){g("error",$.message,!0)}finally{m(!1)}}},[e,g,r]),C=i.useCallback(async E=>{var $;if(e){m(!0);try{const z=await r(e,"workspace_set_default",E===null?{clear:!0}:{id:E});if(z!=null&&z.success){g("info",E?"Default workspace updated":"Default workspace cleared",!0);const J=typeof z.defaultWorkspacePath=="string"?z.defaultWorkspacePath:"";J&&(($=v.current)==null||$.call(v,J))}else g("error",(z==null?void 0:z.error)||"workspace_set_default failed",!0)}catch(z){g("error",z.message,!0)}finally{m(!1)}}},[e,g,r]),I=i.useCallback(async E=>{var z;if(!e||!E.trim())return;const $=E.trim();m(!0);try{const J=await r(e,"workspace_set_default",{path:$});J!=null&&J.success?(g("info","Default workspace set from history"),(z=v.current)==null||z.call(v,$)):g("error",(J==null?void 0:J.error)||"Could not set default (path missing on disk?)")}catch(J){g("error",J.message)}finally{m(!1)}},[e,g,r]),W=i.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:x}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:x})}catch(E){g("warn",`Live nickname updated, but account sync failed: ${E.message}`)}g("info",`Nickname set to "${x||"(cleared)"}"`),j(!1)}catch(E){g("error",`Failed: ${E.message}`)}},[e,x,t,g,n,r]);return{logs:o,launchingIde:l,launchingAgentType:f,workspaceBusy:p,launchPick:y,setLaunchPick:N,editingNickname:h,setEditingNickname:j,nicknameInput:x,setNicknameInput:b,addLog:g,handleLaunchIde:T,runLaunchCliCore:k,handleLaunchCli:w,handleStopCli:K,handleRestartIde:R,handleStopIde:S,handleDetectIdes:O,handleWorkspaceAdd:H,handleWorkspaceRemove:P,handleWorkspaceSetDefault:C,handleWorkspaceResumePath:I,handleSaveNickname:W,setOnDefaultWorkspaceChanged:A}}function og({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:c}){var R;const{workspaceBusy:l,handleWorkspaceAdd:d,handleWorkspaceRemove:f,handleWorkspaceSetDefault:u}=o,[p,m]=i.useState(!1),[y,N]=i.useState(""),[h,j]=i.useState([]),[x,b]=i.useState(!1),[v,A]=i.useState(""),g=i.useCallback(async S=>{b(!0),A("");try{const O=await xn(c,e,S);N(O.path),j(O.directories)}catch(O){A(O instanceof Error?O.message:"Could not load folder")}finally{b(!1)}},[e,c]),M=i.useCallback(()=>{m(!0);const S=[...r.map(H=>H.workspace),...n.map(H=>H.workspace),...a.map(H=>H.workspace)],O=hn(t.platform,pn(S,t.defaultWorkspacePath,(t.workspaces||[]).map(H=>H.path)));g(O)},[a,n,r,g,t.defaultWorkspacePath,t.platform,t.workspaces]),T=typeof t.uptime=="number"||typeof t.freeMem=="number"||typeof t.availableMem=="number"||Array.isArray(t.loadavg)&&t.loadavg.length>0,k=t.availableMem??t.freeMem??t.totalMem,w=T&&t.totalMem>0?Math.min(100,Math.max(0,Math.round((t.totalMem-k)/t.totalMem*100))):0,K=((R=t.loadavg)==null?void 0:R[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(vr,{icon:s.jsx(Qi,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?Zu(t.uptime):"Waiting…"}),s.jsx(vr,{icon:s.jsx(Tt,{size:16}),label:"IDEs",value:`${r.length}`}),s.jsx(vr,{icon:s.jsx(Ea,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(vr,{icon:s.jsx(cu,{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(Po,{value:T?Math.min(Math.round(K/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:T?`${K.toFixed(2)} avg / ${t.cpus} cores`:"Polled from machine page"}),s.jsx(Po,{value:w,max:100,label:"Memory",color:"#3b82f6",detail:T?`${Nn(t.totalMem-k)} / ${Nn(t.totalMem)}${t.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Nn(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(Cs,{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:l,value:t.defaultWorkspaceId||"",onChange:S=>void u(S.target.value===""?null:S.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),(t.workspaces||[]).map(S=>s.jsx("option",{value:S.id,children:S.label||S.path},S.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:l,onClick:M,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(S=>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:[S.id===t.defaultWorkspaceId&&s.jsx("span",{className:"text-[10px]",children:"⭐"}),s.jsx("span",{className:"font-medium text-text-primary truncate",children:un(S.path,S.label)})]}),s.jsx("div",{className:"font-mono truncate text-[10px]",title:S.path,children:S.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void f(S.id),children:"Remove"})]},S.id))})]}),p&&s.jsx(bn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:y,directories:h,busy:x,error:v,confirmLabel:"Add workspace",onClose:()=>m(!1),onNavigate:S=>{g(S)},onConfirm:S=>{(async()=>{if(!S)return;await d(S)&&m(!1)})()}})]})}function ig(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 cg(e,t,r){const n=[];for(const[a,o]of Object.entries(e.settings)){const c=r!=null&&r.filterSchema?r.filterSchema(o):o;if(c.length===0)continue;const l=t.find(d=>d.type===a);n.push({type:a,displayName:(l==null?void 0:l.displayName)||a,icon:(l==null?void 0:l.icon)||"",category:(l==null?void 0:l.category)||"unknown",schema:c,values:e.values[a]||{}})}return n}function Yn(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 Si(e){if(!e||typeof e!="object")return null;if(Yn(e))return e;const t=e,r=t.result;return Yn(r)?r:Yn(t.sourceConfig)?t.sourceConfig:null}function lg(e){const t=e.trim();return t||null}const Ni=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],dg=[{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 ug({machineId:e,provider:t,sendDaemonCommand:r,onClose:n}){const[a,o]=i.useState("config"),[c,l]=i.useState("codex-cli"),[d,f]=i.useState([]),[u,p]=i.useState(""),[m,y]=i.useState([]),[N,h]=i.useState(""),j=i.useRef(null),x=i.useRef(null),b=k=>{f(w=>w.includes(k)?w.filter(K=>K!==k):[...w,k])},v=()=>f([...Ni]),A=()=>f([]);i.useEffect(()=>{var k;(k=j.current)==null||k.scrollIntoView({behavior:"smooth"})},[m]),i.useEffect(()=>()=>{x.current&&clearInterval(x.current)},[]);const g=i.useCallback(()=>{x.current&&clearInterval(x.current),x.current=setInterval(async()=>{try{const k=await r(e,"provider_auto_fix_status",{providerType:t.type});(k==null?void 0:k.running)===!1&&a==="running"&&(o("done"),y(w=>[...w,`
72
72
  ✅ Auto-fix completed!`]),x.current&&clearInterval(x.current))}catch{}},3e3)},[e,t.type,r,a]),M=async()=>{if(d.length!==0){o("running"),y(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${d.join(", ")}`,u?`💬 Comment: ${u}`:"",""]),h("");try{const k=await r(e,"provider_auto_fix",{providerType:t.type,functions:d,agent:c,...u?{comment:u}:{}});k!=null&&k.success&&(k!=null&&k.started||k!=null&&k.running)?(y(w=>[...w,"✅ Agent started. Monitoring progress..."]),g()):(o("error"),h((k==null?void 0:k.error)||"Failed to start auto-fix"))}catch(k){o("error"),h((k==null?void 0:k.message)||"Connection failed")}}},T=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:t.type}),y(k=>[...k,`
73
- ⚠️ Auto-fix cancelled.`]),o("done"),x.current&&clearInterval(x.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:k=>k.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:lg.map(k=>s.jsxs("button",{onClick:()=>l(k.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===k.value?k.color+"66":"var(--border-subtle)",background:c===k.value?k.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===k.value?k.color:"var(--text-primary)"},children:k.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:k.desc})]},k.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:v,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:A,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Ni.map(k=>s.jsxs("button",{onClick:()=>b(k),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:d.includes(k)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:d.includes(k)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:d.includes(k)?"#a78bfa":"var(--text-secondary)"},children:[d.includes(k)?"☑ ":"☐ ",k]},k))})]}),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:k=>p(k.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:[m.map((k,w)=>s.jsx("div",{className:k.startsWith("✅")?"text-green-400":"",style:k.startsWith("❌")||k.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:k},w)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:j})]}),N&&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:N})]})]}),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:M,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:T,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"),y([]),h("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function ug({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var g;const o=t.filter(M=>M.category==="ide"),[c,l]=i.useState(((g=o[0])==null?void 0:g.type)||""),[d,f]=i.useState(""),[u,p]=i.useState(""),[m,y]=i.useState(!1),[N,h]=i.useState(""),[j,x]=i.useState(!1),b=M=>{const T=M.toLowerCase().replace(/[^a-z0-9-]/g,"");f(T),(!u||u===v(d))&&p(v(T))},v=M=>M.split("-").map(T=>T.charAt(0).toUpperCase()+T.slice(1)).join(" "),A=async()=>{if(!(!d||!u||!c)){y(!0),h("");try{const M=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:c});M!=null&&M.success||M!=null&&M.created?(x(!0),a==null||a(d)):h((M==null?void 0:M.error)||"Failed to create provider")}catch(M){h((M==null?void 0:M.message)||"Connection failed")}y(!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:M=>M.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:j?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(M=>s.jsxs("button",{onClick:()=>l(M.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===M.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===M.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:M.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===M.type?"#a78bfa":"var(--text-secondary)"},children:M.displayName})]},M.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:M=>b(M.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:M=>p(M.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"})]}),N&&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:N})]})}),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:j?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:A,disabled:!d||!u||m,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||m?.4:1},children:m?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Ci(e){return e==="cli"||e==="acp"}function fg(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 mg(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 Ti(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 pg({machineId:e,providers:t,sendDaemonCommand:r}){var U;const[n,a]=i.useState([]),[o,c]=i.useState(!1),[l,d]=i.useState(null),[f,u]=i.useState("all"),[p,m]=i.useState(null),[y,N]=i.useState(!1),[h,j]=i.useState(null),[x,b]=i.useState("normal"),[v,A]=i.useState(""),[g,M]=i.useState(!1),T=i.useCallback(async()=>{if(e)try{const P=await r(e,"get_provider_source_config",{}),C=Si(P);C&&(j(C),b(C.sourceMode),A(C.explicitProviderDir||""))}catch{}},[e,r]),k=i.useCallback(async()=>{if(e){c(!0);try{const P=await r(e,"get_provider_settings",{}),C=og(P);if(C){const I=ig(C,t,{filterSchema:W=>W.filter(E=>E.key!=="enabled")});I.sort((W,E)=>W.category.localeCompare(E.category)||W.displayName.localeCompare(E.displayName)),a(I)}}catch{}c(!1)}},[e,t,r]);i.useEffect(()=>{n.length===0&&k(),h||T()},[]);const w=async(P,C,I)=>{d(`${P}.${C}`),a(W=>W.map(E=>E.type===P?{...E,values:{...E.values,[C]:I}}:E));try{const W=await r(e,"set_provider_setting",{providerType:P,key:C,value:I});W!=null&&W.success||k()}catch{k()}d(null)},K=async(P,C)=>{await w(P,"enabled",C),await k()},R=async P=>{d(`${P}.detect`);try{await r(e,"detect_provider",{providerType:P})}finally{await k(),d(null)}},S=async P=>{await w(P,"executablePath",""),await w(P,"executableArgs",""),await k()},O=async()=>{M(!0);try{const P=await r(e,"set_provider_source_config",{providerSourceMode:x,providerDir:cg(v)}),C=Si(P);C?(j(C),b(C.sourceMode),A(C.explicitProviderDir||"")):await T(),await k()}catch{await T()}M(!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(P=>s.jsx("button",{onClick:()=>u(P),className:`machine-btn text-[10px] px-2 py-0.5 ${f===P?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:P.toUpperCase()},P))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>N(!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:k,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:T,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:x,onChange:P=>b(P.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:v,onChange:P=>A(P.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void O(),disabled:g,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:g?"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:"})," ",(h==null?void 0:h.userDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(h==null?void 0:h.upstreamDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((U=h==null?void 0:h.providerRoots)==null?void 0:U.join(" → "))||"loading…"]})]})]}),f!=="all"&&n.filter(P=>P.category===f).length>1&&(()=>{const P=n.filter(E=>E.category===f),C=new Map;for(const E of P)for(const $ of E.schema){if($.type!=="boolean")continue;const F=C.get($.key),J=!!(E.values[$.key]??$.default);F?(F.onCount+=J?1:0,F.total+=1):C.set($.key,{label:$.label||$.key,onCount:J?1:0,total:1})}const I=[...C.entries()].filter(([,E])=>E.total===P.length);if(I.length===0)return null;const W=async(E,$)=>{for(const F of P)await w(F.type,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 ",f.toUpperCase()," providers (",P.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:I.map(([E,$])=>{const F=$.onCount===$.total,J=$.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:$.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",$.onCount,"/",$.total,")"]}),s.jsx("button",{onClick:()=>void W(E,!0),disabled:F,className:`machine-btn text-[9px] px-1.5 py-px ${F?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),s.jsx("button",{onClick:()=>void W(E,!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"})]},E)})})]})})(),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(P=>f==="all"||P.category===f).map(P=>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:P.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:P.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:P.category==="acp"?"rgba(139,92,246,0.08)":P.category==="cli"?"rgba(59,130,246,0.08)":P.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:P.category==="acp"?"#a78bfa":P.category==="cli"?"#60a5fa":P.category==="ide"?"#86efac":"var(--status-warning)"},children:P.category}),Ci(P.category)&&(()=>{const C=t.find(E=>E.type===P.type),I=(C==null?void 0:C.enabled)===!0||P.values.enabled===!0,W=(C==null?void 0:C.machineStatus)||(I?"enabled_unchecked":"disabled");return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${mg(W)}`,children:fg(W)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void K(P.type,!I),disabled:l===`${P.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${I?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:I?"Disable":"Enable"}),s.jsx("button",{onClick:()=>void R(P.type),disabled:!I||l===`${P.type}.detect`,title:I?"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 ${I?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),s.jsx("button",{onClick:()=>void S(P.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),P.category==="ide"&&s.jsx("button",{onClick:()=>m(t.find(C=>C.type===P.type)||{type:P.type,name:P.displayName,displayName:P.displayName,icon:P.icon,category:P.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"})]}),Ci(P.category)&&(()=>{const C=t.find(I=>I.type===P.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:"})," ",Ti(C==null?void 0:C.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",Ti(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:P.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,l===`${P.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(P.type,C.key,!(P.values[C.key]??C.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:P.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:P.values[C.key]??C.default?21:3}})}):C.type==="number"?s.jsx("input",{type:"number",value:Number(P.values[C.key]??C.default??0)||0,min:C.min,max:C.max,onChange:I=>{const W=parseInt(I.target.value)||0;C.min!==void 0&&W<C.min||C.max!==void 0&&W>C.max||w(P.type,C.key,W)},className:"machine-input w-20 text-center text-[11px]"}):C.type==="select"&&C.options?s.jsx("select",{value:String(P.values[C.key]??C.default??""),onChange:I=>w(P.type,C.key,I.target.value),className:"machine-input text-[11px]",children:C.options.map(I=>s.jsx("option",{value:I,children:I},I))}):s.jsx("input",{type:"text",value:String(P.values[C.key]??C.default??""),onBlur:I=>w(P.type,C.key,I.target.value),className:"machine-input w-[120px] text-[11px]"})})]},C.key))})]},P.type))}),p&&s.jsx(dg,{machineId:e,provider:p,sendDaemonCommand:r,onClose:()=>m(null)}),y&&s.jsx(ug,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>N(!1),onCreated:()=>{N(!1),k()}})]})}const hg=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function xg({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function bg(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function gg(e){return e.trim().toLowerCase()}function yn(e,t){const r=gg(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function xo(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function _s(e,t=220){const r=xo(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function yg(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 vg(e,t){return e.filter(r=>yn([r.level,r.message],t))}function Mi(e){return`${e.timestamp}:${e.level}:${e.message}`}function wg(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const c of e.entries)n.set(Mi(c),c);for(const c of t.entries)n.set(Mi(c),c);const a=Array.from(n.values()).sort((c,l)=>c.timestamp-l.timestamp).slice(-r),o=a.reduce((c,l)=>Math.max(c,Number(l.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 jg(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 kg(e,t){return e.split(`
74
- `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>yn([r],t))}function Sg(e,t){return e.filter(r=>yn([r.level,r.category,r.stage,r.interactionId,xo(r.payload)],t))}function Ng(e,t){return e.filter(r=>yn([r.kind,r.topic,r.interactionId,xo(r.payload)],t))}function Ai(e){return e==="warn"||e==="error"}function Cg({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=>Ai(a.level)).length+r.filter(a=>Ai(a.level)).length}}function Tg({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(`
73
+ ⚠️ Auto-fix cancelled.`]),o("done"),x.current&&clearInterval(x.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:k=>k.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:dg.map(k=>s.jsxs("button",{onClick:()=>l(k.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===k.value?k.color+"66":"var(--border-subtle)",background:c===k.value?k.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===k.value?k.color:"var(--text-primary)"},children:k.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:k.desc})]},k.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:v,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:A,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Ni.map(k=>s.jsxs("button",{onClick:()=>b(k),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:d.includes(k)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:d.includes(k)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:d.includes(k)?"#a78bfa":"var(--text-secondary)"},children:[d.includes(k)?"☑ ":"☐ ",k]},k))})]}),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:k=>p(k.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:[m.map((k,w)=>s.jsx("div",{className:k.startsWith("✅")?"text-green-400":"",style:k.startsWith("❌")||k.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:k},w)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:j})]}),N&&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:N})]})]}),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:M,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:T,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"),y([]),h("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function fg({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var g;const o=t.filter(M=>M.category==="ide"),[c,l]=i.useState(((g=o[0])==null?void 0:g.type)||""),[d,f]=i.useState(""),[u,p]=i.useState(""),[m,y]=i.useState(!1),[N,h]=i.useState(""),[j,x]=i.useState(!1),b=M=>{const T=M.toLowerCase().replace(/[^a-z0-9-]/g,"");f(T),(!u||u===v(d))&&p(v(T))},v=M=>M.split("-").map(T=>T.charAt(0).toUpperCase()+T.slice(1)).join(" "),A=async()=>{if(!(!d||!u||!c)){y(!0),h("");try{const M=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:c});M!=null&&M.success||M!=null&&M.created?(x(!0),a==null||a(d)):h((M==null?void 0:M.error)||"Failed to create provider")}catch(M){h((M==null?void 0:M.message)||"Connection failed")}y(!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:M=>M.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:j?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(M=>s.jsxs("button",{onClick:()=>l(M.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===M.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===M.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:M.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===M.type?"#a78bfa":"var(--text-secondary)"},children:M.displayName})]},M.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:M=>b(M.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:M=>p(M.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"})]}),N&&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:N})]})}),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:j?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:A,disabled:!d||!u||m,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||m?.4:1},children:m?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Ci(e){return e==="cli"||e==="acp"}function mg(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 pg(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 Ti(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 hg({machineId:e,providers:t,sendDaemonCommand:r}){var H;const[n,a]=i.useState([]),[o,c]=i.useState(!1),[l,d]=i.useState(null),[f,u]=i.useState("all"),[p,m]=i.useState(null),[y,N]=i.useState(!1),[h,j]=i.useState(null),[x,b]=i.useState("normal"),[v,A]=i.useState(""),[g,M]=i.useState(!1),T=i.useCallback(async()=>{if(e)try{const P=await r(e,"get_provider_source_config",{}),C=Si(P);C&&(j(C),b(C.sourceMode),A(C.explicitProviderDir||""))}catch{}},[e,r]),k=i.useCallback(async()=>{if(e){c(!0);try{const P=await r(e,"get_provider_settings",{}),C=ig(P);if(C){const I=cg(C,t,{filterSchema:W=>W.filter(E=>E.key!=="enabled")});I.sort((W,E)=>W.category.localeCompare(E.category)||W.displayName.localeCompare(E.displayName)),a(I)}}catch{}c(!1)}},[e,t,r]);i.useEffect(()=>{n.length===0&&k(),h||T()},[]);const w=async(P,C,I)=>{d(`${P}.${C}`),a(W=>W.map(E=>E.type===P?{...E,values:{...E.values,[C]:I}}:E));try{const W=await r(e,"set_provider_setting",{providerType:P,key:C,value:I});W!=null&&W.success||k()}catch{k()}d(null)},K=async(P,C)=>{await w(P,"enabled",C),await k()},R=async P=>{d(`${P}.detect`);try{await r(e,"detect_provider",{providerType:P})}finally{await k(),d(null)}},S=async P=>{await w(P,"executablePath",""),await w(P,"executableArgs",""),await k()},O=async()=>{M(!0);try{const P=await r(e,"set_provider_source_config",{providerSourceMode:x,providerDir:lg(v)}),C=Si(P);C?(j(C),b(C.sourceMode),A(C.explicitProviderDir||"")):await T(),await k()}catch{await T()}M(!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(P=>s.jsx("button",{onClick:()=>u(P),className:`machine-btn text-[10px] px-2 py-0.5 ${f===P?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:P.toUpperCase()},P))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>N(!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:k,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:T,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:x,onChange:P=>b(P.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:v,onChange:P=>A(P.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void O(),disabled:g,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:g?"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:"})," ",(h==null?void 0:h.userDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(h==null?void 0:h.upstreamDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((H=h==null?void 0:h.providerRoots)==null?void 0:H.join(" → "))||"loading…"]})]})]}),f!=="all"&&n.filter(P=>P.category===f).length>1&&(()=>{const P=n.filter(E=>E.category===f),C=new Map;for(const E of P)for(const $ of E.schema){if($.type!=="boolean")continue;const z=C.get($.key),J=!!(E.values[$.key]??$.default);z?(z.onCount+=J?1:0,z.total+=1):C.set($.key,{label:$.label||$.key,onCount:J?1:0,total:1})}const I=[...C.entries()].filter(([,E])=>E.total===P.length);if(I.length===0)return null;const W=async(E,$)=>{for(const z of P)await w(z.type,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 ",f.toUpperCase()," providers (",P.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:I.map(([E,$])=>{const z=$.onCount===$.total,J=$.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:$.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",$.onCount,"/",$.total,")"]}),s.jsx("button",{onClick:()=>void W(E,!0),disabled:z,className:`machine-btn text-[9px] px-1.5 py-px ${z?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),s.jsx("button",{onClick:()=>void W(E,!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"})]},E)})})]})})(),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(P=>f==="all"||P.category===f).map(P=>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:P.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:P.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:P.category==="acp"?"rgba(139,92,246,0.08)":P.category==="cli"?"rgba(59,130,246,0.08)":P.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:P.category==="acp"?"#a78bfa":P.category==="cli"?"#60a5fa":P.category==="ide"?"#86efac":"var(--status-warning)"},children:P.category}),Ci(P.category)&&(()=>{const C=t.find(E=>E.type===P.type),I=(C==null?void 0:C.enabled)===!0||P.values.enabled===!0,W=(C==null?void 0:C.machineStatus)||(I?"enabled_unchecked":"disabled");return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${pg(W)}`,children:mg(W)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void K(P.type,!I),disabled:l===`${P.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${I?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:I?"Disable":"Enable"}),s.jsx("button",{onClick:()=>void R(P.type),disabled:!I||l===`${P.type}.detect`,title:I?"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 ${I?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),s.jsx("button",{onClick:()=>void S(P.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),P.category==="ide"&&s.jsx("button",{onClick:()=>m(t.find(C=>C.type===P.type)||{type:P.type,name:P.displayName,displayName:P.displayName,icon:P.icon,category:P.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"})]}),Ci(P.category)&&(()=>{const C=t.find(I=>I.type===P.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:"})," ",Ti(C==null?void 0:C.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",Ti(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:P.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,l===`${P.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(P.type,C.key,!(P.values[C.key]??C.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:P.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:P.values[C.key]??C.default?21:3}})}):C.type==="number"?s.jsx("input",{type:"number",value:Number(P.values[C.key]??C.default??0)||0,min:C.min,max:C.max,onChange:I=>{const W=parseInt(I.target.value)||0;C.min!==void 0&&W<C.min||C.max!==void 0&&W>C.max||w(P.type,C.key,W)},className:"machine-input w-20 text-center text-[11px]"}):C.type==="select"&&C.options?s.jsx("select",{value:String(P.values[C.key]??C.default??""),onChange:I=>w(P.type,C.key,I.target.value),className:"machine-input text-[11px]",children:C.options.map(I=>s.jsx("option",{value:I,children:I},I))}):s.jsx("input",{type:"text",value:String(P.values[C.key]??C.default??""),onBlur:I=>w(P.type,C.key,I.target.value),className:"machine-input w-[120px] text-[11px]"})})]},C.key))})]},P.type))}),p&&s.jsx(ug,{machineId:e,provider:p,sendDaemonCommand:r,onClose:()=>m(null)}),y&&s.jsx(fg,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>N(!1),onCreated:()=>{N(!1),k()}})]})}const xg=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function bg({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function gg(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function yg(e){return e.trim().toLowerCase()}function yn(e,t){const r=yg(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function xo(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function _s(e,t=220){const r=xo(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function vg(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 wg(e,t){return e.filter(r=>yn([r.level,r.message],t))}function Mi(e){return`${e.timestamp}:${e.level}:${e.message}`}function jg(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const c of e.entries)n.set(Mi(c),c);for(const c of t.entries)n.set(Mi(c),c);const a=Array.from(n.values()).sort((c,l)=>c.timestamp-l.timestamp).slice(-r),o=a.reduce((c,l)=>Math.max(c,Number(l.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 kg(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 Sg(e,t){return e.split(`
74
+ `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>yn([r],t))}function Ng(e,t){return e.filter(r=>yn([r.level,r.category,r.stage,r.interactionId,xo(r.payload)],t))}function Cg(e,t){return e.filter(r=>yn([r.kind,r.topic,r.interactionId,xo(r.payload)],t))}function Ai(e){return e==="warn"||e==="error"}function Tg({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=>Ai(a.level)).length+r.filter(a=>Ai(a.level)).length}}function Mg({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(`
75
75
  `)):t.length>0&&a.push(["[daemon logs]",...t].join(`
76
76
  `)),r.length>0&&a.push(["[trace]",...r.map(o=>`${new Date(o.ts).toISOString()} ${o.level.toUpperCase()} ${o.category}.${o.stage} ${_s(o.payload,500)}`.trim())].join(`
77
77
  `)),n.length>0&&a.push(["[browser events]",...n.map(o=>`${new Date(o.ts).toISOString()} ${o.kind}${o.topic?` topic=${o.topic}`:""} ${_s(o.payload,500)}`.trim())].join(`
78
78
  `)),a.join(`
79
79
 
80
- `)}function Mg({machineId:e,sendDaemonCommand:t}){const[r,n]=i.useState([]),[a,o]=i.useState("empty"),[c,l]=i.useState(""),[d,f]=i.useState([]),[u,p]=i.useState([]),[m,y]=i.useState(null),[N,h]=i.useState(!0),[j,x]=i.useState("info"),[b,v]=i.useState("all"),[A,g]=i.useState(!0),[M,T]=i.useState(!0),[k,w]=i.useState(""),[K,R]=i.useState(""),[S,O]=i.useState(0),U=i.useRef(0),P=i.useRef(0),C=i.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),I=i.useRef([]),W=i.useCallback(()=>{const te={entries:[],kind:"empty",rawText:"",lastTs:0};C.current=te,U.current=0,n([]),l(""),o("empty"),g(!0)},[]),E=i.useCallback(()=>{I.current=[],P.current=0,f([]),T(!0)},[]),$=i.useCallback(te=>{te!==j&&(W(),x(te))},[j,W]),F=i.useCallback(te=>{v(ye=>ye===te?ye:te)},[]),J=i.useCallback(()=>{W(),E(),p([]),y(null),w(""),R(""),Ns.clear()},[W,E]),he=i.useCallback(()=>{O(te=>te+1)},[]),le=i.useCallback(async()=>{if(!e)return;const te=U.current,ye=P.current,[fe,be]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:j,since:te}),t(e,"get_debug_trace",xg({count:120,since:ye,category:b}))]);if(fe.status==="fulfilled"){const X=fe.value,ae=(X==null?void 0:X.result)||X,ge=yg(ae),ee=wg(C.current,ge,300);C.current=ee,U.current=ee.lastTs,g(!1),w((X==null?void 0:X.success)===!1?String((X==null?void 0:X.error)||"Could not load daemon logs"):""),o(ee.kind),l(ee.rawText),n(ee.entries)}else g(!1),w(fe.reason instanceof Error?fe.reason.message:"Could not load daemon logs");if(be.status==="fulfilled"){const X=be.value,ae=(X==null?void 0:X.result)||X;if((X==null?void 0:X.success)===!1)R(String((X==null?void 0:X.error)||"Could not load daemon trace"));else if(Array.isArray(ae==null?void 0:ae.trace)){const ge=ae.trace,ee=jg(I.current,ge,120),de=ge.reduce((we,ue)=>Math.max(we,Number(ue.ts||0)),ye);I.current=ee,de>ye&&(P.current=de),R(""),f(ee)}else R("");T(!1)}else T(!1),R(be.reason instanceof Error?be.reason.message:"Could not load daemon trace");p(Ns.list({limit:120})),y(Date.now())},[j,e,t,b]);return i.useEffect(()=>{E()},[E,b]),i.useEffect(()=>{if(!e||(le(),!N))return;const te=setInterval(()=>{le()},3e3);return()=>clearInterval(te)},[N,le,e,S]),{daemonLogs:r,daemonLogKind:a,daemonRawText:c,debugTrace:d,webEvents:u,lastUpdatedAt:m,autoRefresh:N,logLevel:j,traceCategory:b,daemonLoading:A,traceLoading:M,daemonFetchError:k,traceFetchError:K,setAutoRefresh:h,setLogLevel:$,setTraceCategory:F,refresh:he,clear:J}}function Ag({daemonLoading:e,traceLoading:t,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:o,daemonRawLineCount:c,traceCount:l,webEventCount:d}){return[{id:"daemon_logs",label:"Daemon logs",status:r?"error":e?"loading":o>0||c>0?"ok":"empty",detail:r||(a==="text"?`${c} raw file-fallback line(s)`:`${o} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:n?"error":t?"loading":l>0?"ok":"empty",detail:n||`${l} 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 Ii(e){return e==="warn"||e==="error"}function Ig(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 Lg(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 Li(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function Rg(e){const t=_s(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function _g(e){const t=_s(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function Pg({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.forEach((o,c)=>{a.push({id:`daemon-log-${o.timestamp}-${c}`,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:_g(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:Rg(o),category:o.category,stage:o.stage,interactionId:o.interactionId,payload:o.payload})}),t.forEach((o,c)=>{a.push({id:`raw-file-${c}`,source:"raw_file",ts:Lg(o,c),severity:Ig(o),message:o,raw:o})}),a.sort((o,c)=>o.ts!==c.ts?o.ts-c.ts:Li(o.source)-Li(c.source))}function Dg(e){return`${e.source}:${e.severity}:${e.message}`}function Eg(e){const t=e.filter(n=>Ii(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!Ii(n.severity))continue;const a=Dg(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 $g(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function Ri(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${$g(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function Bg({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
80
+ `)}function Ag({machineId:e,sendDaemonCommand:t}){const[r,n]=i.useState([]),[a,o]=i.useState("empty"),[c,l]=i.useState(""),[d,f]=i.useState([]),[u,p]=i.useState([]),[m,y]=i.useState(null),[N,h]=i.useState(!0),[j,x]=i.useState("info"),[b,v]=i.useState("all"),[A,g]=i.useState(!0),[M,T]=i.useState(!0),[k,w]=i.useState(""),[K,R]=i.useState(""),[S,O]=i.useState(0),H=i.useRef(0),P=i.useRef(0),C=i.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),I=i.useRef([]),W=i.useCallback(()=>{const te={entries:[],kind:"empty",rawText:"",lastTs:0};C.current=te,H.current=0,n([]),l(""),o("empty"),g(!0)},[]),E=i.useCallback(()=>{I.current=[],P.current=0,f([]),T(!0)},[]),$=i.useCallback(te=>{te!==j&&(W(),x(te))},[j,W]),z=i.useCallback(te=>{v(ye=>ye===te?ye:te)},[]),J=i.useCallback(()=>{W(),E(),p([]),y(null),w(""),R(""),Ns.clear()},[W,E]),he=i.useCallback(()=>{O(te=>te+1)},[]),ce=i.useCallback(async()=>{if(!e)return;const te=H.current,ye=P.current,[fe,be]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:j,since:te}),t(e,"get_debug_trace",bg({count:120,since:ye,category:b}))]);if(fe.status==="fulfilled"){const X=fe.value,ae=(X==null?void 0:X.result)||X,ge=vg(ae),ee=jg(C.current,ge,300);C.current=ee,H.current=ee.lastTs,g(!1),w((X==null?void 0:X.success)===!1?String((X==null?void 0:X.error)||"Could not load daemon logs"):""),o(ee.kind),l(ee.rawText),n(ee.entries)}else g(!1),w(fe.reason instanceof Error?fe.reason.message:"Could not load daemon logs");if(be.status==="fulfilled"){const X=be.value,ae=(X==null?void 0:X.result)||X;if((X==null?void 0:X.success)===!1)R(String((X==null?void 0:X.error)||"Could not load daemon trace"));else if(Array.isArray(ae==null?void 0:ae.trace)){const ge=ae.trace,ee=kg(I.current,ge,120),de=ge.reduce((we,ue)=>Math.max(we,Number(ue.ts||0)),ye);I.current=ee,de>ye&&(P.current=de),R(""),f(ee)}else R("");T(!1)}else T(!1),R(be.reason instanceof Error?be.reason.message:"Could not load daemon trace");p(Ns.list({limit:120})),y(Date.now())},[j,e,t,b]);return i.useEffect(()=>{E()},[E,b]),i.useEffect(()=>{if(!e||(ce(),!N))return;const te=setInterval(()=>{ce()},3e3);return()=>clearInterval(te)},[N,ce,e,S]),{daemonLogs:r,daemonLogKind:a,daemonRawText:c,debugTrace:d,webEvents:u,lastUpdatedAt:m,autoRefresh:N,logLevel:j,traceCategory:b,daemonLoading:A,traceLoading:M,daemonFetchError:k,traceFetchError:K,setAutoRefresh:h,setLogLevel:$,setTraceCategory:z,refresh:he,clear:J}}function Ig({daemonLoading:e,traceLoading:t,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:o,daemonRawLineCount:c,traceCount:l,webEventCount:d}){return[{id:"daemon_logs",label:"Daemon logs",status:r?"error":e?"loading":o>0||c>0?"ok":"empty",detail:r||(a==="text"?`${c} raw file-fallback line(s)`:`${o} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:n?"error":t?"loading":l>0?"ok":"empty",detail:n||`${l} 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 Ii(e){return e==="warn"||e==="error"}function Lg(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 Rg(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 Li(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function _g(e){const t=_s(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function Pg(e){const t=_s(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function Dg({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.forEach((o,c)=>{a.push({id:`daemon-log-${o.timestamp}-${c}`,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:Pg(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:_g(o),category:o.category,stage:o.stage,interactionId:o.interactionId,payload:o.payload})}),t.forEach((o,c)=>{a.push({id:`raw-file-${c}`,source:"raw_file",ts:Rg(o,c),severity:Lg(o),message:o,raw:o})}),a.sort((o,c)=>o.ts!==c.ts?o.ts-c.ts:Li(o.source)-Li(c.source))}function Eg(e){return`${e.source}:${e.severity}:${e.message}`}function $g(e){const t=e.filter(n=>Ii(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!Ii(n.severity))continue;const a=Eg(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 Bg(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function Ri(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${Bg(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function Kg({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
81
81
  `)),a.push(["[source status]",...r.map(c=>`${c.label}: ${c.status} - ${c.detail}`)].join(`
82
82
  `)),t.latestIssue&&a.push(["[latest issue]",Ri(t.latestIssue)].join(`
83
83
  `)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.repeatedPatterns.map(c=>`${c.count}x ${c.severity.toUpperCase()} ${c.source} ${c.message}`)].join(`
84
84
  `));const o=e.slice(-n);return a.push(["[timeline]",...o.length>0?o.map(Ri):["No diagnostic events captured."]].join(`
85
85
  `)),a.join(`
86
86
 
87
- `)}function Kg(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Og(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Wg({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:c,searchQuery:l,daemonLoading:d,traceLoading:f,daemonFetchError:u,traceFetchError:p}){const m=bg(n,o),y=vg(e,l),N=kg(t,l),h=Sg(m,l),j=Ng(a,l),x=Kg(y,c),b=c==="all"?N:[],v=Og(h,c),A=c==="issues"?[]:j,g=Cg({daemonLogs:y,daemonRawLines:N,trace:h,webEvents:j}),M=Pg({daemonLogs:x,daemonRawLines:b,trace:v,webEvents:A}),T=Eg(M),k=Ag({daemonLoading:d,traceLoading:f,daemonFetchError:u,traceFetchError:p,daemonLogKind:r,daemonLogsCount:y.length,daemonRawLineCount:N.length,traceCount:h.length,webEventCount:j.length});return{filteredDaemonLogs:y,filteredDaemonRawLines:N,filteredTraceEntries:h,filteredWebEvents:j,visibleDaemonLogs:x,visibleDaemonRawLines:b,visibleTraceEntries:v,visibleWebEvents:A,quickFilterCounts:g,diagnosticEvents:M,diagnosticsSummary:T,sourceStates:k}}function Fg(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Ul(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function Ta(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 Xn(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 bo(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function Hg({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Ta(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Ul(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:bo(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 Ug({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:c,onCopyVisible:l,onToggleAutoRefresh:d,onRefresh:f,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(p=>s.jsx("button",{type:"button",onClick:()=>a(p.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===p.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:p.label},p.id))}),s.jsx("input",{value:r,onChange:p=>o(p.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:l,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:f,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function zg({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:hg.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 Vg({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:c,traceFetchError:l}){var u,p;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((p=e.latestIssue)==null?void 0:p.severity)==="warn"?"warning":"good",f=c||l?"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 ${Xn(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 ${Xn(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:[bo(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:Ul(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 ${Xn(f)}`,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:c||l?"Needs attention":o?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",Fg(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(m=>s.jsxs("div",{children:[m.label,": ",m.status]},m.id))})]})]})}function Gg({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()," · ",bo(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function qg({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:c,visibleWebEvents:l,quickFilter:d,searchQuery:f}){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(Hg,{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,p)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${p}`)),e.daemonLogKind!=="text"&&a.map((u,p)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Ta(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-${p}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(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:[c.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&&c.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&c.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&c.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:f.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."}),c.map(u=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Ta(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:_s(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:[l.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:[l.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:f.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),l.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:_s(u.payload,360)||"No payload"})]},u.id))]})]})]})}function Yg({machineId:e,sendDaemonCommand:t}){const r=Mg({machineId:e,sendDaemonCommand:t}),[n,a]=i.useState("info"),[o,c]=i.useState(""),[l,d]=i.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),f=i.useRef(null),u=i.useRef(!1),p=i.useMemo(()=>Wg({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&&p.diagnosticEvents.length>0){const N=u.current?"smooth":"instant";setTimeout(()=>{var h;(h=f.current)==null||h.scrollIntoView({behavior:N}),u.current=!0},50)}},[p.diagnosticEvents.length,r.autoRefresh]);const m=i.useCallback(async()=>{var h;const N=Tg({daemonLogs:p.visibleDaemonLogs,daemonRawLines:p.visibleDaemonRawLines,trace:p.visibleTraceEntries,webEvents:p.visibleWebEvents});if(!N.trim()){rt.showToast("No visible logs to copy.","info");return}try{await((h=navigator.clipboard)==null?void 0:h.writeText(N)),rt.showToast("Copied visible logs to clipboard.","success")}catch(j){rt.showToast(j instanceof Error?j.message:"Could not copy visible logs","warning")}},[p.visibleDaemonLogs,p.visibleDaemonRawLines,p.visibleTraceEntries,p.visibleWebEvents]),y=i.useCallback(async()=>{var h;const N=Bg({events:p.diagnosticEvents,summary:p.diagnosticsSummary,sources:p.sourceStates});try{await((h=navigator.clipboard)==null?void 0:h.writeText(N)),rt.showToast("Copied diagnostic bundle to clipboard.","success")}catch(j){rt.showToast(j instanceof Error?j.message:"Could not copy diagnostic bundle","warning")}},[p.diagnosticEvents,p.diagnosticsSummary,p.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(Ug,{quickFilter:n,quickFilterCounts:p.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:c,onCopyDiagnostics:()=>{y()},onCopyVisible:()=>{m()},onToggleAutoRefresh:()=>r.setAutoRefresh(N=>!N),onRefresh:r.refresh,onClear:r.clear}),s.jsx(zg,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(Vg,{diagnosticsSummary:p.diagnosticsSummary,diagnosticEventsCount:p.diagnosticEvents.length,sourceStates:p.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(Gg,{patterns:p.diagnosticsSummary.repeatedPatterns}),s.jsx(qg,{streams:r,sectionsOpen:l,setSectionsOpen:d,diagnosticEvents:p.diagnosticEvents,visibleDaemonLogs:p.visibleDaemonLogs,visibleDaemonRawLines:p.visibleDaemonRawLines,visibleTraceEntries:p.visibleTraceEntries,visibleWebEvents:p.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:f})]})}function Xg(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 zl(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 Jg(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const c=String((o==null?void 0:o.lifecycle)||"").trim(),l=zl((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(c)?t.push(o):(c==="stopped"||c==="failed")&&(d||l)?r.push(o):n.push(o)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function Qg(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Jn(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 Qn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Zn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function _i(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 Zg(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function ey(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 ty(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 sy({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=i.useState(""),[o,c]=i.useState(null),[l,d]=i.useState(!1),f=vh(e,{enabled:!!e,includeSessions:!0,limit:Uo,intervalMs:xm}),u=f.diagnostics,p=f.loading,m=f.applyDiagnostics,y=i.useMemo(()=>Xg({diagnostics:u,loading:p,refreshing:l,error:n}),[u,p,l,n]),N=i.useMemo(()=>new Map(t.map(R=>[R.sessionId||R.id,R])),[t]),h=i.useCallback(async()=>{if(e){d(!0);try{const R=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Uo}),S=Qn(R);if(!(S!=null&&S.success))throw new Error((S==null?void 0:S.error)||"Could not load hosted runtime diagnostics");m(S.diagnostics||S.result||null),a("")}catch(R){const S=R instanceof Error?R.message:"Could not load hosted runtime diagnostics";a(S)}finally{d(!1)}}},[m,e,r]);i.useEffect(()=>{!e||u||p||l||h()},[u,p,e,h,l]);const j=i.useCallback(async(R,S)=>{const O=`${R}:${S.sessionId}`;if(!(R==="session_host_stop_session"&&!window.confirm(`Stop ${S.displayName}?
88
- This will terminate the hosted runtime.`))){c(O);try{const U=await r(e,R,{sessionId:S.sessionId}),P=Qn(U);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Session host action failed");const C=R==="session_host_resume_session"?"resumed":R==="session_host_restart_session"?"restarted":"stopped";rt.showToast(`Session host ${C}: ${S.displayName}`,"success"),await h()}catch(U){const P=U instanceof Error?U.message:"Session host action failed";rt.showToast(P,"warning"),a(P)}finally{c(U=>U===O?null:U)}}},[e,h,r]),x=i.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
89
- The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const S=await r(e,"session_host_prune_duplicate_sessions",{}),O=Qn(S);if(!(O!=null&&O.success))throw new Error((O==null?void 0:O.error)||"Duplicate prune failed");const U=O.result||{},P=Array.isArray(U.prunedSessionIds)?U.prunedSessionIds.length:0,C=typeof U.duplicateGroupCount=="number"?U.duplicateGroupCount:0;rt.showToast(`Pruned ${P} duplicate runtime(s) across ${C} group(s)`,"success"),await h()}catch(S){const O=S instanceof Error?S.message:"Duplicate prune failed";rt.showToast(O,"warning"),a(O)}finally{c(S=>S==="session_host_prune_duplicate_sessions"?null:S)}}},[e,h,r]),b=i.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((R,S)=>(S.lastActivityAt||0)-(R.lastActivityAt||0)),[u==null?void 0:u.sessions]),v=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)||[]}:Jg(b),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,b]),A=v.liveRuntimes,g=v.recoverySnapshots,M=v.inactiveRecords,T=i.useMemo(()=>ty(A),[A]),k=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(R=>R.level==="warn"||R.level==="error")||null,[u==null?void 0:u.recentLogs]),K=(R,S)=>{var F;const O=o===`session_host_resume_session:${R.sessionId}`,U=o===`session_host_restart_session:${R.sessionId}`,P=o===`session_host_stop_session:${R.sessionId}`,C=zl(R.meta),I=N.get(R.sessionId),W=R.attachedClients.length===1?"1 client":`${R.attachedClients.length} clients`,E=S==="recovery"?"Recover":"Resume",$=Qg(S);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:R.displayName||(I==null?void 0:I.cliName)||R.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${ey(R.lifecycle)}`,children:R.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:R.workspaceLabel||(I==null?void 0:I.runtimeWorkspaceLabel)||R.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:R.runtimeKey}),R.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",R.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((F=R.writeOwner)==null?void 0:F.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Zg(R.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(qi,{size:11})," ",W]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",_i(R.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",$]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[S==="recovery"&&(R.lifecycle==="interrupted"||R.lifecycle==="failed"||R.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{j("session_host_resume_session",R)},children:O?`${E}ing…`:E}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{j("session_host_restart_session",R)},children:U?"Restarting…":"Restart"}),S==="live"&&(R.lifecycle==="running"||R.lifecycle==="starting"||R.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:()=>{j("session_host_stop_session",R)},children:P?"Stopping…":"Stop"})]})]})},R.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(us,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Cp()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[T>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{x()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${T})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${y.toneClass}`,children:y.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{h()},disabled:p||l,children:[s.jsx(lr,{size:13}),p||l?"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(nr,{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:g.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:_i(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Zn(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(nr,{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:[Zn(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(Ea,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Jn("live")}),A.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:A.map(R=>K(R,"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(us,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Jn("recovery")}),g.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:g.map(R=>K(R,"recovery"))})]}),M.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:Jn("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:M.map(R=>K(R,"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"}),k.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:k.map(R=>{var O;const S=b.find(U=>U.sessionId===R.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:(S==null?void 0:S.displayName)||((O=N.get(R.sessionId))==null?void 0:O.cliName)||R.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[R.action,R.lifecycle?` · ${R.lifecycle}`:"",R.detail?` · ${R.detail}`:"",R.error?` · ${R.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${R.success===!1?"text-red-300":"text-text-secondary"}`,children:Zn(R.timestamp)})]},`${R.sessionId}:${R.timestamp}:${R.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 ry({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 ea({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 ta({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 ny({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:c}){const l=n.slice(0,6),d=r.slice(0,4),u=Zs(e,"0.9.59");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:[l.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(ea,{icon:s.jsx(Ut,{size:13}),children:"Current Chats"}),s.jsx(ta,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(p=>{const m=xa(p);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>c(p),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:it(p)}),m>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:ln(m)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:As(p)})]},p.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(ea,{icon:s.jsx(Qi,{size:13}),children:"Recent Launches"}),s.jsx(ta,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(p=>{const{metaText:m,updatedLabel:y}=Sl(p);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>o(p),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:p.label}),y&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:y})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:m})]},p.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(ea,{icon:s.jsx(nr,{size:13}),children:"Daemon Update"}),s.jsx(ta,{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:u?"Daemon update required":"Version mismatch detected"}),s.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:u?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),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(lr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function ay(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function oy({machine:e,selectedWorkspace:t,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:o,onCustomPathChange:c,onOpenBrowseDialog:l}){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 f=d.target.value;if(o(f),f==="__custom__"&&a){l();return}f!=="__custom__"&&c("")},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?"⭐ ":"",un(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:l,children:"Select workspace…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:n,onChange:d=>c(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 iy={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 _r(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function sa({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:o,actions:c,sendDaemonCommand:l,initialWorkspaceId:d,initialWorkspacePath:f,onOpenGitDialog:u}){const p=Ps(),{handleLaunchIde:m,handleStopCli:y,handleRestartIde:N,handleStopIde:h,handleDetectIdes:j,launchingIde:x,launchingAgentType:b,addLog:v}=c,[A,g]=i.useState(null),M=i.useCallback(B=>{B&&p(Yt(B))},[p]),T=iy[e],k=e==="ide",w=e==="acp",K=i.useMemo(()=>n.filter(B=>ps(B,e)),[e,n]),R=i.useMemo(()=>new Map(K.map(B=>[B.type,B.displayName||B.type])),[K]),[S,O]=i.useState(""),[U,P]=i.useState(""),[C,I]=i.useState([]),[W,E]=i.useState(""),[$,F]=i.useState(""),[J,he]=i.useState([]),[le,te]=i.useState(!1),[ye,fe]=i.useState(!1),[be,X]=i.useState(""),[ae,ge]=i.useState(!1),[ee,de]=i.useState(()=>xt()),[we,ue]=i.useState(null),[xe,se]=i.useState(f?"__custom__":d||t.defaultWorkspaceId||""),[ie,re]=i.useState(f||""),[q,Y]=i.useState([]),[ce,ke]=i.useState(!1),[Z,Se]=i.useState(""),[Me,We]=i.useState([]),[Fe,D]=i.useState(!1),[Ne,Ie]=i.useState(""),Re=i.useRef(null),[De,He]=i.useState(null),Ue=i.useRef("__home__"),[Qe,lt]=i.useState("__home__"),[dt,ut]=i.useState(!1),Te=i.useRef(0),Ge=q.filter(B=>!a.some(oe=>oe.type===B&&yt(oe.status)!=="stopped")),Ze=i.useRef({});i.useEffect(()=>{t.defaultWorkspaceId&&!xe&&se(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),i.useEffect(()=>{if(f){se("__custom__"),re(f);return}d&&(se(d),re(""))},[d,f]),i.useEffect(()=>{k||S&&(K.some(B=>B.type===S)||(O(""),F("")))},[K,k,S]);const qe=(()=>{if(xe==="__custom__")return ie.trim();if(!xe)return"";const B=(t.workspaces||[]).find(oe=>oe.id===xe);return(B==null?void 0:B.path)||""})(),tt=i.useCallback(B=>{const oe=Ze.current[B];oe&&(clearTimeout(oe),delete Ze.current[B]),Y(pe=>pe.includes(B)?pe.filter(Ke=>Ke!==B):pe)},[]),H=i.useRef(new Set),V=i.useCallback(async B=>{if(l){D(!0),Ie("");try{const oe=await xn(l,r,B);Se(oe.path),re(oe.path),We(oe.directories)}catch(oe){Ie(oe instanceof Error?oe.message:"Could not load folder")}finally{D(!1)}}},[r,l]),L=i.useCallback(()=>{if(!l)return;se("__custom__"),ke(!0);const B=a.map(pe=>pe.workspace),oe=hn(t.platform,pn(ie.trim(),qe,f,B,t.defaultWorkspacePath,(t.workspaces||[]).map(pe=>pe.path)));V(oe)},[ie,f,V,t.defaultWorkspacePath,t.platform,t.workspaces,a,qe,l]),G=i.useCallback(B=>{const oe=String(B.workspace||"").trim();if(!oe)return;const pe=(t.workspaces||[]).find(Ke=>_r(Ke.path)===_r(oe));if(pe){se(pe.id),re("");return}se("__custom__"),re(oe)},[t.workspaces]),_=i.useCallback(B=>{const oe=String(B.workspace||"").trim();if(!oe)return{workspaceId:null,workspacePath:"",useHome:!0};const pe=(t.workspaces||[]).find(Ke=>_r(Ke.path)===_r(oe));return pe?{workspaceId:pe.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:oe,useHome:!1}},[t.workspaces]),z=i.useCallback(async B=>{if(!l||!B||e!=="cli"){he([]),te(!1),fe(!1),X("");return}const oe=Te.current+1;Te.current=oe,te(!0),X("");try{const pe=await l(r,"list_saved_sessions",{providerType:B,kind:"cli",limit:30});if(Te.current!==oe)return;const Ke=(pe==null?void 0:pe.result)??pe;he(Array.isArray(Ke==null?void 0:Ke.sessions)?Ke.sessions:[])}catch(pe){if(Te.current!==oe)return;he([]),X(pe instanceof Error?pe.message:"Could not load saved sessions")}finally{Te.current===oe&&(te(!1),fe(!0))}},[e,r,l]),Q=i.useMemo(()=>{if(e!=="cli"||!S)return null;const B=R.get(S)||S;return{routeId:r,daemonId:r,providerSessionId:$||void 0,transport:"pty",mode:"chat",agentName:B,agentType:S,status:"idle",title:B,messages:[],ideType:S,workspaceName:qe,workspacePath:qe,displayPrimary:B,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${S}`}},[e,r,R,qe,$,S]),ne=i.useCallback(B=>{if(e==="ide"||!B){I([]);return}I(Bl(r,B))},[e,r]);i.useEffect(()=>{Te.current+=1,F(""),ne(S),fe(!1),he([]),X(""),te(!1)},[e,ne,z,S]);const ve=i.useMemo(()=>J.find(B=>B.providerSessionId===$)||null,[J,$]);i.useEffect(()=>{if(!$)return;const B=J.find(oe=>oe.providerSessionId===$);B!=null&&B.canResume||F("")},[J,$]);const Ae=i.useCallback((B,oe)=>{Re.current=oe,Ue.current=B.selectedWorkspaceKey||"__home__",lt(B.selectedWorkspaceKey||"__home__"),He(B)},[]),Pe=i.useCallback(()=>{Re.current&&(ut(!0),Re.current().finally(()=>{Re.current=null,ut(!1),He(null)}))},[]),Ce=i.useCallback(B=>{if(!B)return;Y(pe=>pe.includes(B)?pe:[...pe,B]);const oe=Ze.current[B];oe&&clearTimeout(oe),Ze.current[B]=setTimeout(()=>{Y(pe=>pe.includes(B)?pe.filter(Ke=>Ke!==B):pe),delete Ze.current[B]},2e4)},[]);i.useEffect(()=>{for(const oe of a)yt(oe.status)!=="stopped"&&(q.includes(oe.type)&&!H.current.has(oe.type)&&(H.current.add(oe.type),v("info",`${R.get(oe.type)||oe.type} launched`,!0)),tt(oe.type));const B=new Set(a.filter(oe=>yt(oe.status)!=="stopped").map(oe=>oe.type));H.current.forEach(oe=>{!q.includes(oe)&&!B.has(oe)&&H.current.delete(oe)})},[v,tt,a,q,R]),i.useEffect(()=>()=>{Object.values(Ze.current).forEach(clearTimeout),Ze.current={}},[]);const[Ee,Be]=i.useState({}),[_e,ze]=i.useState(null);i.useEffect(()=>{if(!k||!r||!l)return;(async()=>{try{const oe=await l(r,"get_ide_extensions",{}),pe=(oe==null?void 0:oe.result)||oe;pe!=null&&pe.success&&(pe!=null&&pe.ideExtensions)&&Be(pe.ideExtensions)}catch{}})()},[k,r,l]);const Je=B=>k?at(B.type):e==="cli"?B.cliName:B.acpName,ft=k?t.detectedIdes||[]:[],pt=i.useCallback(async B=>{const oe=(B==null?void 0:B.type)||S,pe=(B==null?void 0:B.workspacePath)??qe;if(k){await m(oe,pe?{workspace:pe}:void 0)&&Ce(oe);return}const Ke=await c.runLaunchCliCore({cliType:oe,dir:B!=null&&B.workspaceId?void 0:pe||void 0,workspaceId:(B==null?void 0:B.workspaceId)||void 0,useHome:(B==null?void 0:B.useHome)||!(B!=null&&B.workspaceId)&&!pe,argsStr:(B==null?void 0:B.argsStr)??(U||void 0),model:(B==null?void 0:B.model)??(w&&W||void 0),resumeSessionId:(B==null?void 0:B.resumeSessionId)||!w&&e==="cli"&&oe===S&&$||void 0});if(Ke.success||Ke.pending){const Le=(B==null?void 0:B.argsStr)??U;!k&&(Le!=null&&Le.trim())&&(Kl(r,oe,Le),ne(oe)),Ce(oe),Ke.success&&Ke.sessionId&&M(Ke.sessionId)}},[c,m,w,k,U,W,ne,Ce,r,M,qe,$,S]),ht=Vc(k?"ide":w?"acp":"cli",!k&&!w&&!!$),me=Gc(k?"ide":w?"acp":"cli",!k&&!w&&!!$),je=()=>{var Le;const B=k?at(S):R.get(S)||S,oe=!k&&!w&&!!$,{options:pe,selectedKey:Ke}=cs({machine:t,currentWorkspaceId:xe&&xe!=="__custom__"?xe:null,currentWorkspacePath:qe});Ae({title:oe?to(B):ns("start-fresh",B),description:oe?so():as("start-fresh"),confirmLabel:ht,busyLabel:me,workspaceOptions:pe,selectedWorkspaceKey:Ke,details:[{label:"Mode",value:T.label},{label:"Provider",value:B},...!k&&e==="cli"&&$?[{label:"Resume",value:((Le=J.find($e=>$e.providerSessionId===$))==null?void 0:Le.title)||$}]:[],...!k&&U.trim()?[{label:"Arguments",value:U.trim()}]:[],...w&&W.trim()?[{label:"Model",value:W.trim()}]:[]]},async()=>{const $e=pe.find(nt=>nt.key===Ue.current);$e!=null&&$e.workspaceId?(se($e.workspaceId),re("")):$e!=null&&$e.workspacePath?(se("__custom__"),re($e.workspacePath)):(se(""),re("")),await pt({workspaceId:($e==null?void 0:$e.workspaceId)??null,workspacePath:($e==null?void 0:$e.workspacePath)??"",useHome:!($e!=null&&$e.workspaceId)&&!($e!=null&&$e.workspacePath)})})},wt=B=>{k?h(B):y(B.type,B.workspace,B.id)},bt=i.useCallback(async(B,oe,pe=!1)=>{if(B.mode===oe){pe&&B.sessionId&&M(B.sessionId);return}if(!l||!B.sessionId){pe&&B.sessionId&&M(B.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:B.sessionId,cliType:B.type,mode:oe}),pe&&M(B.sessionId)}catch(Ke){const Le=ml(Ke);fl(Ke)?console.warn(Le?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Ke instanceof Error?Ke.message:String(Ke)):console.error("Failed to switch CLI view mode:",Ke)}},[r,M,l]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${T.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 ",T.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:k?ft.length>0?ft.map(B=>{const oe=a.find(nt=>(nt.type||"").toLowerCase()===(B.type||"").toLowerCase()&&yt(nt.status)!=="stopped"),pe=B.running||!!oe,Ke=!!oe&&oe.cdpConnected,Le=q.includes(B.type||B.id||""),$e=S===(B.type||"");return s.jsxs("button",{onClick:()=>{if(Ke&&oe){const nt=oe.sessionId;nt?p(Yt(nt),{state:{openRemoteForTabKey:nt}}):p("/dashboard",{state:{openRemoteForTabKey:oe.id}});return}Le||O(nt=>nt===(B.type||"")?"":B.type||"")},disabled:!!x||Le,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Ke?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":$e?"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:x&&x!==B.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(B.type)}),pe&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Ke?"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:B.name||at(B.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Ke?"text-green-400":Le?"text-orange-400":$e?"text-accent-primary":"text-text-muted"}`,children:Ke?"Open Session":Le?"Starting...":$e?"Configure":"Select"})]})]},B.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:j,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(ru,{size:14})," Scan System"]})]}):K.length>0?K.map(B=>{const oe=S===B.type,pe=q.includes(B.type),Le=!!a.find($e=>$e.type===B.type&&yt($e.status)!=="stopped");return s.jsxs("button",{onClick:()=>O($e=>$e===B.type?"":B.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${oe?"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:B.icon}),Le&&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:B.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${pe?"text-orange-400":oe?"text-accent-primary":"text-text-muted"}`,children:pe?"Starting...":oe?"Configure":"Select"})]})]},B.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."})]})}),S&&(k?ft.find(B=>B.type===S):K.find(B=>B.type===S))&&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:k?at(S):R.get(S)||S})]}),s.jsx(oy,{machine:t,selectedWorkspace:xe,resolvedWorkspacePath:qe,customPath:ie,canBrowse:!!l,onWorkspaceChange:se,onCustomPathChange:re,onOpenBrowseDialog:L}),!k&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&e==="cli"&&s.jsx(Wl,{busy:!!b||!!x||q.includes(S),savedSessionsLoading:le,savedSessionsError:be,savedSessionsLoaded:ye,savedSessionsCount:J.length,selectedSession:ve,onRefresh:()=>void z(S),onOpenHistory:()=>{S&&(ge(!0),Ol({hasLoadedInitialResults:ye,isLoading:le})&&z(S))},onClearSelection:()=>F("")}),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:W,onChange:B=>E(B.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:U,onChange:B=>P(B.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(B=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>P(B),title:B,children:B},B))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:je,disabled:!!b||!!x||q.includes(S),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:b===S||x===S?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+q.filter(B=>!a.some(oe=>oe.type===B&&yt(oe.status)!=="stopped")).length,")"]}),a.length===0&&Ge.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 ",T.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ge.map(B=>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(B)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:k?at(B):R.get(B)||B}),s.jsx("div",{className:"text-[11px] text-text-muted",children:b===B?"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:${B}`)),a.map(B=>{const oe=k?B:null,pe=!k&&!w?B:null,Ke=yt(B.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(B.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Je(B),(oe==null?void 0:oe.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",oe.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:B.workspace||"—"}),u&&B.git&&B.workspace?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:Le=>{Le.stopPropagation(),u(B.daemonId??r,B.workspace)},children:s.jsx(Is,{git:B.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Is,{git:B.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(pe==null?void 0:pe.mode)&&s.jsx("span",{className:pe.mode==="chat"?"text-violet-400":"text-text-secondary",children:pe.mode==="chat"?"Chat view":"Terminal view"})]}),pe&&(pe.runtimeKey||pe.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[pe.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 ",pe.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 Le;(Le=navigator.clipboard)==null||Le.writeText(`adhdev attach ${pe.runtimeKey}`),g(pe.runtimeKey||null),window.setTimeout(()=>{g($e=>$e===pe.runtimeKey?null:$e)},1200)},children:A===pe.runtimeKey?"Copied":"Copy"})]}),pe.runtimeWriteOwner&&s.jsx("span",{style:{color:pe.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:pe.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:ay(pe.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 ${Ke==="stopped"?"bg-red-500/[0.08] text-red-500":Ke==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Ke}),k&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Le=B.sessionId;if(Le){p(Yt(Le),{state:{openRemoteForTabKey:Le}});return}p("/dashboard",{state:{openRemoteForTabKey:B.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(Tt,{size:13})}),s.jsx("button",{onClick:()=>{const Le=B.workspace||"",{options:$e,selectedKey:nt}=cs({machine:t,currentWorkspacePath:Le});Ae({title:ns("restart-ide",at(B.type)),description:as("restart-ide"),confirmLabel:Ls("restart-ide"),busyLabel:Rs("restart-ide"),workspaceOptions:$e,selectedWorkspaceKey:nt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:at(B.type)}]},async()=>{const jt=$e.find(Vt=>Vt.key===Ue.current),ct=(jt==null?void 0:jt.workspacePath)??"";if(ct&&ct!==Le){await pt({type:B.type,workspacePath:ct});return}await N(B)})},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(lr,{size:14})})]}),w&&s.jsx("button",{onClick:()=>{const Le=B.sessionId;Le&&M(Le)},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:!B.sessionId,children:s.jsx(Ut,{size:14})}),pe&&Ke!=="stopped"&&s.jsxs(s.Fragment,{children:[pe.mode&&s.jsx(Qa,{mode:pe.mode,onChange:Le=>void bt(pe,Le,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Le=B.sessionId;Le&&M(Le)},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:!B.sessionId,children:pe.mode==="chat"?s.jsx(Ut,{size:14}):s.jsx(Tt,{size:13})})]}),Ke==="stopped"?s.jsx("button",{onClick:()=>{const Le=B.workspace||"",$e=k?at(B.type):Je(B),{options:nt,selectedKey:jt}=cs({machine:t,currentWorkspacePath:Le});Ae({title:ns("restart-stopped",$e),description:as("restart-stopped"),confirmLabel:Ls("restart-stopped"),busyLabel:Rs("restart-stopped"),workspaceOptions:nt,selectedWorkspaceKey:jt,details:[{label:"Mode",value:T.label},{label:"Provider",value:$e}]},async()=>{const ct=nt.find(Vt=>Vt.key===Ue.current);await pt({type:B.type,workspaceId:(ct==null?void 0:ct.workspaceId)??null,workspacePath:(ct==null?void 0:ct.workspacePath)??"",useHome:!(ct!=null&&ct.workspaceId)&&!(ct!=null&&ct.workspacePath)})})},disabled:q.includes(B.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:q.includes(B.type)?"⏳":s.jsx($a,{size:14})}):s.jsx("button",{onClick:()=>wt(B),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(St,{size:14})})]})]}),oe&&oe.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:oe.aiAgents.map(Le=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${cc(Le.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Le.name," · ",yt(Le.status)]},Le.id))}),oe&&(Ee[oe.type]||[]).length>0&&l&&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:(Ee[oe.type]||[]).map(Le=>s.jsxs("button",{disabled:_e===`${oe.type}.${Le.type}`,onClick:async()=>{const $e=`${oe.type}.${Le.type}`;ze($e);try{await l(r,"set_ide_extension",{ideType:oe.type,extensionType:Le.type,enabled:!Le.enabled}),Be(nt=>({...nt,[oe.type]:(nt[oe.type]||[]).map(jt=>jt.type===Le.type?{...jt,enabled:!jt.enabled}:jt)}))}catch(nt){console.error("Extension toggle failed:",nt)}finally{ze(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 ${Le.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 ${Le.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Le.name,s.jsx("span",{className:"text-[9px] font-normal",children:Le.enabled?"ON":"OFF"})]},Le.type))})]})]},B.id)})]}),ce&&l&&s.jsx(bn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:Z,directories:Me,busy:Fe,error:Ne,confirmLabel:"Use this folder",onClose:()=>ke(!1),onNavigate:B=>{V(B)},onConfirm:B=>{re(B),se("__custom__"),ke(!1)}}),De&&s.jsx(mo,{title:De.title,description:De.description,details:De.details,workspaceOptions:De.workspaceOptions,selectedWorkspaceKey:Qe,onWorkspaceChange:B=>{Ue.current=B,lt(B)},confirmLabel:De.confirmLabel,busyLabel:De.busyLabel,busy:dt,onConfirm:Pe,onCancel:()=>{Re.current=null,He(null)}}),ae&&Q&&s.jsx(ro,{activeConv:Q,ides:[],isCreatingChat:!1,isRefreshingHistory:le,savedSessions:J,isSavedSessionsLoading:le,isResumingSavedSessionId:we,savedHistoryFilters:ee,missingWorkspaceResumePath:qe||null,onSavedHistoryFiltersChange:de,onClose:()=>ge(!1),onNewChat:()=>{F(""),ge(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{z(S)},onResumeSavedSession:B=>{if(!B.canResume||we)return;const oe=_(B);F(B.providerSessionId),G(B),ue(B.providerSessionId),ge(!1),pt({type:B.providerType,workspaceId:oe.workspaceId,workspacePath:oe.workspacePath,useHome:oe.useHome,resumeSessionId:B.providerSessionId}).finally(()=>{ue(pe=>pe===B.providerSessionId?null:pe)})}})]})}const Pi=[{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 cy({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:o,actions:c,getIcon:l,initialCategory:d="ide",initialWorkspaceId:f,initialWorkspacePath:u,sendDaemonCommand:p,onOpenGitDialog:m}){var j;const[y,N]=i.useState(d);i.useEffect(()=>{N(d)},[d]);const h=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:Pi.map(x=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${y===x.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>N(x.id),children:[s.jsx("span",{children:x.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${y===x.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:h[x.id]})]},x.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(j=Pi.find(x=>x.id===y))==null?void 0:j.helper})]}),y==="ide"&&s.jsx(sa,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:p,initialWorkspaceId:f,initialWorkspacePath:u,onOpenGitDialog:m}),y==="cli"&&s.jsx(sa,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:p,initialWorkspaceId:f,initialWorkspacePath:u,onOpenGitDialog:m}),y==="acp"&&s.jsx(sa,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:o,getIcon:l,actions:c,sendDaemonCommand:p,initialWorkspaceId:f,initialWorkspacePath:u,onOpenGitDialog:m})]})}function ly({onNicknameSynced:e}={}){var re,q,Y,ce,ke,Z,Se,Me,We,Fe;const{id:t}=Td(),r=Ps(),n=La(),{sendCommand:a}=mt(),o=fr(),c=cl(),l=Bc(),d=l.ides||[],f=l.initialLoaded??!0,u=d.find(D=>D.id===t&&D.type==="adhdev-daemon"),p=d.some(D=>D.type==="adhdev-daemon"),m=t?(re=l.connectionRetryStatuses)==null?void 0:re[t]:void 0,y=!!(m!=null&&m.blocked),[N,h]=i.useState("workspace"),[j,x]=i.useState(null),b=i.useCallback((D,Ne)=>{x({daemonId:D,workspace:Ne})},[]),[v,A]=i.useState("ide"),g=i.useRef(null),[M,T]=i.useState(null),k=i.useRef("__home__"),[w,K]=i.useState("__home__"),[R,S]=i.useState(!1),O=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||N!=="overview")return;const D=u.machine;(typeof(D==null?void 0:D.cpus)!="number"||typeof(D==null?void 0:D.totalMem)!="number"||typeof(D==null?void 0:D.arch)!="string"||typeof(D==null?void 0:D.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[N,c,u,t]),yh(t&&N==="overview"?[t]:[],{enabled:N==="overview",intervalMs:fm});const U=()=>{if(p){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},P=ng({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:O});i.useEffect(()=>rt.onToast(Ne=>{l.setToasts(Re=>{if(Re.some(Ue=>Ue.message===Ne.message&&Ne.timestamp-Ue.timestamp<3e3))return Re;const He={id:Ne.id,message:Ne.message,type:Ne.type,timestamp:Ne.timestamp,targetKey:Ne.targetKey,actions:Ne.actions};return[...Re.slice(-4),He]});const Ie=Ne.duration||5e3;setTimeout(()=>l.setToasts(Re=>Re.filter(De=>De.id!==Ne.id)),Ie)}),[l]);const C=(u==null?void 0:u.availableProviders)||[],I={};for(const D of C)I[D.type]=D.icon;const W=D=>I[D]||"",E=u?{id:u.id,hostname:lc(u,{fallbackId:u.id}),platform:((q=u.machine)==null?void 0:q.platform)||"unknown",arch:((Y=u.machine)==null?void 0:Y.arch)||"",cpus:((ce=u.machine)==null?void 0:ce.cpus)||0,totalMem:((ke=u.machine)==null?void 0:ke.totalMem)||0,freeMem:(Z=u.machine)==null?void 0:Z.freeMem,availableMem:(Se=u.machine)==null?void 0:Se.availableMem,loadavg:(Me=u.machine)==null?void 0:Me.loadavg,uptime:(We=u.machine)==null?void 0:We.uptime,release:((Fe=u.machine)==null?void 0:Fe.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,$=d.filter(D=>D.daemonId===t&&D.type!=="adhdev-daemon").filter(D=>!or(D)&&!js(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,version:D.version||"",instanceId:D.instanceId||"",status:D.status,workspace:D.workspace||null,terminals:D.terminals||0,aiAgents:af(D.aiAgents||(D.agents||[]).map(Ne=>({id:Ne.name,name:Ne.name,status:Ne.status,version:Ne.version}))),activeChat:D.activeChat||null,chats:D.chats||[],childSessions:D.childSessions||[],cdpConnected:D.cdpConnected||!1,daemonId:t})),F=d.filter(D=>D.daemonId===t&&or(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,cliName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,mode:D.mode,runtimeKey:D.runtimeKey,runtimeDisplayName:D.runtimeDisplayName,runtimeWorkspaceLabel:D.runtimeWorkspaceLabel,runtimeWriteOwner:D.runtimeWriteOwner||null,runtimeAttachedClients:D.runtimeAttachedClients||[],daemonId:t})),J=d.filter(D=>D.daemonId===t&&js(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,acpName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,daemonId:t})),he=u?Ct(u,{fallbackId:t}):"",le="workspace",te=n.state,ye=te==null?void 0:te.initialMachineTab,fe=te==null?void 0:te.initialWorkspaceCategory,be=te==null?void 0:te.initialWorkspaceId,X=te==null?void 0:te.initialWorkspacePath,ae=ye==="ides"||ye==="clis"||ye==="acps"?"workspace":ye||le,ge=ye==="ides"?"ide":ye==="clis"?"cli":ye==="acps"?"acp":fe,ee=[...$.map(D=>{var Ne,Ie,Re,De,He;return{id:`ide:${D.type}:${D.workspace||""}`,label:((Ne=D.activeChat)==null?void 0:Ne.title)||D.type,kind:"ide",providerType:D.type,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((He=(De=(Re=(Ie=D.activeChat)==null?void 0:Ie.messages)==null?void 0:Re.at)==null?void 0:De.call(Re,-1))==null?void 0:He.timestamp)||0}}),...F.map(D=>{var Ne,Ie,Re,De,He;return{id:`cli:${D.type}:${D.workspace||""}`,label:((Ne=D.activeChat)==null?void 0:Ne.title)||D.cliName,kind:"cli",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((He=(De=(Re=(Ie=D.activeChat)==null?void 0:Ie.messages)==null?void 0:Re.at)==null?void 0:De.call(Re,-1))==null?void 0:He.timestamp)||0}}),...J.map(D=>{var Ne,Ie,Re,De,He;return{id:`acp:${D.type}:${D.workspace||""}`,label:((Ne=D.activeChat)==null?void 0:Ne.title)||D.acpName,kind:"acp",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:fs(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((He=(De=(Re=(Ie=D.activeChat)==null?void 0:Ie.messages)==null?void 0:Re.at)==null?void 0:De.call(Re,-1))==null?void 0:He.timestamp)||0}})].sort((D,Ne)=>(Ne.lastLaunchedAt||0)-(D.lastLaunchedAt||0)),de=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(D=>({id:D.id,label:D.title||D.providerName||D.providerType,kind:D.kind,providerType:D.providerType,providerSessionId:D.providerSessionId,subtitle:fs(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace,summaryMetadata:D.summaryMetadata,lastLaunchedAt:D.lastLaunchedAt})):ee,we=i.useMemo(()=>{var Ne;const D=((Ne=l.connectionStates)==null?void 0:Ne[t||""])||void 0;return d.filter(Ie=>Ie.daemonId===t&&Ie.type!=="adhdev-daemon").flatMap(Ie=>no(Ie,{connectionStates:t&&D?{[t]:D}:void 0,defaultConnectionState:D})).filter(Ie=>!(Ie.transport==="pty"&&Ie.mode==="terminal")).sort((Ie,Re)=>xa(Re)-xa(Ie))},[d,l.connectionStates,t]),ue=i.useCallback(D=>{const Ne=Ya(D);Ne&&r(Yt(Ne))},[r]),xe=i.useCallback(()=>{g.current&&(S(!0),g.current().finally(()=>{g.current=null,S(!1),T(null)}))},[]),se=i.useCallback(D=>{if(!E)return;const{options:Ne,selectedKey:Ie}=cs({machine:E,currentWorkspacePath:D.workspace}),Re=async()=>{A(D.kind),h("workspace")};g.current=async()=>{const De=Ne.find(Qe=>Qe.key===k.current),He=(De==null?void 0:De.workspacePath)??null,Ue=(De==null?void 0:De.workspaceId)??null;if(D.kind==="ide"&&D.providerType){await P.handleLaunchIde(D.providerType,He?{workspace:He}:void 0);return}if((D.kind==="cli"||D.kind==="acp")&&D.providerType){await P.runLaunchCliCore({cliType:D.providerType,dir:Ue?void 0:He||"",workspaceId:Ue||void 0,model:D.kind==="acp"&&uc(D.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:D.providerSessionId});return}await Re()},k.current=Ie,K(Ie),T({title:D.kind==="ide"?ns("restart-ide",D.label):D.providerSessionId?to(D.label):ns("start-fresh",D.label),description:D.kind==="ide"?as("restart-ide"):D.providerSessionId?so():as("start-fresh"),confirmLabel:D.kind==="ide"?Ls("restart-ide"):D.providerSessionId?tn(!0):Ls("start-fresh"),busyLabel:D.kind==="ide"?Rs("restart-ide"):D.providerSessionId?Za(!0):Rs("start-fresh"),workspaceOptions:Ne,details:[{label:"Mode",value:D.kind.toUpperCase()},...D.providerType?[{label:"Provider",value:D.providerType}]:[]]})},[P,E]);if(i.useEffect(()=>{h(ae)},[le,ae,t]),i.useEffect(()=>{ge&&A(ge)},[ge,t]),!E)return f?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:U,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 ie=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Tt,{size:14})," Workspace"]}),count:$.length+F.length+J.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(on,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(nu,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(tu,{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:U,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[P.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:P.nicknameInput,onChange:D=>P.setNicknameInput(D.target.value),onKeyDown:D=>{D.key==="Enter"&&P.handleSaveNickname(),D.key==="Escape"&&P.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:P.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>P.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{P.setEditingNickname(!0),P.setNicknameInput(E.machineNickname||"")},title:"Click to set nickname",children:he}),y?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),l.retryConnection&&t&&s.jsx("button",{onClick:()=>l.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:[E.platform," · ",E.arch]}),s.jsxs("span",{children:[E.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),E.p2p.available&&s.jsxs("span",{children:["P2P ",E.p2p.state==="connected"?"connected":E.p2p.state]}),E.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:E.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ie.map(D=>s.jsxs("button",{onClick:()=>h(D.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${N===D.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[D.label,D.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${N===D.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:D.count})]},D.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[N==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(ny,{machineEntry:u,providers:C,recentLaunches:de,currentConversations:we,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",{})}catch{}},onOpenRecent:se,onOpenConversation:ue}),s.jsx(cy,{machine:E,machineId:t,providers:C,ideSessions:$,cliSessions:F,acpSessions:J,actions:P,getIcon:W,initialCategory:v,initialWorkspaceId:be,initialWorkspacePath:X,sendDaemonCommand:a,onOpenGitDialog:b})]}),N==="providers"&&s.jsx(pg,{machineId:t,providers:C,sendDaemonCommand:a}),N==="overview"&&s.jsx(ag,{machineId:t,machine:E,ideSessions:$,cliSessions:F,acpSessions:J,actions:P,sendDaemonCommand:a}),N==="session-host"&&s.jsx(sy,{machineId:t,cliSessions:F,sendDaemonCommand:a}),N==="logs"&&s.jsx(Yg,{machineId:t,sendDaemonCommand:a})]})})}),P.launchPick&&E&&s.jsx(ry,{machine:E,launchPick:P.launchPick,actions:P}),M&&s.jsx(mo,{title:M.title,description:M.description,details:M.details,workspaceOptions:M.workspaceOptions,selectedWorkspaceKey:w,onWorkspaceChange:D=>{k.current=D,K(D)},confirmLabel:M.confirmLabel,busyLabel:M.busyLabel,busy:R,onConfirm:xe,onCancel:()=>{g.current=null,T(null)}}),j&&s.jsx(Hl,{daemonId:j.daemonId,workspace:j.workspace,onClose:()=>x(null)}),s.jsx(qc,{toasts:l.toasts||[],onDismiss:D=>l.setToasts(Ne=>Ne.filter(Ie=>Ie.id!==D)),onClickToast:D=>{D.targetKey&&r(Yt(D.targetKey))}}),s.jsx("style",{children:`
87
+ `)}function Og(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Wg(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Fg({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:c,searchQuery:l,daemonLoading:d,traceLoading:f,daemonFetchError:u,traceFetchError:p}){const m=gg(n,o),y=wg(e,l),N=Sg(t,l),h=Ng(m,l),j=Cg(a,l),x=Og(y,c),b=c==="all"?N:[],v=Wg(h,c),A=c==="issues"?[]:j,g=Tg({daemonLogs:y,daemonRawLines:N,trace:h,webEvents:j}),M=Dg({daemonLogs:x,daemonRawLines:b,trace:v,webEvents:A}),T=$g(M),k=Ig({daemonLoading:d,traceLoading:f,daemonFetchError:u,traceFetchError:p,daemonLogKind:r,daemonLogsCount:y.length,daemonRawLineCount:N.length,traceCount:h.length,webEventCount:j.length});return{filteredDaemonLogs:y,filteredDaemonRawLines:N,filteredTraceEntries:h,filteredWebEvents:j,visibleDaemonLogs:x,visibleDaemonRawLines:b,visibleTraceEntries:v,visibleWebEvents:A,quickFilterCounts:g,diagnosticEvents:M,diagnosticsSummary:T,sourceStates:k}}function Hg(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function zl(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function Ta(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 Xn(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 bo(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function Ug({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Ta(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:zl(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:bo(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 zg({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:c,onCopyVisible:l,onToggleAutoRefresh:d,onRefresh:f,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(p=>s.jsx("button",{type:"button",onClick:()=>a(p.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===p.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:p.label},p.id))}),s.jsx("input",{value:r,onChange:p=>o(p.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:l,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:f,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function Vg({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:xg.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 Gg({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:c,traceFetchError:l}){var u,p;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((p=e.latestIssue)==null?void 0:p.severity)==="warn"?"warning":"good",f=c||l?"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 ${Xn(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 ${Xn(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:[bo(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:zl(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 ${Xn(f)}`,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:c||l?"Needs attention":o?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",Hg(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(m=>s.jsxs("div",{children:[m.label,": ",m.status]},m.id))})]})]})}function qg({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()," · ",bo(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function Yg({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:c,visibleWebEvents:l,quickFilter:d,searchQuery:f}){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(Ug,{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,p)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${p}`)),e.daemonLogKind!=="text"&&a.map((u,p)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Ta(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-${p}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(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:[c.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&&c.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&c.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&c.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:f.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."}),c.map(u=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Ta(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:_s(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:[l.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:[l.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:f.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),l.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:_s(u.payload,360)||"No payload"})]},u.id))]})]})]})}function Xg({machineId:e,sendDaemonCommand:t}){const r=Ag({machineId:e,sendDaemonCommand:t}),[n,a]=i.useState("info"),[o,c]=i.useState(""),[l,d]=i.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),f=i.useRef(null),u=i.useRef(!1),p=i.useMemo(()=>Fg({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&&p.diagnosticEvents.length>0){const N=u.current?"smooth":"instant";setTimeout(()=>{var h;(h=f.current)==null||h.scrollIntoView({behavior:N}),u.current=!0},50)}},[p.diagnosticEvents.length,r.autoRefresh]);const m=i.useCallback(async()=>{var h;const N=Mg({daemonLogs:p.visibleDaemonLogs,daemonRawLines:p.visibleDaemonRawLines,trace:p.visibleTraceEntries,webEvents:p.visibleWebEvents});if(!N.trim()){rt.showToast("No visible logs to copy.","info");return}try{await((h=navigator.clipboard)==null?void 0:h.writeText(N)),rt.showToast("Copied visible logs to clipboard.","success")}catch(j){rt.showToast(j instanceof Error?j.message:"Could not copy visible logs","warning")}},[p.visibleDaemonLogs,p.visibleDaemonRawLines,p.visibleTraceEntries,p.visibleWebEvents]),y=i.useCallback(async()=>{var h;const N=Kg({events:p.diagnosticEvents,summary:p.diagnosticsSummary,sources:p.sourceStates});try{await((h=navigator.clipboard)==null?void 0:h.writeText(N)),rt.showToast("Copied diagnostic bundle to clipboard.","success")}catch(j){rt.showToast(j instanceof Error?j.message:"Could not copy diagnostic bundle","warning")}},[p.diagnosticEvents,p.diagnosticsSummary,p.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(zg,{quickFilter:n,quickFilterCounts:p.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:c,onCopyDiagnostics:()=>{y()},onCopyVisible:()=>{m()},onToggleAutoRefresh:()=>r.setAutoRefresh(N=>!N),onRefresh:r.refresh,onClear:r.clear}),s.jsx(Vg,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(Gg,{diagnosticsSummary:p.diagnosticsSummary,diagnosticEventsCount:p.diagnosticEvents.length,sourceStates:p.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(qg,{patterns:p.diagnosticsSummary.repeatedPatterns}),s.jsx(Yg,{streams:r,sectionsOpen:l,setSectionsOpen:d,diagnosticEvents:p.diagnosticEvents,visibleDaemonLogs:p.visibleDaemonLogs,visibleDaemonRawLines:p.visibleDaemonRawLines,visibleTraceEntries:p.visibleTraceEntries,visibleWebEvents:p.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:f})]})}function Jg(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 Vl(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 Qg(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const c=String((o==null?void 0:o.lifecycle)||"").trim(),l=Vl((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(c)?t.push(o):(c==="stopped"||c==="failed")&&(d||l)?r.push(o):n.push(o)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function Zg(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Jn(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 Qn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Zn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function _i(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 ey(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function ty(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 sy(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 ry({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=i.useState(""),[o,c]=i.useState(null),[l,d]=i.useState(!1),f=wh(e,{enabled:!!e,includeSessions:!0,limit:Uo,intervalMs:bm}),u=f.diagnostics,p=f.loading,m=f.applyDiagnostics,y=i.useMemo(()=>Jg({diagnostics:u,loading:p,refreshing:l,error:n}),[u,p,l,n]),N=i.useMemo(()=>new Map(t.map(R=>[R.sessionId||R.id,R])),[t]),h=i.useCallback(async()=>{if(e){d(!0);try{const R=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Uo}),S=Qn(R);if(!(S!=null&&S.success))throw new Error((S==null?void 0:S.error)||"Could not load hosted runtime diagnostics");m(S.diagnostics||S.result||null),a("")}catch(R){const S=R instanceof Error?R.message:"Could not load hosted runtime diagnostics";a(S)}finally{d(!1)}}},[m,e,r]);i.useEffect(()=>{!e||u||p||l||h()},[u,p,e,h,l]);const j=i.useCallback(async(R,S)=>{const O=`${R}:${S.sessionId}`;if(!(R==="session_host_stop_session"&&!window.confirm(`Stop ${S.displayName}?
88
+ This will terminate the hosted runtime.`))){c(O);try{const H=await r(e,R,{sessionId:S.sessionId}),P=Qn(H);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Session host action failed");const C=R==="session_host_resume_session"?"resumed":R==="session_host_restart_session"?"restarted":"stopped";rt.showToast(`Session host ${C}: ${S.displayName}`,"success"),await h()}catch(H){const P=H instanceof Error?H.message:"Session host action failed";rt.showToast(P,"warning"),a(P)}finally{c(H=>H===O?null:H)}}},[e,h,r]),x=i.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
89
+ The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const S=await r(e,"session_host_prune_duplicate_sessions",{}),O=Qn(S);if(!(O!=null&&O.success))throw new Error((O==null?void 0:O.error)||"Duplicate prune failed");const H=O.result||{},P=Array.isArray(H.prunedSessionIds)?H.prunedSessionIds.length:0,C=typeof H.duplicateGroupCount=="number"?H.duplicateGroupCount:0;rt.showToast(`Pruned ${P} duplicate runtime(s) across ${C} group(s)`,"success"),await h()}catch(S){const O=S instanceof Error?S.message:"Duplicate prune failed";rt.showToast(O,"warning"),a(O)}finally{c(S=>S==="session_host_prune_duplicate_sessions"?null:S)}}},[e,h,r]),b=i.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((R,S)=>(S.lastActivityAt||0)-(R.lastActivityAt||0)),[u==null?void 0:u.sessions]),v=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)||[]}:Qg(b),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,b]),A=v.liveRuntimes,g=v.recoverySnapshots,M=v.inactiveRecords,T=i.useMemo(()=>sy(A),[A]),k=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(R=>R.level==="warn"||R.level==="error")||null,[u==null?void 0:u.recentLogs]),K=(R,S)=>{var z;const O=o===`session_host_resume_session:${R.sessionId}`,H=o===`session_host_restart_session:${R.sessionId}`,P=o===`session_host_stop_session:${R.sessionId}`,C=Vl(R.meta),I=N.get(R.sessionId),W=R.attachedClients.length===1?"1 client":`${R.attachedClients.length} clients`,E=S==="recovery"?"Recover":"Resume",$=Zg(S);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:R.displayName||(I==null?void 0:I.cliName)||R.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${ty(R.lifecycle)}`,children:R.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:R.workspaceLabel||(I==null?void 0:I.runtimeWorkspaceLabel)||R.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:R.runtimeKey}),R.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",R.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((z=R.writeOwner)==null?void 0:z.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:ey(R.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(qi,{size:11})," ",W]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",_i(R.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",$]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[S==="recovery"&&(R.lifecycle==="interrupted"||R.lifecycle==="failed"||R.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{j("session_host_resume_session",R)},children:O?`${E}ing…`:E}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{j("session_host_restart_session",R)},children:H?"Restarting…":"Restart"}),S==="live"&&(R.lifecycle==="running"||R.lifecycle==="starting"||R.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:()=>{j("session_host_stop_session",R)},children:P?"Stopping…":"Stop"})]})]})},R.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(us,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Tp()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[T>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{x()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${T})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${y.toneClass}`,children:y.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{h()},disabled:p||l,children:[s.jsx(lr,{size:13}),p||l?"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(nr,{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:g.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:_i(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Zn(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(nr,{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:[Zn(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(Ea,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Jn("live")}),A.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:A.map(R=>K(R,"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(us,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Jn("recovery")}),g.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:g.map(R=>K(R,"recovery"))})]}),M.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:Jn("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:M.map(R=>K(R,"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"}),k.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:k.map(R=>{var O;const S=b.find(H=>H.sessionId===R.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:(S==null?void 0:S.displayName)||((O=N.get(R.sessionId))==null?void 0:O.cliName)||R.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[R.action,R.lifecycle?` · ${R.lifecycle}`:"",R.detail?` · ${R.detail}`:"",R.error?` · ${R.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${R.success===!1?"text-red-300":"text-text-secondary"}`,children:Zn(R.timestamp)})]},`${R.sessionId}:${R.timestamp}:${R.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 ny({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 ea({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 ta({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 ay({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:c}){const l=n.slice(0,6),d=r.slice(0,4),u=Zs(e,"0.9.60");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:[l.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(ea,{icon:s.jsx(Ut,{size:13}),children:"Current Chats"}),s.jsx(ta,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(p=>{const m=xa(p);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>c(p),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:it(p)}),m>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:ln(m)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:As(p)})]},p.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(ea,{icon:s.jsx(Qi,{size:13}),children:"Recent Launches"}),s.jsx(ta,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(p=>{const{metaText:m,updatedLabel:y}=Nl(p);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>o(p),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:p.label}),y&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:y})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:m})]},p.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(ea,{icon:s.jsx(nr,{size:13}),children:"Daemon Update"}),s.jsx(ta,{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:u?"Daemon update required":"Version mismatch detected"}),s.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:u?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),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(lr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function oy(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function iy({machine:e,selectedWorkspace:t,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:o,onCustomPathChange:c,onOpenBrowseDialog:l}){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 f=d.target.value;if(o(f),f==="__custom__"&&a){l();return}f!=="__custom__"&&c("")},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?"⭐ ":"",un(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:l,children:"Select workspace…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:n,onChange:d=>c(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 cy={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 _r(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function sa({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:o,actions:c,sendDaemonCommand:l,initialWorkspaceId:d,initialWorkspacePath:f,onOpenGitDialog:u}){const p=Ps(),{handleLaunchIde:m,handleStopCli:y,handleRestartIde:N,handleStopIde:h,handleDetectIdes:j,launchingIde:x,launchingAgentType:b,addLog:v}=c,[A,g]=i.useState(null),M=i.useCallback(B=>{B&&p(Yt(B))},[p]),T=cy[e],k=e==="ide",w=e==="acp",K=i.useMemo(()=>n.filter(B=>ps(B,e)),[e,n]),R=i.useMemo(()=>new Map(K.map(B=>[B.type,B.displayName||B.type])),[K]),[S,O]=i.useState(""),[H,P]=i.useState(""),[C,I]=i.useState([]),[W,E]=i.useState(""),[$,z]=i.useState(""),[J,he]=i.useState([]),[ce,te]=i.useState(!1),[ye,fe]=i.useState(!1),[be,X]=i.useState(""),[ae,ge]=i.useState(!1),[ee,de]=i.useState(()=>xt()),[we,ue]=i.useState(null),[xe,se]=i.useState(f?"__custom__":d||t.defaultWorkspaceId||""),[ie,re]=i.useState(f||""),[q,Y]=i.useState([]),[le,ke]=i.useState(!1),[Z,Ce]=i.useState(""),[Ee,We]=i.useState([]),[Fe,D]=i.useState(!1),[Se,Ae]=i.useState(""),Le=i.useRef(null),[Pe,He]=i.useState(null),Ue=i.useRef("__home__"),[Qe,lt]=i.useState("__home__"),[dt,ut]=i.useState(!1),Te=i.useRef(0),Ge=q.filter(B=>!a.some(oe=>oe.type===B&&yt(oe.status)!=="stopped")),Ze=i.useRef({});i.useEffect(()=>{t.defaultWorkspaceId&&!xe&&se(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),i.useEffect(()=>{if(f){se("__custom__"),re(f);return}d&&(se(d),re(""))},[d,f]),i.useEffect(()=>{k||S&&(K.some(B=>B.type===S)||(O(""),z("")))},[K,k,S]);const qe=(()=>{if(xe==="__custom__")return ie.trim();if(!xe)return"";const B=(t.workspaces||[]).find(oe=>oe.id===xe);return(B==null?void 0:B.path)||""})(),tt=i.useCallback(B=>{const oe=Ze.current[B];oe&&(clearTimeout(oe),delete Ze.current[B]),Y(pe=>pe.includes(B)?pe.filter(Ke=>Ke!==B):pe)},[]),F=i.useRef(new Set),V=i.useCallback(async B=>{if(l){D(!0),Ae("");try{const oe=await xn(l,r,B);Ce(oe.path),re(oe.path),We(oe.directories)}catch(oe){Ae(oe instanceof Error?oe.message:"Could not load folder")}finally{D(!1)}}},[r,l]),L=i.useCallback(()=>{if(!l)return;se("__custom__"),ke(!0);const B=a.map(pe=>pe.workspace),oe=hn(t.platform,pn(ie.trim(),qe,f,B,t.defaultWorkspacePath,(t.workspaces||[]).map(pe=>pe.path)));V(oe)},[ie,f,V,t.defaultWorkspacePath,t.platform,t.workspaces,a,qe,l]),G=i.useCallback(B=>{const oe=String(B.workspace||"").trim();if(!oe)return;const pe=(t.workspaces||[]).find(Ke=>_r(Ke.path)===_r(oe));if(pe){se(pe.id),re("");return}se("__custom__"),re(oe)},[t.workspaces]),_=i.useCallback(B=>{const oe=String(B.workspace||"").trim();if(!oe)return{workspaceId:null,workspacePath:"",useHome:!0};const pe=(t.workspaces||[]).find(Ke=>_r(Ke.path)===_r(oe));return pe?{workspaceId:pe.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:oe,useHome:!1}},[t.workspaces]),U=i.useCallback(async B=>{if(!l||!B||e!=="cli"){he([]),te(!1),fe(!1),X("");return}const oe=Te.current+1;Te.current=oe,te(!0),X("");try{const pe=await l(r,"list_saved_sessions",{providerType:B,kind:"cli",limit:30});if(Te.current!==oe)return;const Ke=(pe==null?void 0:pe.result)??pe;he(Array.isArray(Ke==null?void 0:Ke.sessions)?Ke.sessions:[])}catch(pe){if(Te.current!==oe)return;he([]),X(pe instanceof Error?pe.message:"Could not load saved sessions")}finally{Te.current===oe&&(te(!1),fe(!0))}},[e,r,l]),Q=i.useMemo(()=>{if(e!=="cli"||!S)return null;const B=R.get(S)||S;return{routeId:r,daemonId:r,providerSessionId:$||void 0,transport:"pty",mode:"chat",agentName:B,agentType:S,status:"idle",title:B,messages:[],ideType:S,workspaceName:qe,workspacePath:qe,displayPrimary:B,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${S}`}},[e,r,R,qe,$,S]),ne=i.useCallback(B=>{if(e==="ide"||!B){I([]);return}I(Kl(r,B))},[e,r]);i.useEffect(()=>{Te.current+=1,z(""),ne(S),fe(!1),he([]),X(""),te(!1)},[e,ne,U,S]);const ve=i.useMemo(()=>J.find(B=>B.providerSessionId===$)||null,[J,$]);i.useEffect(()=>{if(!$)return;const B=J.find(oe=>oe.providerSessionId===$);B!=null&&B.canResume||z("")},[J,$]);const Me=i.useCallback((B,oe)=>{Le.current=oe,Ue.current=B.selectedWorkspaceKey||"__home__",lt(B.selectedWorkspaceKey||"__home__"),He(B)},[]),_e=i.useCallback(()=>{Le.current&&(ut(!0),Le.current().finally(()=>{Le.current=null,ut(!1),He(null)}))},[]),Ne=i.useCallback(B=>{if(!B)return;Y(pe=>pe.includes(B)?pe:[...pe,B]);const oe=Ze.current[B];oe&&clearTimeout(oe),Ze.current[B]=setTimeout(()=>{Y(pe=>pe.includes(B)?pe.filter(Ke=>Ke!==B):pe),delete Ze.current[B]},2e4)},[]);i.useEffect(()=>{for(const oe of a)yt(oe.status)!=="stopped"&&(q.includes(oe.type)&&!F.current.has(oe.type)&&(F.current.add(oe.type),v("info",`${R.get(oe.type)||oe.type} launched`,!0)),tt(oe.type));const B=new Set(a.filter(oe=>yt(oe.status)!=="stopped").map(oe=>oe.type));F.current.forEach(oe=>{!q.includes(oe)&&!B.has(oe)&&F.current.delete(oe)})},[v,tt,a,q,R]),i.useEffect(()=>()=>{Object.values(Ze.current).forEach(clearTimeout),Ze.current={}},[]);const[De,Be]=i.useState({}),[Re,ze]=i.useState(null);i.useEffect(()=>{if(!k||!r||!l)return;(async()=>{try{const oe=await l(r,"get_ide_extensions",{}),pe=(oe==null?void 0:oe.result)||oe;pe!=null&&pe.success&&(pe!=null&&pe.ideExtensions)&&Be(pe.ideExtensions)}catch{}})()},[k,r,l]);const Je=B=>k?at(B.type):e==="cli"?B.cliName:B.acpName,ft=k?t.detectedIdes||[]:[],pt=i.useCallback(async B=>{const oe=(B==null?void 0:B.type)||S,pe=(B==null?void 0:B.workspacePath)??qe;if(k){await m(oe,pe?{workspace:pe}:void 0)&&Ne(oe);return}const Ke=await c.runLaunchCliCore({cliType:oe,dir:B!=null&&B.workspaceId?void 0:pe||void 0,workspaceId:(B==null?void 0:B.workspaceId)||void 0,useHome:(B==null?void 0:B.useHome)||!(B!=null&&B.workspaceId)&&!pe,argsStr:(B==null?void 0:B.argsStr)??(H||void 0),model:(B==null?void 0:B.model)??(w&&W||void 0),resumeSessionId:(B==null?void 0:B.resumeSessionId)||!w&&e==="cli"&&oe===S&&$||void 0});if(Ke.success||Ke.pending){const Ie=(B==null?void 0:B.argsStr)??H;!k&&(Ie!=null&&Ie.trim())&&(Ol(r,oe,Ie),ne(oe)),Ne(oe),Ke.success&&Ke.sessionId&&M(Ke.sessionId)}},[c,m,w,k,H,W,ne,Ne,r,M,qe,$,S]),ht=Gc(k?"ide":w?"acp":"cli",!k&&!w&&!!$),me=qc(k?"ide":w?"acp":"cli",!k&&!w&&!!$),je=()=>{var Ie;const B=k?at(S):R.get(S)||S,oe=!k&&!w&&!!$,{options:pe,selectedKey:Ke}=cs({machine:t,currentWorkspaceId:xe&&xe!=="__custom__"?xe:null,currentWorkspacePath:qe});Me({title:oe?to(B):ns("start-fresh",B),description:oe?so():as("start-fresh"),confirmLabel:ht,busyLabel:me,workspaceOptions:pe,selectedWorkspaceKey:Ke,details:[{label:"Mode",value:T.label},{label:"Provider",value:B},...!k&&e==="cli"&&$?[{label:"Resume",value:((Ie=J.find($e=>$e.providerSessionId===$))==null?void 0:Ie.title)||$}]:[],...!k&&H.trim()?[{label:"Arguments",value:H.trim()}]:[],...w&&W.trim()?[{label:"Model",value:W.trim()}]:[]]},async()=>{const $e=pe.find(nt=>nt.key===Ue.current);$e!=null&&$e.workspaceId?(se($e.workspaceId),re("")):$e!=null&&$e.workspacePath?(se("__custom__"),re($e.workspacePath)):(se(""),re("")),await pt({workspaceId:($e==null?void 0:$e.workspaceId)??null,workspacePath:($e==null?void 0:$e.workspacePath)??"",useHome:!($e!=null&&$e.workspaceId)&&!($e!=null&&$e.workspacePath)})})},wt=B=>{k?h(B):y(B.type,B.workspace,B.id)},bt=i.useCallback(async(B,oe,pe=!1)=>{if(B.mode===oe){pe&&B.sessionId&&M(B.sessionId);return}if(!l||!B.sessionId){pe&&B.sessionId&&M(B.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:B.sessionId,cliType:B.type,mode:oe}),pe&&M(B.sessionId)}catch(Ke){const Ie=pl(Ke);ml(Ke)?console.warn(Ie?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Ke instanceof Error?Ke.message:String(Ke)):console.error("Failed to switch CLI view mode:",Ke)}},[r,M,l]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${T.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 ",T.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:k?ft.length>0?ft.map(B=>{const oe=a.find(nt=>(nt.type||"").toLowerCase()===(B.type||"").toLowerCase()&&yt(nt.status)!=="stopped"),pe=B.running||!!oe,Ke=!!oe&&oe.cdpConnected,Ie=q.includes(B.type||B.id||""),$e=S===(B.type||"");return s.jsxs("button",{onClick:()=>{if(Ke&&oe){const nt=oe.sessionId;nt?p(Yt(nt),{state:{openRemoteForTabKey:nt}}):p("/dashboard",{state:{openRemoteForTabKey:oe.id}});return}Ie||O(nt=>nt===(B.type||"")?"":B.type||"")},disabled:!!x||Ie,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Ke?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":$e?"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:x&&x!==B.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(B.type)}),pe&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Ke?"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:B.name||at(B.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Ke?"text-green-400":Ie?"text-orange-400":$e?"text-accent-primary":"text-text-muted"}`,children:Ke?"Open Session":Ie?"Starting...":$e?"Configure":"Select"})]})]},B.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:j,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(nu,{size:14})," Scan System"]})]}):K.length>0?K.map(B=>{const oe=S===B.type,pe=q.includes(B.type),Ie=!!a.find($e=>$e.type===B.type&&yt($e.status)!=="stopped");return s.jsxs("button",{onClick:()=>O($e=>$e===B.type?"":B.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${oe?"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:B.icon}),Ie&&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:B.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${pe?"text-orange-400":oe?"text-accent-primary":"text-text-muted"}`,children:pe?"Starting...":oe?"Configure":"Select"})]})]},B.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."})]})}),S&&(k?ft.find(B=>B.type===S):K.find(B=>B.type===S))&&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:k?at(S):R.get(S)||S})]}),s.jsx(iy,{machine:t,selectedWorkspace:xe,resolvedWorkspacePath:qe,customPath:ie,canBrowse:!!l,onWorkspaceChange:se,onCustomPathChange:re,onOpenBrowseDialog:L}),!k&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&e==="cli"&&s.jsx(Fl,{busy:!!b||!!x||q.includes(S),savedSessionsLoading:ce,savedSessionsError:be,savedSessionsLoaded:ye,savedSessionsCount:J.length,selectedSession:ve,onRefresh:()=>void U(S),onOpenHistory:()=>{S&&(ge(!0),Wl({hasLoadedInitialResults:ye,isLoading:ce})&&U(S))},onClearSelection:()=>z("")}),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:W,onChange:B=>E(B.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:B=>P(B.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(B=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>P(B),title:B,children:B},B))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:je,disabled:!!b||!!x||q.includes(S),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:b===S||x===S?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+q.filter(B=>!a.some(oe=>oe.type===B&&yt(oe.status)!=="stopped")).length,")"]}),a.length===0&&Ge.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 ",T.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ge.map(B=>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(B)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:k?at(B):R.get(B)||B}),s.jsx("div",{className:"text-[11px] text-text-muted",children:b===B?"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:${B}`)),a.map(B=>{const oe=k?B:null,pe=!k&&!w?B:null,Ke=yt(B.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(B.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Je(B),(oe==null?void 0:oe.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",oe.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:B.workspace||"—"}),u&&B.git&&B.workspace?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:Ie=>{Ie.stopPropagation(),u(B.daemonId??r,B.workspace)},children:s.jsx(Is,{git:B.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Is,{git:B.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(pe==null?void 0:pe.mode)&&s.jsx("span",{className:pe.mode==="chat"?"text-violet-400":"text-text-secondary",children:pe.mode==="chat"?"Chat view":"Terminal view"})]}),pe&&(pe.runtimeKey||pe.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[pe.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 ",pe.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 Ie;(Ie=navigator.clipboard)==null||Ie.writeText(`adhdev attach ${pe.runtimeKey}`),g(pe.runtimeKey||null),window.setTimeout(()=>{g($e=>$e===pe.runtimeKey?null:$e)},1200)},children:A===pe.runtimeKey?"Copied":"Copy"})]}),pe.runtimeWriteOwner&&s.jsx("span",{style:{color:pe.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:pe.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:oy(pe.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 ${Ke==="stopped"?"bg-red-500/[0.08] text-red-500":Ke==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Ke}),k&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Ie=B.sessionId;if(Ie){p(Yt(Ie),{state:{openRemoteForTabKey:Ie}});return}p("/dashboard",{state:{openRemoteForTabKey:B.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(Tt,{size:13})}),s.jsx("button",{onClick:()=>{const Ie=B.workspace||"",{options:$e,selectedKey:nt}=cs({machine:t,currentWorkspacePath:Ie});Me({title:ns("restart-ide",at(B.type)),description:as("restart-ide"),confirmLabel:Ls("restart-ide"),busyLabel:Rs("restart-ide"),workspaceOptions:$e,selectedWorkspaceKey:nt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:at(B.type)}]},async()=>{const jt=$e.find(Vt=>Vt.key===Ue.current),ct=(jt==null?void 0:jt.workspacePath)??"";if(ct&&ct!==Ie){await pt({type:B.type,workspacePath:ct});return}await N(B)})},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(lr,{size:14})})]}),w&&s.jsx("button",{onClick:()=>{const Ie=B.sessionId;Ie&&M(Ie)},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:!B.sessionId,children:s.jsx(Ut,{size:14})}),pe&&Ke!=="stopped"&&s.jsxs(s.Fragment,{children:[pe.mode&&s.jsx(Qa,{mode:pe.mode,onChange:Ie=>void bt(pe,Ie,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Ie=B.sessionId;Ie&&M(Ie)},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:!B.sessionId,children:pe.mode==="chat"?s.jsx(Ut,{size:14}):s.jsx(Tt,{size:13})})]}),Ke==="stopped"?s.jsx("button",{onClick:()=>{const Ie=B.workspace||"",$e=k?at(B.type):Je(B),{options:nt,selectedKey:jt}=cs({machine:t,currentWorkspacePath:Ie});Me({title:ns("restart-stopped",$e),description:as("restart-stopped"),confirmLabel:Ls("restart-stopped"),busyLabel:Rs("restart-stopped"),workspaceOptions:nt,selectedWorkspaceKey:jt,details:[{label:"Mode",value:T.label},{label:"Provider",value:$e}]},async()=>{const ct=nt.find(Vt=>Vt.key===Ue.current);await pt({type:B.type,workspaceId:(ct==null?void 0:ct.workspaceId)??null,workspacePath:(ct==null?void 0:ct.workspacePath)??"",useHome:!(ct!=null&&ct.workspaceId)&&!(ct!=null&&ct.workspacePath)})})},disabled:q.includes(B.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:q.includes(B.type)?"⏳":s.jsx($a,{size:14})}):s.jsx("button",{onClick:()=>wt(B),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(St,{size:14})})]})]}),oe&&oe.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:oe.aiAgents.map(Ie=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${cc(Ie.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Ie.name," · ",yt(Ie.status)]},Ie.id))}),oe&&(De[oe.type]||[]).length>0&&l&&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:(De[oe.type]||[]).map(Ie=>s.jsxs("button",{disabled:Re===`${oe.type}.${Ie.type}`,onClick:async()=>{const $e=`${oe.type}.${Ie.type}`;ze($e);try{await l(r,"set_ide_extension",{ideType:oe.type,extensionType:Ie.type,enabled:!Ie.enabled}),Be(nt=>({...nt,[oe.type]:(nt[oe.type]||[]).map(jt=>jt.type===Ie.type?{...jt,enabled:!jt.enabled}:jt)}))}catch(nt){console.error("Extension toggle failed:",nt)}finally{ze(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 ${Ie.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 ${Ie.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Ie.name,s.jsx("span",{className:"text-[9px] font-normal",children:Ie.enabled?"ON":"OFF"})]},Ie.type))})]})]},B.id)})]}),le&&l&&s.jsx(bn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:Z,directories:Ee,busy:Fe,error:Se,confirmLabel:"Use this folder",onClose:()=>ke(!1),onNavigate:B=>{V(B)},onConfirm:B=>{re(B),se("__custom__"),ke(!1)}}),Pe&&s.jsx(mo,{title:Pe.title,description:Pe.description,details:Pe.details,workspaceOptions:Pe.workspaceOptions,selectedWorkspaceKey:Qe,onWorkspaceChange:B=>{Ue.current=B,lt(B)},confirmLabel:Pe.confirmLabel,busyLabel:Pe.busyLabel,busy:dt,onConfirm:_e,onCancel:()=>{Le.current=null,He(null)}}),ae&&Q&&s.jsx(ro,{activeConv:Q,ides:[],isCreatingChat:!1,isRefreshingHistory:ce,savedSessions:J,isSavedSessionsLoading:ce,isResumingSavedSessionId:we,savedHistoryFilters:ee,missingWorkspaceResumePath:qe||null,onSavedHistoryFiltersChange:de,onClose:()=>ge(!1),onNewChat:()=>{z(""),ge(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{U(S)},onResumeSavedSession:B=>{if(!B.canResume||we)return;const oe=_(B);z(B.providerSessionId),G(B),ue(B.providerSessionId),ge(!1),pt({type:B.providerType,workspaceId:oe.workspaceId,workspacePath:oe.workspacePath,useHome:oe.useHome,resumeSessionId:B.providerSessionId}).finally(()=>{ue(pe=>pe===B.providerSessionId?null:pe)})}})]})}const Pi=[{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 ly({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:o,actions:c,getIcon:l,initialCategory:d="ide",initialWorkspaceId:f,initialWorkspacePath:u,sendDaemonCommand:p,onOpenGitDialog:m}){var j;const[y,N]=i.useState(d);i.useEffect(()=>{N(d)},[d]);const h=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:Pi.map(x=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${y===x.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>N(x.id),children:[s.jsx("span",{children:x.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${y===x.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:h[x.id]})]},x.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(j=Pi.find(x=>x.id===y))==null?void 0:j.helper})]}),y==="ide"&&s.jsx(sa,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:p,initialWorkspaceId:f,initialWorkspacePath:u,onOpenGitDialog:m}),y==="cli"&&s.jsx(sa,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:p,initialWorkspaceId:f,initialWorkspacePath:u,onOpenGitDialog:m}),y==="acp"&&s.jsx(sa,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:o,getIcon:l,actions:c,sendDaemonCommand:p,initialWorkspaceId:f,initialWorkspacePath:u,onOpenGitDialog:m})]})}function dy({onNicknameSynced:e}={}){var re,q,Y,le,ke,Z,Ce,Ee,We,Fe;const{id:t}=Md(),r=Ps(),n=La(),{sendCommand:a}=mt(),o=fr(),c=ll(),l=Kc(),d=l.ides||[],f=l.initialLoaded??!0,u=d.find(D=>D.id===t&&D.type==="adhdev-daemon"),p=d.some(D=>D.type==="adhdev-daemon"),m=t?(re=l.connectionRetryStatuses)==null?void 0:re[t]:void 0,y=!!(m!=null&&m.blocked),[N,h]=i.useState("workspace"),[j,x]=i.useState(null),b=i.useCallback((D,Se)=>{x({daemonId:D,workspace:Se})},[]),[v,A]=i.useState("ide"),g=i.useRef(null),[M,T]=i.useState(null),k=i.useRef("__home__"),[w,K]=i.useState("__home__"),[R,S]=i.useState(!1),O=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||N!=="overview")return;const D=u.machine;(typeof(D==null?void 0:D.cpus)!="number"||typeof(D==null?void 0:D.totalMem)!="number"||typeof(D==null?void 0:D.arch)!="string"||typeof(D==null?void 0:D.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[N,c,u,t]),vh(t&&N==="overview"?[t]:[],{enabled:N==="overview",intervalMs:mm});const H=()=>{if(p){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},P=ag({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:O});i.useEffect(()=>rt.onToast(Se=>{l.setToasts(Le=>{if(Le.some(Ue=>Ue.message===Se.message&&Se.timestamp-Ue.timestamp<3e3))return Le;const He={id:Se.id,message:Se.message,type:Se.type,timestamp:Se.timestamp,targetKey:Se.targetKey,actions:Se.actions};return[...Le.slice(-4),He]});const Ae=Se.duration||5e3;setTimeout(()=>l.setToasts(Le=>Le.filter(Pe=>Pe.id!==Se.id)),Ae)}),[l]);const C=(u==null?void 0:u.availableProviders)||[],I={};for(const D of C)I[D.type]=D.icon;const W=D=>I[D]||"",E=u?{id:u.id,hostname:lc(u,{fallbackId:u.id}),platform:((q=u.machine)==null?void 0:q.platform)||"unknown",arch:((Y=u.machine)==null?void 0:Y.arch)||"",cpus:((le=u.machine)==null?void 0:le.cpus)||0,totalMem:((ke=u.machine)==null?void 0:ke.totalMem)||0,freeMem:(Z=u.machine)==null?void 0:Z.freeMem,availableMem:(Ce=u.machine)==null?void 0:Ce.availableMem,loadavg:(Ee=u.machine)==null?void 0:Ee.loadavg,uptime:(We=u.machine)==null?void 0:We.uptime,release:((Fe=u.machine)==null?void 0:Fe.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,$=d.filter(D=>D.daemonId===t&&D.type!=="adhdev-daemon").filter(D=>!or(D)&&!js(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,version:D.version||"",instanceId:D.instanceId||"",status:D.status,workspace:D.workspace||null,terminals:D.terminals||0,aiAgents:of(D.aiAgents||(D.agents||[]).map(Se=>({id:Se.name,name:Se.name,status:Se.status,version:Se.version}))),activeChat:D.activeChat||null,chats:D.chats||[],childSessions:D.childSessions||[],cdpConnected:D.cdpConnected||!1,daemonId:t})),z=d.filter(D=>D.daemonId===t&&or(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,cliName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,mode:D.mode,runtimeKey:D.runtimeKey,runtimeDisplayName:D.runtimeDisplayName,runtimeWorkspaceLabel:D.runtimeWorkspaceLabel,runtimeWriteOwner:D.runtimeWriteOwner||null,runtimeAttachedClients:D.runtimeAttachedClients||[],daemonId:t})),J=d.filter(D=>D.daemonId===t&&js(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,acpName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,daemonId:t})),he=u?Ct(u,{fallbackId:t}):"",ce="workspace",te=n.state,ye=te==null?void 0:te.initialMachineTab,fe=te==null?void 0:te.initialWorkspaceCategory,be=te==null?void 0:te.initialWorkspaceId,X=te==null?void 0:te.initialWorkspacePath,ae=ye==="ides"||ye==="clis"||ye==="acps"?"workspace":ye||ce,ge=ye==="ides"?"ide":ye==="clis"?"cli":ye==="acps"?"acp":fe,ee=[...$.map(D=>{var Se,Ae,Le,Pe,He;return{id:`ide:${D.type}:${D.workspace||""}`,label:((Se=D.activeChat)==null?void 0:Se.title)||D.type,kind:"ide",providerType:D.type,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((He=(Pe=(Le=(Ae=D.activeChat)==null?void 0:Ae.messages)==null?void 0:Le.at)==null?void 0:Pe.call(Le,-1))==null?void 0:He.timestamp)||0}}),...z.map(D=>{var Se,Ae,Le,Pe,He;return{id:`cli:${D.type}:${D.workspace||""}`,label:((Se=D.activeChat)==null?void 0:Se.title)||D.cliName,kind:"cli",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((He=(Pe=(Le=(Ae=D.activeChat)==null?void 0:Ae.messages)==null?void 0:Le.at)==null?void 0:Pe.call(Le,-1))==null?void 0:He.timestamp)||0}}),...J.map(D=>{var Se,Ae,Le,Pe,He;return{id:`acp:${D.type}:${D.workspace||""}`,label:((Se=D.activeChat)==null?void 0:Se.title)||D.acpName,kind:"acp",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:fs(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((He=(Pe=(Le=(Ae=D.activeChat)==null?void 0:Ae.messages)==null?void 0:Le.at)==null?void 0:Pe.call(Le,-1))==null?void 0:He.timestamp)||0}})].sort((D,Se)=>(Se.lastLaunchedAt||0)-(D.lastLaunchedAt||0)),de=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(D=>({id:D.id,label:D.title||D.providerName||D.providerType,kind:D.kind,providerType:D.providerType,providerSessionId:D.providerSessionId,subtitle:fs(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace,summaryMetadata:D.summaryMetadata,lastLaunchedAt:D.lastLaunchedAt})):ee,we=i.useMemo(()=>{var Se;const D=((Se=l.connectionStates)==null?void 0:Se[t||""])||void 0;return d.filter(Ae=>Ae.daemonId===t&&Ae.type!=="adhdev-daemon").flatMap(Ae=>no(Ae,{connectionStates:t&&D?{[t]:D}:void 0,defaultConnectionState:D})).filter(Ae=>!(Ae.transport==="pty"&&Ae.mode==="terminal")).sort((Ae,Le)=>xa(Le)-xa(Ae))},[d,l.connectionStates,t]),ue=i.useCallback(D=>{const Se=Ya(D);Se&&r(Yt(Se))},[r]),xe=i.useCallback(()=>{g.current&&(S(!0),g.current().finally(()=>{g.current=null,S(!1),T(null)}))},[]),se=i.useCallback(D=>{if(!E)return;const{options:Se,selectedKey:Ae}=cs({machine:E,currentWorkspacePath:D.workspace}),Le=async()=>{A(D.kind),h("workspace")};g.current=async()=>{const Pe=Se.find(Qe=>Qe.key===k.current),He=(Pe==null?void 0:Pe.workspacePath)??null,Ue=(Pe==null?void 0:Pe.workspaceId)??null;if(D.kind==="ide"&&D.providerType){await P.handleLaunchIde(D.providerType,He?{workspace:He}:void 0);return}if((D.kind==="cli"||D.kind==="acp")&&D.providerType){await P.runLaunchCliCore({cliType:D.providerType,dir:Ue?void 0:He||"",workspaceId:Ue||void 0,model:D.kind==="acp"&&uc(D.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:D.providerSessionId});return}await Le()},k.current=Ae,K(Ae),T({title:D.kind==="ide"?ns("restart-ide",D.label):D.providerSessionId?to(D.label):ns("start-fresh",D.label),description:D.kind==="ide"?as("restart-ide"):D.providerSessionId?so():as("start-fresh"),confirmLabel:D.kind==="ide"?Ls("restart-ide"):D.providerSessionId?tn(!0):Ls("start-fresh"),busyLabel:D.kind==="ide"?Rs("restart-ide"):D.providerSessionId?Za(!0):Rs("start-fresh"),workspaceOptions:Se,details:[{label:"Mode",value:D.kind.toUpperCase()},...D.providerType?[{label:"Provider",value:D.providerType}]:[]]})},[P,E]);if(i.useEffect(()=>{h(ae)},[ce,ae,t]),i.useEffect(()=>{ge&&A(ge)},[ge,t]),!E)return f?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 ie=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Tt,{size:14})," Workspace"]}),count:$.length+z.length+J.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(on,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(au,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(su,{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:[P.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:P.nicknameInput,onChange:D=>P.setNicknameInput(D.target.value),onKeyDown:D=>{D.key==="Enter"&&P.handleSaveNickname(),D.key==="Escape"&&P.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:P.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>P.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{P.setEditingNickname(!0),P.setNicknameInput(E.machineNickname||"")},title:"Click to set nickname",children:he}),y?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),l.retryConnection&&t&&s.jsx("button",{onClick:()=>l.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:[E.platform," · ",E.arch]}),s.jsxs("span",{children:[E.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),E.p2p.available&&s.jsxs("span",{children:["P2P ",E.p2p.state==="connected"?"connected":E.p2p.state]}),E.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:E.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ie.map(D=>s.jsxs("button",{onClick:()=>h(D.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${N===D.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[D.label,D.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${N===D.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:D.count})]},D.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[N==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(ay,{machineEntry:u,providers:C,recentLaunches:de,currentConversations:we,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",{})}catch{}},onOpenRecent:se,onOpenConversation:ue}),s.jsx(ly,{machine:E,machineId:t,providers:C,ideSessions:$,cliSessions:z,acpSessions:J,actions:P,getIcon:W,initialCategory:v,initialWorkspaceId:be,initialWorkspacePath:X,sendDaemonCommand:a,onOpenGitDialog:b})]}),N==="providers"&&s.jsx(hg,{machineId:t,providers:C,sendDaemonCommand:a}),N==="overview"&&s.jsx(og,{machineId:t,machine:E,ideSessions:$,cliSessions:z,acpSessions:J,actions:P,sendDaemonCommand:a}),N==="session-host"&&s.jsx(ry,{machineId:t,cliSessions:z,sendDaemonCommand:a}),N==="logs"&&s.jsx(Xg,{machineId:t,sendDaemonCommand:a})]})})}),P.launchPick&&E&&s.jsx(ny,{machine:E,launchPick:P.launchPick,actions:P}),M&&s.jsx(mo,{title:M.title,description:M.description,details:M.details,workspaceOptions:M.workspaceOptions,selectedWorkspaceKey:w,onWorkspaceChange:D=>{k.current=D,K(D)},confirmLabel:M.confirmLabel,busyLabel:M.busyLabel,busy:R,onConfirm:xe,onCancel:()=>{g.current=null,T(null)}}),j&&s.jsx(Ul,{daemonId:j.daemonId,workspace:j.workspace,onClose:()=>x(null)}),s.jsx(Yc,{toasts:l.toasts||[],onDismiss:D=>l.setToasts(Se=>Se.filter(Ae=>Ae.id!==D)),onClickToast:D=>{D.targetKey&&r(Yt(D.targetKey))}}),s.jsx("style",{children:`
90
90
  @keyframes toast-in {
91
91
  from { opacity: 0; transform: translateX(40px); }
92
92
  to { opacity: 1; transform: translateX(0); }
93
93
  }
94
- `})]})}function go(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function dy(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=go();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 Dt(e,t){return await fetch(dy(e),{credentials:"same-origin",...t})}function Vl(){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 uy{constructor(){Ye(this,"adapters",new Map);Ye(this,"states",new Map);Ye(this,"runtimeListeners",new Map);Ye(this,"screenshotCallbacks",new Map);Ye(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,c){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:o,rows:c})}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 Dt(`${a.pathname}${a.search}`);if(!o.ok){let l=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(l=d.error)}catch{}return{success:!1,error:l}}const c=await o.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof c.seq=="number"?c.seq:0,text:typeof c.text=="string"?c.text:"",truncated:!!c.truncated,cols:typeof c.cols=="number"?c.cols:void 0,rows:typeof c.rows=="number"?c.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 Ot=new uy;function fy(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=go();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Pr=fy(),Di=3e3,my=3e4;let Rt=null,py=0;const an=new Map;let Qt=null,tr=null;function Ei(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Vs(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function hy(e){return e==="connected"?"connected":e}async function Ur(e,t,r){const n=Jc(e,r||{}),a=Rt;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++py}_${Date.now()}`;return new Promise((c,l)=>{const d=setTimeout(()=>{an.delete(o),l(new Error(`WS command timeout: ${t}`))},3e4);an.set(o,{resolve:f=>{clearTimeout(d),c(f)},reject:f=>{clearTimeout(d),l(f)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Ma(e,t){const r=Rt;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 xy(e,t,r){const n=Rt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Jc(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 by{constructor(t){Ye(this,"daemonId");Ye(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN}get connectionState(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return Ur(this.daemonId,t,r)}async sendInput(t,r){return Ur(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Qt&&(clearInterval(Qt),Qt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Ur(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());Ot.emitScreenshot(this.daemonId,a)}}catch{}};r(),Qt=setInterval(r,2e3)}stopScreenshots(t){Qt&&(clearInterval(Qt),Qt=null)}}let At=null;function gy(e){return(!At||At.daemonId!==e)&&(At=new by(e)),At}function yy({children:e}){const t=i.useRef(rr()),r=rr();t.current=r;const{setUserName:n}=ds(),a=i.useRef(n);a.current=n;const o=i.useRef(null),c=i.useRef(null),[,l]=i.useState("disconnected"),d=i.useCallback((h,j)=>{l(h),tr==null||tr(h,j)},[]),f=i.useRef(null),u=i.useRef(),p=i.useRef(Di),m=i.useRef(!0),y=i.useRef(!1),N=i.useRef("initial_connect");return i.useEffect(()=>{m.current=!0,y.current=!1;function h(){var b,v;if(!m.current||((b=f.current)==null?void 0:b.readyState)===WebSocket.OPEN||((v=f.current)==null?void 0:v.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Pr}...`),Vs("connect_attempt",{url:Pr,reason:N.current,delayMs:p.current});let x;try{x=new WebSocket(Pr)}catch(A){console.error("[Standalone WS] Failed to create WebSocket:",A),j();return}f.current=x,x.onopen=()=>{if(!m.current){x.close();return}d("connected"),p.current=Di,Vs("open",{url:Pr,reason:N.current}),Ht.resubscribeAll({sendData:Ma}),console.log("[Standalone WS] Connected")},Rt=x,x.onmessage=A=>{var g,M;try{const T=JSON.parse(A.data);if((T.type==="command_result"||T.type==="error")&&T.requestId){const k=an.get(T.requestId);k&&(an.delete(T.requestId),T.type==="error"?k.reject(new Error(((g=T.data)==null?void 0:g.message)||"Command failed")):k.resolve(T.data));return}if(T.type==="session_output"){const k=T.sessionId||T.cliId||T.cliType;k&&Ot.emitSessionOutput(k,typeof T.data=="string"?T.data:"",typeof T.seq=="number"?T.seq:void 0);return}if(T.type==="runtime_snapshot"){Ot.emitRuntimeSnapshot(T.sessionId,typeof T.text=="string"?T.text:"",typeof T.seq=="number"?T.seq:0,!!T.truncated,typeof T.cols=="number"?T.cols:void 0,typeof T.rows=="number"?T.rows:void 0);return}if(T.type==="topic_update"){const k=T.update;k&&Ht.publish(k);return}if(T.type==="status"||T.type==="initial_state"){const k=T.data;if(!k)return;const{injectEntries:w,markLoaded:K,getIdes:R}=t.current,S=k.instanceId||"standalone",O=R().find(C=>C.id===S),U=gy(S);Ot.register(S,U),Ot.setState(S,"connected"),d("connected",S),Ot.emitStatus(S,k);const P=Zr(k,{daemonId:S,existingDaemon:O,existingEntries:R()});Ei("ws_status",{type:T.type,daemonId:S,sessions:(k.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:(k.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),Ei("entries",{daemonId:S,entries:P.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}))}),P.length>0&&w(P,{authoritativeDaemonIds:[S]}),K(),c.current!==S&&((M=o.current)==null||M.call(o),c.current=S,o.current=Ht.subscribe({sendData:Ma},S,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${S}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const I=t.current.getIdes(),W=I.find($=>$.id===S),E=Zr(C.status,{daemonId:S,existingDaemon:W,existingEntries:I,timestamp:C.timestamp});E.length>0&&t.current.injectEntries(E,{authoritativeDaemonIds:[S]}),C.userName&&a.current&&a.current(C.userName)}))}}catch(T){console.error("[Standalone WS] Parse error:",T)}},x.onclose=A=>{m.current&&(At==null||At.stopScreenshots(),At&&Ot.setState(At.daemonId,"disconnected"),d("disconnected"),f.current=null,N.current=`close:${A.code}${A.wasClean?":clean":":unclean"}`,Vs("close",{code:A.code,reason:A.reason||"",wasClean:A.wasClean}),j())},x.onerror=A=>{y.current||!m.current||(N.current="error",Vs("error",{message:A instanceof Event?"event":String(A),readyState:x.readyState}),console.warn("[Standalone WS] Error, will reconnect:",A))}}function j(){if(!m.current)return;clearTimeout(u.current);const x=p.current;console.log(`[Standalone WS] Reconnecting in ${x}ms...`),Vs("schedule_reconnect",{reason:N.current,delayMs:x}),u.current=setTimeout(()=>{p.current=Math.min(p.current*1.5,my),h()},x)}return h(),()=>{var x;m.current=!1,y.current=!0,(x=o.current)==null||x.call(o),o.current=null,c.current=null,clearTimeout(u.current),f.current&&(f.current.onerror=null,f.current.onclose=null,f.current.close(),f.current=null,Rt=null),At&&(At.stopScreenshots(),Ot.unregister(At.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function vy({children:e}){const[t,r]=i.useState("disconnected"),[n,a]=i.useState(null);i.useEffect(()=>(tr=(c,l)=>{r(c),l&&a(l)},()=>{tr=null}),[]);const o=i.useMemo(()=>{const c=t==="connected",l=hy(t),d={};return n&&(d[n]=l),d.standalone=l,{wsStatus:t,isConnected:c,connectionStates:d}},[t,n]);return s.jsx(zd,{connectionOverrides:o,children:s.jsx(yy,{children:e})})}const Gl="adhdev_standalone_font_preferences",ls={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},vn=[{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"}],cr=[{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"}],wy=new Set(vn.map(e=>e.id)),jy=new Set(cr.map(e=>e.id));function $t(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:zr("chat",t.chat),code:zr("code",t.code),terminal:zr("terminal",t.terminal)}}function zr(e,t){const r=ls[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"?wy:jy).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function Vr(e,t){var a;const r=zr(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?vn:cr;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function ky(e){const t=$t(e),r=Vr("chat",t.chat),n=Vr("code",t.code),a=Vr("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function es(e,t=document.documentElement){const r=$t(e),n=ky(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function Aa(e){const t=$t(e);try{localStorage.setItem(Gl,JSON.stringify(t))}catch{}return t}function Sy(){try{const e=localStorage.getItem(Gl);if(e)return $t(JSON.parse(e))}catch{}return ls}function Ny(){return es(Sy())}function Gs(e,t){var n;const r=e==="chat"?vn:cr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const Cy=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Gi,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(us,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:s.jsx(on,{}),label:"Settings"}];function Ty({children:e}){const t=Ps(),r=La(),n=i.useMemo(()=>Cy.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(Yi,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Xi,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(zp,{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.59"]}),footerActions:({collapsed:o,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${o?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,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 My=[{icon:s.jsx(us,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ut,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Ji,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Tt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(ar,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Yi,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Ay=[{icon:s.jsx(ou,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Gi,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(cn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(eu,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(qi,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(su,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Iy=[{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 Ly(){return s.jsxs(tl,{icon:s.jsx(Xi,{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.59"]}),children:[s.jsx(Nt,{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(Nt,{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:My.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(Nt,{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:Qc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:el.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Zc.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(Nt,{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:Ay.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(Nt,{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:Iy.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(rl,{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(xu,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function ra(e,t,r){return{...e,[t]:r}}function na({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:c=>{const l=c.target.value;o(l==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:l})},children:a.map(c=>s.jsx("option",{value:c.id,children:c.label},c.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:c=>o({preset:"custom",customFamily:c.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:Vr(e,n)})]})]})]})}function Ry({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:o,onSave:c,onResetToSaved:l,onResetToDefaults:d}){const f=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(na,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:vn,onChange:u=>o(ra(e,"chat",u))}),s.jsx(na,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:cr,onChange:u=>o(ra(e,"code",u))}),s.jsx(na,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:cr,onChange:u=>o(ra(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: ",Gs("chat",e.chat.preset)," · Code: ",Gs("code",e.code.preset)," · Terminal: ",Gs("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Gs("chat",ls.chat.preset)," / ",Gs("code",ls.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:c,disabled:r||!f,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:l,disabled:r||!f,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 _y(){const{ides:e}=ds(),t=e.find(X=>X.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=mt(),{userName:a}=ds(),[o,c]=i.useState(a||""),[l,d]=i.useState(null),[f,u]=i.useState(null),[p,m]=i.useState(ls),[y,N]=i.useState(!1),[h,j]=i.useState(""),[x,b]=i.useState(""),[v,A]=i.useState("127.0.0.1"),[g,M]=i.useState(""),[T,k]=i.useState(""),[w,K]=i.useState(""),[R,S]=i.useState(""),[O,U]=i.useState(""),[P,C]=i.useState(!1),I=async()=>{const ae=await(await Dt("/auth/session")).json();d(ae)},W=async()=>{const ae=await(await Dt("/api/v1/standalone/preferences")).json();u(ae),A(ae.standaloneBindHost);const ge=$t(ae.standaloneFontPreferences);m(ge),es(ge),Aa(ge)};i.useEffect(()=>{a!==void 0&&c(a)},[a]),i.useEffect(()=>{Promise.all([I(),W()]).catch(X=>{S(X instanceof Error?X.message:String(X))})},[]),i.useEffect(()=>{es(p)},[p]);const E=X=>{const ae=X.target.value.trim();t!=null&&t.id&&ae!==a&&n(t.id,"set_user_name",{userName:ae}).catch(console.error)},[$,F]=i.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),J=X=>{F(X);try{localStorage.setItem("adhdev_sound",X?"1":"0")}catch{}},he=async()=>{j(""),b(""),N(!0);try{const X=$t(p),ae=await Dt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:X})}),ge=await ae.json();if(!ae.ok)throw new Error((ge==null?void 0:ge.error)||"Failed to save standalone font preferences");const ee=$t(ge.standaloneFontPreferences);u(ge),m(ee),es(ee),Aa(ee),b("Standalone chat fonts saved for this self-hosted dashboard.")}catch(X){j(X instanceof Error?X.message:String(X))}finally{N(!1)}},le=()=>{const X=$t(f==null?void 0:f.standaloneFontPreferences);j(""),b(""),m(X),es(X)},te=()=>{j(""),b(""),m(ls),es(ls)},ye=async()=>{S(""),U(""),C(!0);try{const X=await Dt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:v})}),ae=await X.json();if(!X.ok)throw new Error((ae==null?void 0:ae.error)||"Failed to save standalone network preference");u(ae),A(ae.standaloneBindHost),U(ae.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){S(X instanceof Error?X.message:String(X))}finally{C(!1)}},fe=async()=>{if(S(""),U(""),T.trim().length<4){S("Password must be at least 4 characters.");return}if(T!==w){S("New password and confirmation do not match.");return}C(!0);try{const X=await Dt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:g,newPassword:T})}),ae=await X.json();if(!X.ok)throw new Error((ae==null?void 0:ae.error)||"Failed to save password");d(ae),await W(),M(""),k(""),K(""),U(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Vl()}catch(X){S(X instanceof Error?X.message:String(X))}finally{C(!1)}},be=async()=>{S(""),U(""),C(!0);try{const X=await Dt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:g,clear:!0})}),ae=await X.json();if(!X.ok)throw new Error((ae==null?void 0:ae.error)||"Failed to clear password");d(ae),await W(),M(""),k(""),K(""),U("Standalone password disabled.")}catch(X){S(X instanceof Error?X.message:String(X))}finally{C(!1)}};return s.jsxs(tl,{icon:s.jsx(on,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(Cr,{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."}),(l==null?void 0:l.publicHostWarning)&&s.jsx(Cr,{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(Nt,{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.59"]}),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:(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Default bind"}),s.jsx("span",{className:"font-mono text-xs",children:(f==null?void 0:f.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(Nt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:v==="127.0.0.1",onChange:()=>A("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:v==="0.0.0.0",onChange:()=>A("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:()=>{ye()},disabled:P,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:P?"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 ",(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(Nt,{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:l!=null&&l.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."}),R&&s.jsx(Cr,{variant:"error",children:R}),O&&s.jsx(Cr,{variant:"success",children:O}),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:l!=null&&l.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:g,onChange:X=>M(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:l!=null&&l.hasPasswordAuth?"New password":"New standalone password",value:T,onChange:X=>k(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=>K(X.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{fe()},disabled:P,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:P?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{be()},disabled:P,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(Nt,{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(Nt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(eh,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(Nt,{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(nh,{})]}),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(fh,{})]}),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(Ry,{value:p,savedValue:$t(f==null?void 0:f.standaloneFontPreferences),saving:y,error:h,notice:x,onChange:m,onSave:()=>{he()},onResetToSaved:le,onResetToDefaults:te})]}),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(hh,{})]})]})}),s.jsx(Nt,{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(Jp,{}),s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(hu,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:$,onChange:J})]})}),s.jsx(Nt,{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(Zd,{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=>c(X.target.value),onBlur:E,onKeyDown:X=>{X.key==="Enter"&&X.currentTarget.blur()}})]})})})]})}Hp();dh();Ny();const Py=Ui({baseUrl:"",getToken:go});function Dy({children:e}){const[t,r]=i.useState(null),[n,a]=i.useState(!0),[o,c]=i.useState(""),[l,d]=i.useState(""),[f,u]=i.useState(!1),p=async()=>{a(!0),d("");try{const N=await(await Dt("/auth/session")).json();r(N)}catch(y){d(y instanceof Error?y.message:String(y))}finally{a(!1)}};i.useEffect(()=>{p()},[]),i.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let y=!1;return(async()=>{try{const N=await Dt("/api/v1/standalone/preferences");if(!N.ok)return;const h=await N.json();if(y)return;const j=$t(h.standaloneFontPreferences);es(j),Aa(j)}catch{}})(),()=>{y=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const m=async y=>{y.preventDefault(),u(!0),d("");try{const N=await Dt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),h=await N.json();if(!N.ok)throw new Error((h==null?void 0:h.error)||"Login failed");r(h),c(""),Vl()}catch(N){d(N instanceof Error?N.message:String(N))}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:m,children:[s.jsx("input",{type:"password",value:o,onChange:y=>c(y.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:f||!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:f?"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."}),l&&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:l})]})}):s.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",l||"unknown error"]})}function $i(){const{ides:e,initialLoaded:t}=ds();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(ia,{to:`/machines/${r.id}`,replace:!0}):s.jsx(ia,{to:"/dashboard",replace:!0})}function Ey(){const e=i.useMemo(()=>({sendCommand:Ur,sendData:Ma,sendPtyInput:xy}),[]);return s.jsx(Md,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(qd,{client:Py,children:s.jsx(Dy,{children:s.jsx(vy,{children:s.jsx(Xd,{value:e,children:s.jsx(Ty,{children:s.jsxs(Ad,{children:[s.jsx(Xt,{path:"/dashboard",element:s.jsx(rg,{})}),s.jsx(Xt,{path:"/machine",element:s.jsx($i,{})}),s.jsx(Xt,{path:"/machines/:id",element:s.jsx(ly,{})}),s.jsx(Xt,{path:"/machines",element:s.jsx($i,{})}),s.jsx(Xt,{path:"/about",element:s.jsx(Ly,{})}),s.jsx(Xt,{path:"/settings",element:s.jsx(_y,{})}),s.jsx(Xt,{path:"*",element:s.jsx(ia,{to:"/dashboard",replace:!0})})]})})})})})})})}np({connectionManager:Ot});Id(document.getElementById("root")).render(s.jsx(Ey,{}));
94
+ `})]})}function go(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function uy(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=go();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 Dt(e,t){return await fetch(uy(e),{credentials:"same-origin",...t})}function Gl(){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 fy{constructor(){Ye(this,"adapters",new Map);Ye(this,"states",new Map);Ye(this,"runtimeListeners",new Map);Ye(this,"screenshotCallbacks",new Map);Ye(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,c){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:o,rows:c})}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 Dt(`${a.pathname}${a.search}`);if(!o.ok){let l=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(l=d.error)}catch{}return{success:!1,error:l}}const c=await o.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof c.seq=="number"?c.seq:0,text:typeof c.text=="string"?c.text:"",truncated:!!c.truncated,cols:typeof c.cols=="number"?c.cols:void 0,rows:typeof c.rows=="number"?c.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 Ot=new fy;function my(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=go();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Pr=my(),Di=3e3,py=3e4;let Rt=null,hy=0;const an=new Map;let Qt=null,tr=null;function Ei(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Vs(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function xy(e){return e==="connected"?"connected":e}async function Ur(e,t,r){const n=Qc(e,r||{}),a=Rt;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++hy}_${Date.now()}`;return new Promise((c,l)=>{const d=setTimeout(()=>{an.delete(o),l(new Error(`WS command timeout: ${t}`))},3e4);an.set(o,{resolve:f=>{clearTimeout(d),c(f)},reject:f=>{clearTimeout(d),l(f)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Ma(e,t){const r=Rt;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 by(e,t,r){const n=Rt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Qc(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 gy{constructor(t){Ye(this,"daemonId");Ye(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN}get connectionState(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return Ur(this.daemonId,t,r)}async sendInput(t,r){return Ur(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Qt&&(clearInterval(Qt),Qt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Ur(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());Ot.emitScreenshot(this.daemonId,a)}}catch{}};r(),Qt=setInterval(r,2e3)}stopScreenshots(t){Qt&&(clearInterval(Qt),Qt=null)}}let At=null;function yy(e){return(!At||At.daemonId!==e)&&(At=new gy(e)),At}function vy({children:e}){const t=i.useRef(rr()),r=rr();t.current=r;const{setUserName:n}=ds(),a=i.useRef(n);a.current=n;const o=i.useRef(null),c=i.useRef(null),[,l]=i.useState("disconnected"),d=i.useCallback((h,j)=>{l(h),tr==null||tr(h,j)},[]),f=i.useRef(null),u=i.useRef(),p=i.useRef(Di),m=i.useRef(!0),y=i.useRef(!1),N=i.useRef("initial_connect");return i.useEffect(()=>{m.current=!0,y.current=!1;function h(){var b,v;if(!m.current||((b=f.current)==null?void 0:b.readyState)===WebSocket.OPEN||((v=f.current)==null?void 0:v.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Pr}...`),Vs("connect_attempt",{url:Pr,reason:N.current,delayMs:p.current});let x;try{x=new WebSocket(Pr)}catch(A){console.error("[Standalone WS] Failed to create WebSocket:",A),j();return}f.current=x,x.onopen=()=>{if(!m.current){x.close();return}d("connected"),p.current=Di,Vs("open",{url:Pr,reason:N.current}),Ht.resubscribeAll({sendData:Ma}),console.log("[Standalone WS] Connected")},Rt=x,x.onmessage=A=>{var g,M;try{const T=JSON.parse(A.data);if((T.type==="command_result"||T.type==="error")&&T.requestId){const k=an.get(T.requestId);k&&(an.delete(T.requestId),T.type==="error"?k.reject(new Error(((g=T.data)==null?void 0:g.message)||"Command failed")):k.resolve(T.data));return}if(T.type==="session_output"){const k=T.sessionId||T.cliId||T.cliType;k&&Ot.emitSessionOutput(k,typeof T.data=="string"?T.data:"",typeof T.seq=="number"?T.seq:void 0);return}if(T.type==="runtime_snapshot"){Ot.emitRuntimeSnapshot(T.sessionId,typeof T.text=="string"?T.text:"",typeof T.seq=="number"?T.seq:0,!!T.truncated,typeof T.cols=="number"?T.cols:void 0,typeof T.rows=="number"?T.rows:void 0);return}if(T.type==="topic_update"){const k=T.update;k&&Ht.publish(k);return}if(T.type==="status"||T.type==="initial_state"){const k=T.data;if(!k)return;const{injectEntries:w,markLoaded:K,getIdes:R}=t.current,S=k.instanceId||"standalone",O=R().find(C=>C.id===S),H=yy(S);Ot.register(S,H),Ot.setState(S,"connected"),d("connected",S),Ot.emitStatus(S,k);const P=Zr(k,{daemonId:S,existingDaemon:O,existingEntries:R()});Ei("ws_status",{type:T.type,daemonId:S,sessions:(k.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:(k.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),Ei("entries",{daemonId:S,entries:P.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}))}),P.length>0&&w(P,{authoritativeDaemonIds:[S]}),K(),c.current!==S&&((M=o.current)==null||M.call(o),c.current=S,o.current=Ht.subscribe({sendData:Ma},S,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${S}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const I=t.current.getIdes(),W=I.find($=>$.id===S),E=Zr(C.status,{daemonId:S,existingDaemon:W,existingEntries:I,timestamp:C.timestamp});E.length>0&&t.current.injectEntries(E,{authoritativeDaemonIds:[S]}),C.userName&&a.current&&a.current(C.userName)}))}}catch(T){console.error("[Standalone WS] Parse error:",T)}},x.onclose=A=>{m.current&&(At==null||At.stopScreenshots(),At&&Ot.setState(At.daemonId,"disconnected"),d("disconnected"),f.current=null,N.current=`close:${A.code}${A.wasClean?":clean":":unclean"}`,Vs("close",{code:A.code,reason:A.reason||"",wasClean:A.wasClean}),j())},x.onerror=A=>{y.current||!m.current||(N.current="error",Vs("error",{message:A instanceof Event?"event":String(A),readyState:x.readyState}),console.warn("[Standalone WS] Error, will reconnect:",A))}}function j(){if(!m.current)return;clearTimeout(u.current);const x=p.current;console.log(`[Standalone WS] Reconnecting in ${x}ms...`),Vs("schedule_reconnect",{reason:N.current,delayMs:x}),u.current=setTimeout(()=>{p.current=Math.min(p.current*1.5,py),h()},x)}return h(),()=>{var x;m.current=!1,y.current=!0,(x=o.current)==null||x.call(o),o.current=null,c.current=null,clearTimeout(u.current),f.current&&(f.current.onerror=null,f.current.onclose=null,f.current.close(),f.current=null,Rt=null),At&&(At.stopScreenshots(),Ot.unregister(At.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function wy({children:e}){const[t,r]=i.useState("disconnected"),[n,a]=i.useState(null);i.useEffect(()=>(tr=(c,l)=>{r(c),l&&a(l)},()=>{tr=null}),[]);const o=i.useMemo(()=>{const c=t==="connected",l=xy(t),d={};return n&&(d[n]=l),d.standalone=l,{wsStatus:t,isConnected:c,connectionStates:d}},[t,n]);return s.jsx(Vd,{connectionOverrides:o,children:s.jsx(vy,{children:e})})}const ql="adhdev_standalone_font_preferences",ls={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},vn=[{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"}],cr=[{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"}],jy=new Set(vn.map(e=>e.id)),ky=new Set(cr.map(e=>e.id));function $t(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:zr("chat",t.chat),code:zr("code",t.code),terminal:zr("terminal",t.terminal)}}function zr(e,t){const r=ls[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"?jy:ky).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function Vr(e,t){var a;const r=zr(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?vn:cr;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function Sy(e){const t=$t(e),r=Vr("chat",t.chat),n=Vr("code",t.code),a=Vr("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function es(e,t=document.documentElement){const r=$t(e),n=Sy(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function Aa(e){const t=$t(e);try{localStorage.setItem(ql,JSON.stringify(t))}catch{}return t}function Ny(){try{const e=localStorage.getItem(ql);if(e)return $t(JSON.parse(e))}catch{}return ls}function Cy(){return es(Ny())}function Gs(e,t){var n;const r=e==="chat"?vn:cr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const Ty=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Gi,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(us,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:s.jsx(on,{}),label:"Settings"}];function My({children:e}){const t=Ps(),r=La(),n=i.useMemo(()=>Ty.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(Yi,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Xi,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Vp,{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.60"]}),footerActions:({collapsed:o,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${o?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,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 Ay=[{icon:s.jsx(us,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ut,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Ji,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Tt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(ar,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Yi,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Iy=[{icon:s.jsx(iu,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Gi,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(cn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(tu,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(qi,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(ru,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Ly=[{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 Ry(){return s.jsxs(sl,{icon:s.jsx(Xi,{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.60"]}),children:[s.jsx(Nt,{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(Nt,{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:Ay.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(Nt,{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:Zc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:tl.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:el.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(Nt,{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:Iy.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(Nt,{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:Ly.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(nl,{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(bu,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function ra(e,t,r){return{...e,[t]:r}}function na({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:c=>{const l=c.target.value;o(l==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:l})},children:a.map(c=>s.jsx("option",{value:c.id,children:c.label},c.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:c=>o({preset:"custom",customFamily:c.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:Vr(e,n)})]})]})]})}function _y({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:o,onSave:c,onResetToSaved:l,onResetToDefaults:d}){const f=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(na,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:vn,onChange:u=>o(ra(e,"chat",u))}),s.jsx(na,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:cr,onChange:u=>o(ra(e,"code",u))}),s.jsx(na,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:cr,onChange:u=>o(ra(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: ",Gs("chat",e.chat.preset)," · Code: ",Gs("code",e.code.preset)," · Terminal: ",Gs("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Gs("chat",ls.chat.preset)," / ",Gs("code",ls.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:c,disabled:r||!f,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:l,disabled:r||!f,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 Py(){const{ides:e}=ds(),t=e.find(X=>X.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=mt(),{userName:a}=ds(),[o,c]=i.useState(a||""),[l,d]=i.useState(null),[f,u]=i.useState(null),[p,m]=i.useState(ls),[y,N]=i.useState(!1),[h,j]=i.useState(""),[x,b]=i.useState(""),[v,A]=i.useState("127.0.0.1"),[g,M]=i.useState(""),[T,k]=i.useState(""),[w,K]=i.useState(""),[R,S]=i.useState(""),[O,H]=i.useState(""),[P,C]=i.useState(!1),I=async()=>{const ae=await(await Dt("/auth/session")).json();d(ae)},W=async()=>{const ae=await(await Dt("/api/v1/standalone/preferences")).json();u(ae),A(ae.standaloneBindHost);const ge=$t(ae.standaloneFontPreferences);m(ge),es(ge),Aa(ge)};i.useEffect(()=>{a!==void 0&&c(a)},[a]),i.useEffect(()=>{Promise.all([I(),W()]).catch(X=>{S(X instanceof Error?X.message:String(X))})},[]),i.useEffect(()=>{es(p)},[p]);const E=X=>{const ae=X.target.value.trim();t!=null&&t.id&&ae!==a&&n(t.id,"set_user_name",{userName:ae}).catch(console.error)},[$,z]=i.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),J=X=>{z(X);try{localStorage.setItem("adhdev_sound",X?"1":"0")}catch{}},he=async()=>{j(""),b(""),N(!0);try{const X=$t(p),ae=await Dt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:X})}),ge=await ae.json();if(!ae.ok)throw new Error((ge==null?void 0:ge.error)||"Failed to save standalone font preferences");const ee=$t(ge.standaloneFontPreferences);u(ge),m(ee),es(ee),Aa(ee),b("Standalone chat fonts saved for this self-hosted dashboard.")}catch(X){j(X instanceof Error?X.message:String(X))}finally{N(!1)}},ce=()=>{const X=$t(f==null?void 0:f.standaloneFontPreferences);j(""),b(""),m(X),es(X)},te=()=>{j(""),b(""),m(ls),es(ls)},ye=async()=>{S(""),H(""),C(!0);try{const X=await Dt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:v})}),ae=await X.json();if(!X.ok)throw new Error((ae==null?void 0:ae.error)||"Failed to save standalone network preference");u(ae),A(ae.standaloneBindHost),H(ae.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){S(X instanceof Error?X.message:String(X))}finally{C(!1)}},fe=async()=>{if(S(""),H(""),T.trim().length<4){S("Password must be at least 4 characters.");return}if(T!==w){S("New password and confirmation do not match.");return}C(!0);try{const X=await Dt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:g,newPassword:T})}),ae=await X.json();if(!X.ok)throw new Error((ae==null?void 0:ae.error)||"Failed to save password");d(ae),await W(),M(""),k(""),K(""),H(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Gl()}catch(X){S(X instanceof Error?X.message:String(X))}finally{C(!1)}},be=async()=>{S(""),H(""),C(!0);try{const X=await Dt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:g,clear:!0})}),ae=await X.json();if(!X.ok)throw new Error((ae==null?void 0:ae.error)||"Failed to clear password");d(ae),await W(),M(""),k(""),K(""),H("Standalone password disabled.")}catch(X){S(X instanceof Error?X.message:String(X))}finally{C(!1)}};return s.jsxs(sl,{icon:s.jsx(on,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(Cr,{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."}),(l==null?void 0:l.publicHostWarning)&&s.jsx(Cr,{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(Nt,{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.60"]}),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:(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Default bind"}),s.jsx("span",{className:"font-mono text-xs",children:(f==null?void 0:f.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(Nt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:v==="127.0.0.1",onChange:()=>A("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:v==="0.0.0.0",onChange:()=>A("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:()=>{ye()},disabled:P,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:P?"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 ",(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(Nt,{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:l!=null&&l.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."}),R&&s.jsx(Cr,{variant:"error",children:R}),O&&s.jsx(Cr,{variant:"success",children:O}),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:l!=null&&l.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:g,onChange:X=>M(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:l!=null&&l.hasPasswordAuth?"New password":"New standalone password",value:T,onChange:X=>k(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=>K(X.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{fe()},disabled:P,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:P?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{be()},disabled:P,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(Nt,{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(Nt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(th,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(Nt,{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(ah,{})]}),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(mh,{})]}),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(_y,{value:p,savedValue:$t(f==null?void 0:f.standaloneFontPreferences),saving:y,error:h,notice:x,onChange:m,onSave:()=>{he()},onResetToSaved:ce,onResetToDefaults:te})]}),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(xh,{})]})]})}),s.jsx(Nt,{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(Qp,{}),s.jsx(Zt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xu,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:$,onChange:J})]})}),s.jsx(Nt,{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(eu,{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=>c(X.target.value),onBlur:E,onKeyDown:X=>{X.key==="Enter"&&X.currentTarget.blur()}})]})})})]})}Up();uh();Cy();const Dy=Ui({baseUrl:"",getToken:go});function Ey({children:e}){const[t,r]=i.useState(null),[n,a]=i.useState(!0),[o,c]=i.useState(""),[l,d]=i.useState(""),[f,u]=i.useState(!1),p=async()=>{a(!0),d("");try{const N=await(await Dt("/auth/session")).json();r(N)}catch(y){d(y instanceof Error?y.message:String(y))}finally{a(!1)}};i.useEffect(()=>{p()},[]),i.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let y=!1;return(async()=>{try{const N=await Dt("/api/v1/standalone/preferences");if(!N.ok)return;const h=await N.json();if(y)return;const j=$t(h.standaloneFontPreferences);es(j),Aa(j)}catch{}})(),()=>{y=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const m=async y=>{y.preventDefault(),u(!0),d("");try{const N=await Dt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),h=await N.json();if(!N.ok)throw new Error((h==null?void 0:h.error)||"Login failed");r(h),c(""),Gl()}catch(N){d(N instanceof Error?N.message:String(N))}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:m,children:[s.jsx("input",{type:"password",value:o,onChange:y=>c(y.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:f||!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:f?"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."}),l&&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:l})]})}):s.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",l||"unknown error"]})}function $i(){const{ides:e,initialLoaded:t}=ds();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(ia,{to:`/machines/${r.id}`,replace:!0}):s.jsx(ia,{to:"/dashboard",replace:!0})}function $y(){const e=i.useMemo(()=>({sendCommand:Ur,sendData:Ma,sendPtyInput:by}),[]);return s.jsx(Ad,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Yd,{client:Dy,children:s.jsx(Ey,{children:s.jsx(wy,{children:s.jsx(Jd,{value:e,children:s.jsx(My,{children:s.jsxs(Id,{children:[s.jsx(Xt,{path:"/dashboard",element:s.jsx(ng,{})}),s.jsx(Xt,{path:"/machine",element:s.jsx($i,{})}),s.jsx(Xt,{path:"/machines/:id",element:s.jsx(dy,{})}),s.jsx(Xt,{path:"/machines",element:s.jsx($i,{})}),s.jsx(Xt,{path:"/about",element:s.jsx(Ry,{})}),s.jsx(Xt,{path:"/settings",element:s.jsx(Py,{})}),s.jsx(Xt,{path:"*",element:s.jsx(ia,{to:"/dashboard",replace:!0})})]})})})})})})})}ap({connectionManager:Ot});Ld(document.getElementById("root")).render(s.jsx($y,{}));